public IActionResult Validate([FromBody] TokenResource resource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Token failed to generate"));
            }

            var user = _userService.FindByUsername(resource.Username);

            if (user == null)
            {
                return(Unauthorized());
            }

            if (!_userService.ValidateUser(user.UserName, resource.Password))
            {
                return(Unauthorized());
            }

            AppLogger.LogResourceRequest(nameof(Validate), user.UserName);

            var token = AppSecurity.GenerateToken(user.Id);

            _userService.StoreAccessToken(token, user.Id);

            return(Ok(token));
        }
Ejemplo n.º 2
0
        public CrayonApiClient(HttpClient httpClient)
        {
            _httpClient             = httpClient;
            _jsonSerializerSettings = new JsonSerializerSettings {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling     = NullValueHandling.Include,
                DefaultValueHandling  = DefaultValueHandling.Include,
                Formatting            = Formatting.Indented
            };

            _assemblyVersion = typeof(CrayonApiClient).GetTypeInfo().Assembly.GetName().Version.ToString();

            Addresses         = new AddressResource(this);
            AgreementProducts = new AgreementProductResource(this);
            Agreements        = new AgreementResource(this);
            BillingStatements = new BillingStatementResource(this);
            BlogItems         = new BlogItemResource(this);
            Clients           = new ClientResource(this);
            CustomerTenants   = new CustomerTenantResource(this);
            InvoiceProfiles   = new InvoiceProfileResource(this);
            Me = new MeResource(this);
            OrganizationAccess = new OrganizationAccessResource(this);
            Organizations      = new OrganizationResource(this);
            Publishers         = new PublisherResource(this);
            Programs           = new ProgramResource(this);
            Regions            = new RegionResource(this);
            Secrets            = new SecretResource(this);
            Subscriptions      = new SubscriptionResource(this);
            Tokens             = new TokenResource(this);
            UsageRecords       = new UsageRecordResource(this);
            Users = new UserResource(this);
        }
Ejemplo n.º 3
0
        public Client(Credentials credentials, IEnvironment env = null)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            environment = env ?? Environments.Production;
            requester   = new Requester(credentials, environment, null, this.apiVersion);

            Account      = new AccountResource(requester);
            Balance      = new BalanceResource(requester);
            Charges      = new ChargeResource(requester);
            Customers    = new CustomerResource(requester);
            Disputes     = new DisputeResource(requester);
            Events       = new EventResource(requester);
            Forex        = new ForexResource(requester);
            Links        = new LinkResource(requester);
            Occurrences  = new OccurrenceResource(requester);
            Sources      = new PaymentSourceResource(requester);
            Receipts     = new ReceiptResource(requester);
            Recipients   = new RecipientResource(requester);
            Refunds      = new RefundResource(requester);
            Schedules    = new ScheduleResource(requester);
            Tokens       = new TokenResource(requester);
            Transactions = new TransactionResource(requester);
            Transfers    = new TransferResource(requester);
        }
Ejemplo n.º 4
0
        public IActionResult CreateToken([FromBody] LoginView login)
        {
            IActionResult response  = Unauthorized();
            var           userInfor = Authenticate(login, out User user, out Role userRole);

            var expiresDate = DateTime.Now.AddHours(12);
            var now         = DateTime.Now;

            if (userInfor != null)
            {
                if (!string.IsNullOrEmpty(user.Token) && user.Expire != null && user.Expire.Value > DateTime.Now)
                {
                    var tokenResource = new TokenResource
                    {
                        Token  = user.Token,
                        Expiry = user.Expire.Value
                    };
                    response = Json(tokenResource);
                }
                else
                {
                    var tokenResource = BuildToken(userInfor, user, userRole, now, expiresDate);
                    response = Json(tokenResource);
                }
            }
            else
            {
                response = Json(new { code = Constant.NotExist, message = Constant.MessageNotExist });
            }

            return(response);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Client for making requests to the API.
        /// </summary>
        /// <param name="authHandler">The authentication handler.</param>
        /// <param name="ctx">The HTTP context to use for this session.</param>
        private Client(Func <CancellationToken, Task <string> > authHandler, HttpContext ctx)
        {
            // Setup resources.
            Assets              = new AssetsResource(authHandler, ctx);
            TimeSeries          = new TimeSeriesResource(authHandler, ctx);
            DataPoints          = new DataPointsResource(authHandler, ctx);
            Events              = new EventsResource(authHandler, ctx);
            Sequences           = new SequencesResource(authHandler, ctx);
            Raw                 = new RawResource(authHandler, ctx);
            Relationships       = new RelationshipResource(authHandler, ctx);
            DataSets            = new DataSetsResource(authHandler, ctx);
            ThreeDModels        = new ThreeDModelsResource(authHandler, ctx);
            ThreeDRevisions     = new ThreeDRevisionsResource(authHandler, ctx);
            ThreeDAssetMappings = new ThreeDAssetMappingsResource(authHandler, ctx);
            Files               = new FilesResource(authHandler, ctx);
            Login               = new LoginResource(authHandler, ctx);
            Token               = new TokenResource(authHandler, ctx);
            ExtPipes            = new ExtPipesResource(authHandler, ctx);
            Labels              = new LabelsResource(authHandler, ctx);
            Groups              = new GroupsResource(authHandler, ctx);

            // Playground features (experimental)
            Playground = new PlaygroundResource(authHandler, ctx);
            // Beta features (experimental)
            Beta = new BetaResource(authHandler, ctx);
        }
Ejemplo n.º 6
0
        public ActionResult <List <IceServer> > GetIceServers()
        {
            const string accountSid = "AC9202a1e5936791dfd6813e4b52ff3ad1";
            const string authToken  = "410134e9dff2193a2d0e471e44d1c8eb";

            TwilioClient.Init(accountSid, authToken);
            var token = TokenResource.Create();

            return(token.IceServers);
        }
Ejemplo n.º 7
0
        public Token GetTokenByResourceUrl(string resourceUrl)
        {
            TokenResource tokenResource = GetTokenResourceFromRequest();

            if (tokenResource != null)
            {
                return(tokenResource.tokens.SingleOrDefault(_token => _token._resource == resourceUrl));
            }
            return(null);
        }
        public IActionResult RefreshToken(TokenResource tokenResources)
        {
            BaseResponse <AccessToken> accessTokenResponse = authenticationService.CreateAccessTokenByRefreshToken(tokenResources.refreshToken);

            if (accessTokenResponse.Success)
            {
                return(Ok(accessTokenResponse.Extra));
            }
            return(BadRequest(accessTokenResponse.ErrorMessage));
        }
Ejemplo n.º 9
0
        public async Task SaveTokensAsync(string code)
        {
            HttpClient client = new HttpClient();

            var tenant      = WebConfigurationManager.AppSettings[OAuth.TENANT];
            var clientId    = WebConfigurationManager.AppSettings[OAuth.CLIENT_ID];
            var redirectUri = WebConfigurationManager.AppSettings[OAuth.REDIRECT_URI];
            var secret      = WebConfigurationManager.AppSettings[OAuth.CLIENT_SECRET];

            var path    = "https://login.microsoftonline.com/" + tenant + "/oauth2/token";
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("redirect_uri", redirectUri), // back to previous url
                new KeyValuePair <string, string>("client_secret", secret),
                new KeyValuePair <string, string>("client_id", clientId),
                new KeyValuePair <string, string>("grant_type", "authorization_code"),
                new KeyValuePair <string, string>("resource", APIResource.SHAREPOINT_CONTEXT),
                new KeyValuePair <string, string>("code", code),
            });

            HttpResponseMessage response = await client.PostAsync(path, content);

            var resultContent2 = await response.Content.ReadAsStringAsync();

            var resultContent = await response.Content.ReadAsAsync <OAuthResponse>();

            TokenResource tokenResource = new TokenResource()
            {
                RefreshToken = resultContent.refresh_token,
                tokens       = new List <Token>(),
            };

            tokenResource.tokens.Add(new Token()
            {
                _accessToken          = resultContent.access_token,
                _resource             = APIResource.SHAREPOINT_CONTEXT,
                _acessTokenExpireTime = DateTime.Now.AddSeconds(resultContent.expires_in).ToString(),
            });

            // add other resource tokens to tokenResource

            Type apiResource = typeof(APIResource);

            foreach (FieldInfo resource in apiResource.GetFields(BindingFlags.Static | BindingFlags.Public))
            {
                var _resource = resource.GetValue(null).ToString();
                if (_resource != APIResource.SHAREPOINT_CONTEXT)
                {
                    Token token = await GetTokenAsync(resultContent.refresh_token, _resource);

                    tokenResource.tokens.Add(token);
                }
            }
            _tokenProvider.SaveTokenResource(tokenResource);
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> Login([FromBody] LoginUserResource loginUserResource)
        {
            if (ModelState.IsValid)
            {
                var user = await this.userManager.FindByEmailAsync(loginUserResource.Email);

                if (user == null || !await this.userManager.CheckPasswordAsync(user, loginUserResource.Password))
                {
                    ModelState.AddModelError("", "Email and password does not match");
                    return(new UnauthorizedObjectResult(new UnAuthorizedResource(ModelState)));
                }
                else if (!user.EmailConfirmed && await this.userManager.CheckPasswordAsync(user, loginUserResource.Password))
                {
                    ModelState.AddModelError("", "Email not confirmed yet");
                    return(new UnauthorizedObjectResult(new UnAuthorizedResource(ModelState)));
                }
                else if (!user.IsActive)
                {
                    ModelState.AddModelError("Auth", "User has disactivated");
                    return(new UnauthorizedObjectResult(new UnAuthorizedResource(ModelState)));
                }

                var result = await this.signInManager.CheckPasswordSignInAsync(user, loginUserResource.Password, false);

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", "Email and password does not match");
                    return(new UnauthorizedObjectResult(new UnAuthorizedResource(ModelState)));
                }
                else
                {
                    var newRefreshToken = new RefreshToken
                    {
                        UserId      = user.Id,
                        AccessToken = await GenerateAccessTokenAsync(user),
                        Token       = Guid.NewGuid().ToString(),
                        CreatedAt   = DateTime.Now
                    };

                    this.refreshTokenRepository.Add(newRefreshToken);

                    await this.unitOfWork.CompleteAsync();

                    var response = new TokenResource()
                    {
                        AccessToken  = newRefreshToken.AccessToken,
                        RefreshToken = newRefreshToken.Token
                    };

                    return(new OkObjectResult(response));
                }
            }

            return(new BadRequestObjectResult(new BadRequestResource(ModelState)));
        }
Ejemplo n.º 11
0
        public IActionResult RevokeRefreshToken(TokenResource tokenResource)
        {
            BaseResponse <AccessToken> accessTokenResponse = this._authenticationService.RevokeRefreshToken(tokenResource.RefreshToken);

            if (accessTokenResponse.Success)
            {
                return(Ok(accessTokenResponse.Extra));
            }

            return(BadRequest(accessTokenResponse.Message));
        }
Ejemplo n.º 12
0
 public TokenResource getToken()
 {
     try
     {
         return(TokenResource.Create());
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Ejemplo n.º 13
0
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken  = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var token = TokenResource.Create(ttl: 3600);

        Console.WriteLine(token.Username);
    }
Ejemplo n.º 14
0
        public void SaveTokenResource(TokenResource tokenResource)
        {
            string accessTokenId = Guid.NewGuid().ToString();

            MemoryCache.Default.Set(accessTokenId, tokenResource, DateTime.Now.AddYears(1));

            HttpCookie tokenCookie = new HttpCookie("token_key");

            tokenCookie.Value   = accessTokenId;
            tokenCookie.Expires = DateTime.Now.AddDays(1);

            HttpContext.Current.Response.Cookies.Add(tokenCookie);

            //string expireTime = DateTime.Now.AddSeconds(expireDuration).ToString();

            //var _token = GetTokenByResourceUrl(resourceUrl);


            //var _token = GetTokenByResourceUrl(resourceUrl);

            //if (_token != null)
            //{
            //    _token._accessToken = token._accessToken;
            //}
            //else
            //{
            //    _token = token;
            //}

            //TokenResource tokenResource = GetTokenResourceFromRequest();
            //if (tokenResource != null)
            //{
            //    if (resourceUrl == APIResource.GRAPH_API)
            //    {
            //        tokenResource.graphApiToken = token;
            //    }
            //    else if (resourceUrl == APIResource.SHAREPOINT_CONTEXT)
            //    {
            //        tokenResource.sharepointToken = token;
            //    }
            //}
            //else
            //{
            //    if (resourceUrl == APIResource.GRAPH_API)
            //    {
            //        tokenResource = new TokenResource() { graphApiToken = token };
            //    }
            //    else if (resourceUrl == APIResource.SHAREPOINT_CONTEXT)
            //    {
            //        tokenResource = new TokenResource() { sharepointToken = token };
            //    }
            //}
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> RevokeRefreshToken(TokenResource tokenResource)
        {
            BaseResponse <AccessToken> accessToken = await _authenticationService.RevokeRefreshToken(tokenResource.RefreshToken);

            if (accessToken.Success)
            {
                return(Ok(accessToken.Extra));
            }
            else
            {
                return(BadRequest(accessToken.ErrorMessage));
            }
        }
Ejemplo n.º 16
0
        public IActionResult RemoveRefreshToken(TokenResource tokenResource)
        {
            TokenResponse tokenResponse = authenticationServices.RevokeRefreshToken(tokenResource.RefreshToken);

            if (tokenResponse.Status)
            {
                return(Ok(tokenResponse.accessToken));
            }
            else
            {
                return(BadRequest(tokenResponse.Message));
            }
        }
Ejemplo n.º 17
0
        public IActionResult RemoveRefreshToken(TokenResource tokenResource)
        {
            BaseResponce <AccessToken> accessTokenResponce = authenticationService.RevokeRefreshToken(tokenResource.RefreshToken);

            if (accessTokenResponce.Success)
            {
                return(Ok(accessTokenResponce.Extra));
            }
            else
            {
                return(BadRequest(accessTokenResponce.ErrorMessage));
            }
        }
Ejemplo n.º 18
0
        public IActionResult RefreshToken(TokenResource tokenResource)
        {
            AccessTokenResponse accessTokenResponse = authenticationService.CreateAccessTokenByRefreshToken(tokenResource.RefreshToken);

            if (accessTokenResponse.Success)
            {
                return(Ok(accessTokenResponse.Success));
            }
            else
            {
                return(BadRequest(accessTokenResponse.Message));
            }
        }
Ejemplo n.º 19
0
        public IActionResult RevokeRefreshToken(TokenResource tokenResource)
        {
            AccessTokenResponse acccessTokenResponse = _service.RevokeRefreshToken(tokenResource.RefreshToken);

            if (acccessTokenResponse.Success)
            {
                return(Ok(acccessTokenResponse.accessToken));
            }
            else
            {
                return(BadRequest(acccessTokenResponse.Message));
            }
        }
Ejemplo n.º 20
0
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        // DANGER! This is insecure. See http://twil.io/secure
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken  = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var token = TokenResource.Create();

        Console.WriteLine(token.Username);
    }
    static void Main(string[] args)
    {
        // Find your Account Sid and Auth Token at twilio.com/console
        // To set up environmental variables, see http://twil.io/secure
        const string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        const string authToken  = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var token = TokenResource.Create(ttl: 3600);

        Console.WriteLine(token.Username);
    }
        public void TestCreateResponse()
        {
            var twilioRestClient = Substitute.For <ITwilioRestClient>();

            twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
            twilioRestClient.Request(Arg.Any <Request>())
            .Returns(new Response(
                         System.Net.HttpStatusCode.Created,
                         "{\"username\": \"dc2d2894d5a9023620c467b0e71cfa6a35457e6679785ed6ae9856fe5bdfa269\",\"ice_servers\": [{\"url\": \"stun:global.stun.twilio.com:3478?transport=udp\",\"urls\": \"stun:global.stun.twilio.com:3478?transport=udp\"},{\"username\": \"dc2d2894d5a9023620c467b0e71cfa6a35457e6679785ed6ae9856fe5bdfa269\",\"credential\": \"tE2DajzSJwnsSbc123\",\"url\": \"turn:global.turn.twilio.com:3478?transport=udp\",\"urls\": \"turn:global.turn.twilio.com:3478?transport=udp\"},{\"username\": \"dc2d2894d5a9023620c467b0e71cfa6a35457e6679785ed6ae9856fe5bdfa269\",\"credential\": \"tE2DajzSJwnsSbc123\",\"url\": \"turn:global.turn.twilio.com:3478?transport=tcp\",\"urls\": \"turn:global.turn.twilio.com:3478?transport=tcp\"},{\"username\": \"dc2d2894d5a9023620c467b0e71cfa6a35457e6679785ed6ae9856fe5bdfa269\",\"credential\": \"tE2DajzSJwnsSbc123\",\"url\": \"turn:global.turn.twilio.com:443?transport=tcp\",\"urls\": \"turn:global.turn.twilio.com:443?transport=tcp\"}],\"date_updated\": \"Fri, 01 May 2020 01:42:57 +0000\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"ttl\": \"86400\",\"date_created\": \"Fri, 01 May 2020 01:42:57 +0000\",\"password\": \"tE2DajzSJwnsSbc123\"}"
                         ));

            var response = TokenResource.Create(client: twilioRestClient);

            Assert.NotNull(response);
        }
Ejemplo n.º 23
0
        public void TestCreateResponse()
        {
            var twilioRestClient = Substitute.For <ITwilioRestClient>();

            twilioRestClient.AccountSid.Returns("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            twilioRestClient.Request(Arg.Any <Request>())
            .Returns(new Response(
                         System.Net.HttpStatusCode.Created,
                         "{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"Fri, 24 Jul 2015 18:43:58 +0000\",\"date_updated\": \"Fri, 24 Jul 2015 18:43:58 +0000\",\"ice_servers\": [{\"url\": \"stun:global.stun:3478?transport=udp\"},{\"credential\": \"5SR2x8mZK1lTFJW3NVgLGw6UM9C0dja4jI/Hdw3xr+w=\",\"url\": \"turn:global.turn:3478?transport=udp\",\"username\": \"cda92e5006c7810494639fc466ecc80182cef8183fdf400f84c4126f3b59d0bb\"}],\"password\": \"5SR2x8mZK1lTFJW3NVgLGw6UM9C0dja4jI/Hdw3xr+w=\",\"ttl\": \"86400\",\"username\": \"cda92e5006c7810494639fc466ecc80182cef8183fdf400f84c4126f3b59d0bb\"}"
                         ));

            var response = TokenResource.Create(client: twilioRestClient);

            Assert.NotNull(response);
        }
Ejemplo n.º 24
0
        public Client(Credentials credentials) {
            if (credentials == null) throw new ArgumentNullException("credentials");
            requester = new Requester(credentials);

            Account = new AccountResource(requester);
            Balance = new BalanceResource(requester);
            Cards = new CardResourceShim(requester);
            Charges = new ChargeResource(requester);
            Customers = new CustomerResource(requester);
            Disputes = new DisputeResource(requester);
            Events = new EventResource(requester);
            Recipients = new RecipientResource(requester);
            Refunds = new RefundResourceShim(requester);
            Tokens = new TokenResource(requester);
            Transactions = new TransactionResource(requester);
            Transfers = new TransferResource(requester);
        }
Ejemplo n.º 25
0
        public async Task <IActionResult> RefreshToken(TokenResource tokenResource)
        {
            BaseResponse <AccessToken> accessTokenResponse = await _authenticationService.CreateAccessTokenByRefreshToken(tokenResource.RefreshToken);

            if (accessTokenResponse.Success)
            {
                // response2 = HttpContext.Response.Headers.Add;

                //response.Headers.Add("Set-Cookie","Authorization", $"Bearer {accessTokenResponse.Extra.Token}");
                // ​response.AddHeader("Set-Cookie", "SID=31d4d96e407aad42; Path=/; Secure; HttpOnly");

                return(Ok(accessTokenResponse.Extra));
            }
            else
            {
                return(BadRequest(accessTokenResponse.ErrorMessage));
            }
        }
        public void Post_WhenUnAuthorized_ReturnsOk_WithNewAccessToken()
        {
            var tokenResource = new TokenResource
            {
                Username = "******",
                Password = "******"
            };

            var response = _client.PostAsync(APIROUTE + "validate", ClientHelper.EncodeContent(tokenResource)).Result;

            response.EnsureSuccessStatusCode();

            var json   = response.Content.ReadAsStringAsync().Result;
            var result = JsonConvert.DeserializeObject <JsonWebToken>(json);

            Assert.NotNull(result);
            Assert.IsType <JsonWebToken>(result);
        }
Ejemplo n.º 27
0
        public async Task <IActionResult> Refresh([FromBody] TokenResource tokenResource)
        {
            var principal = _tokenService.GetPrincipalFromExpiredExpiredToken(tokenResource.Token);
            var username  = principal.Identity.Name;

            var user = _userContext.User.SingleOrDefault(u => u.username == username);

            if (user == null || user.RefreshToken != tokenResource.refreshToken)
            {
                return(BadRequest());
            }

            var newRefreshToken = _tokenService.generateRefreshToken();

            user.RefreshToken = newRefreshToken;
            await _userContext.SaveChangesAsync();

            // var newJwtToken = _tokenService.generateAccessToken(principal.Claims);
            var key   = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var _refresh_token = Guid.NewGuid().ToString().Replace("-", "");

            var SecurityToken = new JwtSecurityToken(
                issuer: _config["Jwt:Issuer"],
                audience: _config["Jwt:Issuer"],
                claims: principal.Claims,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddMinutes(2),
                signingCredentials: creds);

            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(SecurityToken),
                notBefore = SecurityToken.ValidFrom,
                token_expiration = SecurityToken.ValidTo,
                refresh_token = newRefreshToken,
                IssuedUtc = DateTime.UtcNow,
                refresh_token_expire = DateTime.UtcNow.AddDays(20)
            }));
        }
Ejemplo n.º 28
0
        public void TestCreateRequest()
        {
            var twilioRestClient = Substitute.For <ITwilioRestClient>();
            var request          = new Request(
                HttpMethod.Post,
                Twilio.Rest.Domain.Api,
                "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Tokens.json",
                ""
                );

            twilioRestClient.AccountSid.Returns("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));

            try
            {
                TokenResource.Create(client: twilioRestClient);
                Assert.Fail("Expected TwilioException to be thrown for 500");
            }
            catch (ApiException) {}
            twilioRestClient.Received().Request(request);
        }
Ejemplo n.º 29
0
        public Client(Credentials credentials)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }
            requester = new Requester(credentials);

            Account      = new AccountResource(requester);
            Balance      = new BalanceResource(requester);
            Cards        = new CardResourceShim(requester);
            Charges      = new ChargeResource(requester);
            Customers    = new CustomerResource(requester);
            Disputes     = new DisputeResource(requester);
            Events       = new EventResource(requester);
            Links        = new LinkResource(requester);
            Recipients   = new RecipientResource(requester);
            Refunds      = new RefundResourceShim(requester);
            Tokens       = new TokenResource(requester);
            Transactions = new TransactionResource(requester);
            Transfers    = new TransferResource(requester);
        }
Ejemplo n.º 30
0
        public TokenResource GetTokenResourceFromRequest()
        {
            HttpCookie tokenCookieFromRequest = HttpContext.Current.Request.Cookies["token_key"];
            var        tokenCookieFromHeader  = HttpContext.Current.Request.Headers.GetValues("token_key");

            if (tokenCookieFromRequest != null)
            {
                TokenResource token = (TokenResource)MemoryCache.Default.Get(tokenCookieFromRequest.Value);
                if (token != null)
                {
                    return(token);
                }
            }
            else if (tokenCookieFromHeader != null)
            {
                TokenResource token = (TokenResource)MemoryCache.Default.Get(tokenCookieFromHeader.FirstOrDefault());
                if (token != null)
                {
                    return(token);
                }
            }
            return(null);
        }
Ejemplo n.º 31
0
        public IActionResult Refresh([FromBody] RefreshTokenResource resource)
        {
            UserModels    sv       = new UserModels();
            IActionResult response = null;

            var identity = (ClaimsIdentity)User.Identity;
            IEnumerable <Claim> claims = identity.Claims;
            var userLogin = claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value;

            User user = sv.GetUserbyUserName(userLogin);

            if (user != null && user.Token == resource.Token)
            {
                var role        = sv.GetRolebyId(user.Role);
                var expiresDate = DateTime.Now.AddHours(12);
                var now         = DateTime.Now;
                var userInfo    = sv.GetUserInforByEmail(user.Username);

                if (!string.IsNullOrEmpty(user.Token) && user.Expire != null && user.Expire.Value > DateTime.Now)
                {
                    var tokenResource = new TokenResource
                    {
                        Token  = user.Token,
                        Expiry = user.Expire.Value
                    };
                    response = Json(tokenResource);
                }
                else
                {
                    var tokenResource = BuildToken(userInfo, user, role, now, expiresDate);
                    response = Json(tokenResource);
                }
            }

            return(response);
        }