Exemplo n.º 1
0
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var expired = ExpiresIn != 0 ? DateTime.Now >= _lastAuthenticateDateTime.AddSeconds(ExpiresIn) : false;

            if (!_isAuthenticated || expired)
            {
                var tokenRequest = new RestRequest(tokenUri = (new Uri(client.BaseUrl, TokenEndPoint)).ToString(), Method.POST);
                tokenRequest.AddHeader("content-type", "application/x-www-form-urlencoded");
                if (_credentials is PasswordCredentials && !expired)
                {
                    var passwordCredentials = (PasswordCredentials)_credentials;
                    tokenRequest.AddObject(new
                    {
                        client_id     = passwordCredentials.ClientId,
                        client_secret = passwordCredentials.ClientSecret,
                        passwordCredentials.UserName,
                        passwordCredentials.Password,
                        grant_type = PasswordCredentialsGrantType
                    });
                }
                else
                {
                    tokenRequest.AddObject(new
                    {
                        client_id     = _credentials.ClientId,
                        client_secret = _credentials.ClientSecret,
                        grant_type    = ClientCredentialsGrantType
                    });
                    IsUserAuthenticated = false;
                    CurrentUser         = null;
                }

                var response = tokenClient.Execute(tokenRequest);
                response.ThrowExceptionOnResponseError();
                var oAuthReponse = tokenClient.Deserialize <OAuthReponse>(response).Data;

                _lastAuthenticateDateTime = DateTime.Now;
                _isAuthenticated          = true;
                _accessToken  = oAuthReponse.BearerToken;
                _refreshToken = oAuthReponse.RefreshToken;
                ExpiresIn     = oAuthReponse.ExpiresIn;

                if (_credentials is PasswordCredentials)
                {
                    IsUserAuthenticated = true;
                    var token = new JwtSecurityToken(oAuthReponse.BearerToken);
                    CurrentUser = new UserModel
                    {
                        Id   = int.Parse(token.Claims.First(x => x.Type == "Id").Value),
                        Name = token.Claims.First(x => x.Type == "Name").Value
                    };
                }
            }

            request.AddHeader("Authorization", string.Format("Bearer {0}", _accessToken));
        }
Exemplo n.º 2
0
        public void SetRestResponseFromCache <T>(IRestClient client, IRestResponse <T> response, IRestRequest request, Method method = Method.GET)
        {
            if (method != Method.GET || request.Method != Method.GET)
            {
                return;
            }
            CheckCacheByUri(client, request, out CacheEntry etag);

            // the data SHOULD be there just let them deal with it.
            if (etag.Data == null)
            {
                return;
            }
            // this part is tricky, since we emulate the RestRequest serialize
            var contentEncoding = etag.ContentEncoding != null?Encoding.UTF8.GetString(etag.ContentEncoding) : "utf-8";

            var contentType = etag.ContentType != null?Encoding.UTF8.GetString(etag.ContentType) : null;

            response.RawBytes        = etag.Data;
            response.ContentEncoding = contentEncoding;
            response.ContentLength   = etag.Data.LongLength;
            response.ContentType     = contentType;
            response.ResponseUri     = new Uri(MEMORY_CACHE_URI);
            response.Data            = client.Deserialize <T>(response).Data;
        }
Exemplo n.º 3
0
        public IRestResponse <T> RestResponseFromCache <T>(IRestClient client, IRestRequest request, Method method = Method.GET)
        {
            if (method != Method.GET || request.Method != Method.GET)
            {
                return(null);
            }
            CheckCacheByUri(client, request, out CacheEntry etag);

            // the data is there, we allowed cache so that takes precedence
            if (etag.HasExpires == true)
            {
                // this part is tricky, since we emulate the RestRequest serialize
                var contentEncoding = etag.ContentEncoding != null?Encoding.UTF8.GetString(etag.ContentEncoding) : "utf-8";

                var raw = new RestResponse()
                {
                    RawBytes        = etag.Data,
                    ContentEncoding = contentEncoding,
                    ContentLength   = etag.Data.LongLength,
                    StatusCode      = HttpStatusCode.NotModified,
                    ResponseStatus  = ResponseStatus.None,
                    Request         = request,
                    ContentType     = etag.ContentType != null?Encoding.UTF8.GetString(etag.ContentType) : null,
                                          ResponseUri = new Uri(MEMORY_CACHE_URI)
                };

                return(client.Deserialize <T>(raw));
            }
            return(null);
        }
Exemplo n.º 4
0
        public static RestResponse <dynamic> ExecuteDynamic(this IRestClient client, IRestRequest request)
        {
            var     response = client.Execute <dynamic>(request);
            var     generic  = (RestResponse <dynamic>)response;
            dynamic content  = client.Deserialize <object>(response);

            generic.Data = content;

            return(generic);
        }
        private static LanguageToolResponse CheckGrammar(IRestClient client, string text)
        {
            var request = new RestRequest("check", Method.POST);

            request.AddParameter("language", "es");
            request.AddParameter("text", text);

            var response = client.Execute(request);

            return(client.Deserialize <LanguageToolResponse>(response).Data);
        }
Exemplo n.º 6
0
        public TEntity GetRecordById <TEntity>(int id) where TEntity : EntityBase
        {
            var request = new RestRequest($"data/{GetTableViewName<TEntity>()}/{id}", Method.GET);

            AppendWebsiteIdHeader(request);
            var response = _client.Execute(request);

            response.ThrowExceptionOnResponseError();
            return(_client.Deserialize <TEntity>(response).Data);
        }
Exemplo n.º 7
0
        private static IRestResponse <T> GetJsonResponseWithData <T>(
            IRestResponse <T> response,
            IRestClient client,
            IRestRequest request,
            string content)
        {
            response.Content     = content;
            response.Request     = request;
            response.ContentType = ContentType.Json;
            var responseWithDeserializedData = client.Deserialize <T>(response);

            responseWithDeserializedData.Content = content;
            return(responseWithDeserializedData);
        }
Exemplo n.º 8
0
        internal static async Task <T> DeserializeAsync <T>(this HttpContent content, IRestClient restClient)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            if (restClient == null)
            {
                throw new ArgumentNullException(nameof(restClient));
            }

            using var stream = await content
                               .ReadAsStreamAsync()
                               .ConfigureAwait(false);

            return(restClient.Deserialize <T>(stream));
        }
Exemplo n.º 9
0
 public IRestResponse <T> Deserialize <T>(IRestResponse response)
 {
     return(_innerService.Deserialize <T>(response));
 }
Exemplo n.º 10
0
 public IRestResponse <T> Deserialize <T>(IRestResponse response)
 {
     return(_innerClient.Deserialize <T>(response));
 }