Exemple #1
0
        public async Task <IActionResult> Register([FromBody] TokenViewModel tokenViewModel)
        {
            if (tokenViewModel.Password != tokenViewModel.Repassword)
            {
                ModelState.AddModelError(string.Empty, "Password don't match");
                return(View());
            }

            var newUser = new IdentityUser
            {
                UserName = tokenViewModel.Email,
                Email    = tokenViewModel.Email
            };

            var userCreationResult = await _userManager.CreateAsync(newUser, tokenViewModel.Password);

            if (!userCreationResult.Succeeded)
            {
                foreach (var error in userCreationResult.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
                return(View());
            }

            var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(newUser);

            var tokenVerificationUrl = Url.Action("VerifyEmail", "Account", new { id = newUser.Id, token = emailConfirmationToken }, Request.Scheme);

            await _MessageService.SendEmail(tokenViewModel.Email, "Verify your email", $"Click <a href=\"{tokenVerificationUrl}\">here</a> to verify your email");

            return(Content("Check your email for a verification link"));
        }
        public IHttpActionResult UserLogin(LoginModel model)
        {
            var user = userService.CheckUserNamePassword(model.username, model.password);

            if (user != null)
            {
                var token      = tokenService.GenerateToken(user.Id.ToString());
                var tokenModel = new TokenViewModel()
                {
                    access_token = token,
                    expires_in   = tokenService.ExpireMilliSeconds.ToString(),
                    token_type   = tokenService.TokenType,
                };
                return(Content(HttpStatusCode.OK, new BaseResult <LoginViewModel>()
                {
                    success = true,
                    data = new LoginViewModel()
                    {
                        token = tokenModel,
                        full_name = user.FirstName + ' ' + user.LastName,
                        role = user.RoleModel.Title.ToString()
                    },
                }));
            }

            return(Content(HttpStatusCode.Unauthorized, new BaseResult <LoginViewModel>()
            {
                success = false,
                data = null,
                message = "Invalid Username or password"
            }));
        }
Exemple #3
0
        public async Task <ApiResponse> InvalidateRefreshTokens(TokenViewModel model)
        {
            ApiResponse response = new ApiResponse();

            try
            {
                User storedUser = await GetUserFromToken(model.Token);

                if (storedUser == null)
                {
                    return new ApiResponse {
                               Error = INVALID_TOKEN
                    }
                }
                ;

                await _tokenRepository.Delete(x => x.UserId == storedUser.Id &&
                                              x.RefreshToken != model.OldRefreshToken);

                response.Data = true;
            }
            catch (Exception e)
            {
                response.Error = e.Message;
            }

            return(response);
        }
        public TokenViewModel Generate(UserViewModel Model)
        {
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

            byte[] key = Encoding.ASCII.GetBytes(this._settings.PrivateKey);

            TokenViewModel tokenViewModel = new TokenViewModel();

            tokenViewModel.CreatedAt  = DateTime.Now;
            tokenViewModel.ExpiressAt = tokenViewModel.CreatedAt.AddDays(this._settings.ExpirationDays);
            tokenViewModel.User       = Model;

            SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, Model.Email),
                    new Claim(ClaimTypes.NameIdentifier, Model.Id.ToString()),
                    new Claim(ClaimTypes.Role, Model.Role != null ? Model.Role.Name : "INTERN"),
                }),
                Expires            = tokenViewModel.ExpiressAt,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(securityTokenDescriptor);

            tokenViewModel.AccessToken = tokenHandler.WriteToken(token);

            return(tokenViewModel);
        }
        private async Task <TokenViewModel> GetToken(AuthenticateDTO authenticateDTO)
        {
            var token = new TokenViewModel();

            using (var httpClient = new HttpClient())
            {
                var url = _authSettings.ClientsConnections.RunInDocker ? _authSettings.ClientsConnections.UrlApi1Docker : _authSettings.ClientsConnections.UrlApi1;
                using (var request = new HttpRequestMessage(new HttpMethod("POST"), $"{url}/api/Authenticate"))
                {
                    request.Headers.TryAddWithoutValidation("accept", "application/json");

                    request.Content = new StringContent(JsonConvert.SerializeObject(authenticateDTO));
                    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                    var response = await httpClient.SendAsync(request);

                    if (response.IsSuccessStatusCode)
                    {
                        token = JsonConvert.DeserializeObject <TokenViewModel>(response.Content.ReadAsStringAsync().Result);
                    }
                }
            }

            return(token);
        }
Exemple #6
0
        public async Task Test1()
        {
            // Arrange
            var mockLogger        = new Mock <ILogger <TokenController> >();
            var mockConfiguration = new Mock <IConfiguration>();
            var mockRepo          = new Mock <ISeguridadBll>();

            mockRepo.Setup(repo => repo.ValidarUsuario("Cliente", "passwordSeguro1234567")).ReturnsAsync(GetTestCliente());

            var controller = new TokenController(mockLogger.Object, mockConfiguration.Object, mockRepo.Object);

            TokenViewModel tokenViewModel = new TokenViewModel()
            {
                User     = "******",
                Password = "******"
            };

            // Act
            //var result = await mockRepo.Object.ValidarUsuario(tokenViewModel.User, tokenViewModel.Password);
            var actionResult = await controller.Post(tokenViewModel);

            // Assert
            //Assert.IsNotNull(result);

            //var model = Assert.IsAssignableFrom<ResponseViewModel>(viewResult.ViewData.Model);

            //Assert.Equal(2, model.Count());
            Assert.IsInstanceOf <ActionResult>(actionResult);
            mockRepo.Verify(x => x.ValidarUsuario(tokenViewModel.User, tokenViewModel.Password), Times.Once);
        }
Exemple #7
0
        public TokenViewModel GenerateTokenTrainingAcademy(string UserName, string Password)
        {
            var token      = string.Empty;
            var UrlServico = "https://whpservicemaistop.academiadovarejowhirlpool.com.br/";
            var client     = new RestClient(UrlServico);

            var request = new RestRequest("/token", Method.POST);

            request.AddParameter("grant_type", "password");
            request.AddParameter("username", UserName);
            request.AddParameter("password", Password);

            var response = client.Execute <TokenViewModel>(request);

            if (!response.IsSuccessful)
            {
                _logger.Fatal("Não foi possivel conectar na plataforma de treinamento, entre em contato com o administrador!");
            }

            var Token = JsonConvert.DeserializeObject <TokenViewModel>(response.Content);

            var tokenViewModel = new TokenViewModel()
            {
                access_token = Token.access_token
                ,
                expires_in = Token.expires_in
                ,
                token_type = Token.token_type
            };

            return(tokenViewModel);
        }
        public async Task <TokenViewModel> LoginAsync(LoginViewModel model)
        {
            var User = await _userManager.FindByEmailAsync(model.Email);

            TokenViewModel Token = new TokenViewModel {
                UserName = model.Email
            };

            if (User != null && await _userManager.CheckPasswordAsync(User, model.Password))
            {
                //var signInResult = await _signInManager.PasswordSignInAsync(User, model.password, false, false);
                var role = await _userManager.GetRolesAsync(User);

                IdentityOptions _options = new IdentityOptions();

                var TokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[] {
                        new Claim("UserId", User.Id.ToString()),
                        new Claim(_options.ClaimsIdentity.RoleClaimType, role.FirstOrDefault())
                    }),
                    Expires            = DateTime.Now.AddHours(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.SecurityKey)),
                                                                SecurityAlgorithms.HmacSha256)
                };

                var TokenHandler  = new JwtSecurityTokenHandler();
                var SecurityToken = TokenHandler.CreateToken(TokenDescriptor);
                Token.AccessToken = TokenHandler.WriteToken(SecurityToken);
                Token.UserId      = await _userManager.GetUserIdAsync(User);
            }

            return(Token);
        }
        public EditEmailTextViewModel(ITranslationUpdater translationUpdater, IMailSignatureHelper mailSignatureHelper, ITokenHelper tokenHelper, TokenViewModelFactory tokenViewModelFactory)
            : base(translationUpdater)
        {
            _tokenReplacer = tokenHelper.TokenReplacerWithPlaceHolders;

            var builder = tokenViewModelFactory
                          .Builder <EditEmailTextInteraction>()
                          .WithInitialValue(Interaction)
                          .WithTokenList(tokenHelper.GetTokenListForEmail());

            SubjectTokenViewModel = builder
                                    .WithSelector(i => i.Subject)
                                    .WithDefaultTokenReplacerPreview()
                                    .Build();

            ContentTokenViewModel = builder
                                    .WithSelector(i => i.Content)
                                    .WithTokenCustomPreview(ReplaceTokensAddSignature)
                                    .Build();

            _signatureText = mailSignatureHelper.ComposeMailSignature();

            OkCommand     = new DelegateCommand(ExecuteOk);
            CancelCommand = new DelegateCommand(o => FinishInteraction());
        }
Exemple #10
0
        public IActionResult ValidateToken([FromBody] TokenViewModel token)
        {
            try
            {
                if (token == null)
                {
                    return(BadRequest(new { Error = "Token nulo ou inválido!" }));
                }

                if (string.IsNullOrEmpty(token.Token))
                {
                    return(BadRequest(new { Error = "Token nulo ou inválido!" }));
                }

                if (!_authenticationAppService.ValidateToken(token.Token, _configuration["SecurityKey"].ToCharArray()))
                {
                    throw new BusisnessException("Token Inválido!");
                }

                return(Ok("Token Válido"));
            }
            catch (BusisnessException ex)
            {
                return(BadRequest(new { Errors = ex.Message }));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex.StackTrace);
                return(BadRequest(new { Errors = $"Erro não catalogado. Entre em contato com Administrador. Erro - {ex.Message}" }));
            }
        }
Exemple #11
0
 public LoginResponseModel(string id, string userName, TokenViewModel authToken, TokenViewModel refreshToken)
 {
     Id           = id;
     UserName     = userName;
     AuthToken    = authToken;
     RefreshToken = refreshToken;
 }
Exemple #12
0
        private async Task <TokenViewModel> GenerateAccessToken(User user)
        {
            var roles = await _userManager.GetRolesAsync(user);

            var claims = new List <Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim("UserId", user.Id),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            if (roles.Any())
            {
                claims.Add(new Claim(ClaimTypes.Role, string.Join(",", roles)));
            }
            var expires     = DateTime.Now.AddMonths(1);
            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_Configuration["Jwt:SigningKey"]));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var accessToken = new JwtSecurityToken(_Configuration["Jwt:Issuer"],
                                                   _Configuration["Jwt:Site"],
                                                   claims,
                                                   expires: expires,
                                                   signingCredentials: credentials
                                                   );

            var AccessToken = new JwtSecurityTokenHandler().WriteToken(accessToken);
            var response    = new TokenViewModel();

            response.AcessToken = AccessToken;
            response.ExpireAt   = expires;
            return(response);
        }
        public async Task <JsonResult> Token(TokenViewModel collection)
        {
            try
            {
                var pairs = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("grant_type", "password"),
                    new KeyValuePair <string, string>("username", collection.UserName),
                    new KeyValuePair <string, string> ("Password", collection.Password)
                };
                var content = new FormUrlEncodedContent(pairs);
                var status  = await _userLoginDetailService.Token(content);

                Session["Access_Token"] = status.Access_Token;
                return(new JsonResult {
                    Data = new { status = status }
                });
            }
            catch (Exception ex)
            {
                return(new JsonResult {
                    Data = new { status = false }
                });
            }
        }
        public async Task <IEnumerable <TokenViewModel> > GetAllUserTokens()
        {
            List <TokenViewModel> tokenList = new List <TokenViewModel>();

            try
            {
                List <User> users = await GetUsers();

                List <Token> tokens = await _context
                                      .Tokens
                                      .Find(_ => true)
                                      .ToListAsync();

                foreach (User user in users)
                {
                    foreach (Token token in tokens)
                    {
                        if (token.UserId.Equals(user.Id))
                        {
                            TokenViewModel tokenDataTransformation = new TokenViewModel();
                            tokenDataTransformation.Id       = token.Id;
                            tokenDataTransformation.UserId   = user.Id;
                            tokenDataTransformation.UserName = user.UserName;
                            tokenDataTransformation.TokenKey = token.TokenKey;

                            tokenList.Add(tokenDataTransformation);
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            return(tokenList);
        }
Exemple #15
0
        public FtpActionViewModel(TokenHelper tokenHelper, ITranslationUpdater translationUpdater, ICurrentSettingsProvider currentSettingsProvider, ICommandLocator commandLocator, ITokenViewModelFactory tokenViewModelFactory, IDispatcher dispatcher)
            : base(translationUpdater, currentSettingsProvider, dispatcher)
        {
            // TODO update on translation change!
            DirectoryTokenViewModel = tokenViewModelFactory
                                      .BuilderWithSelectedProfile()
                                      .WithSelector(p => p.Ftp.Directory)
                                      .WithDefaultTokenReplacerPreview(th => th.GetTokenListWithFormatting())
                                      .Build();

            if (currentSettingsProvider?.Settings != null)
            {
                _ftpAccounts    = currentSettingsProvider.Settings.ApplicationSettings.Accounts.FtpAccounts;
                FtpAccountsView = new ListCollectionView(_ftpAccounts);
                FtpAccountsView.SortDescriptions.Add(new SortDescription(nameof(FtpAccount.AccountInfo), ListSortDirection.Ascending));
            }

            AddAccountCommand = commandLocator.CreateMacroCommand()
                                .AddCommand <FtpAccountAddCommand>()
                                .AddCommand(new DelegateCommand(o => SelectNewAccountInView()))
                                .Build();

            EditAccountCommand = commandLocator.CreateMacroCommand()
                                 .AddCommand <FtpAccountEditCommand>()
                                 .AddCommand(new DelegateCommand(o => RefreshAccountsView()))
                                 .Build();
        }
        public async Task <ResultModel <TokenViewModel> > AtualizaToken(string token, string refreshToken)
        {
            ResultModel <TokenViewModel> result = new ResultModel <TokenViewModel>();

            try
            {
                ClaimsPrincipal principal = _tokenService.GetPrincipalFromExpiredToken(token);
                string          username  = principal.Identity.Name;

                AutenticaModel user = await _autenticaRepository.GetUsuario(u => u.Nome == username);

                if (user == null || user.RefreshToken != refreshToken)
                {
                    result.Inconsistencias.Add("Não foi possivel atualiza o token.");
                    return(result);
                }

                TokenViewModel jwtToken        = _tokenService.GenerateAccessToken(principal.Claims);
                string         newRefreshToken = _tokenService.GenerateRefreshToken();
                jwtToken.RefreshToken = newRefreshToken;
                user.RefreshToken     = newRefreshToken;
                await _autenticaRepository.UpdateUsuario(user);

                result.Resultado = jwtToken;
            }
            catch (Exception ex)
            {
                result.Inconsistencias.Add(ex.Message);
            }

            return(result);
        }
        public TokenViewModel GetTokenItems()
        {
            var context    = HttpContext.Current;
            var serializer = new JavaScriptSerializer();

            if (context == null)
            {
                return(new TokenViewModel());
            }
            if (context.Request.Cookies.Get(CartSessionKey) == null)
            {
                var tokenItem = new TokenViewModel();
                var cookie    = new HttpCookie(CartSessionKey, Protect(serializer.Serialize(tokenItem), PurposeText))
                {
                    HttpOnly = false,
                    Secure   = false,
                    Expires  = GetExpiryTime()
                };
                context.Response.Cookies.Set(cookie);
                return(tokenItem);
            }
            var tokenCookie = context.Request.Cookies.Get(CartSessionKey);

            return(serializer.Deserialize <TokenViewModel>(Unprotect(tokenCookie.Value, PurposeText)));
        }
        // GET: Tokens
        public ActionResult Index(int?page)
        {
            if (Request.Cookies.Get("client") != null)
            {
                var pageNumber = page ?? 1;
                var pageSize   = 10;

                var   cli     = Request.Cookies.Get("client").Value;
                Users client  = db.Users.Where(c => c.UserName == cli).FirstOrDefault();
                var   product = db.ClientProducts.Include(t => t.Product).Where(r => r.UsersId == client.ID).ToList();

                List <Token> tokenList = new List <Token>();

                foreach (var item in product)
                {
                    if (tokenList.Count > 0)
                    {
                        if (tokenList.Where(i => i.ProductId == item.ProductId).ToList().Count == 0)
                        {
                            tokenList.AddRange(db.Tokens.Where(r => r.ProductId == item.ProductId));
                        }
                    }
                    else
                    {
                        tokenList.AddRange(db.Tokens.Where(r => r.ProductId == item.ProductId));
                    }
                }

                TokenViewModel tokenViewModel = new TokenViewModel {
                    Tokens = tokenList.OrderBy(d => d.ComplainDate).ToPagedList(pageNumber, pageSize)
                };
                return(View(tokenViewModel));
            }
            return(RedirectToAction("Login", "Users"));
        }
Exemple #19
0
        public async Task <object> ValidTokenAsync([FromBody] TokenViewModel token)
        {
            var emailToken = await ReadTokeJwt(token.AccessToken);

            if (emailToken == "Token expirado")
            {
                return(new
                {
                    error = "Token expirado"
                });
            }

            var userAplication = await _userManager.FindByNameAsync(emailToken);

            var grupo = _mapper.Map <GrupoViewModel>(_grupoRepository.GetByIdGrupo(userAplication.IdGrupo));

            var newToken = await GenerateJwt(emailToken);

            var usu = new UserSettingsViewModel()
            {
                idGrupo = userAplication.IdGrupo,
                Data    = new DataViewModel()
                {
                    DisplayName = grupo.Nome,
                    Email       = emailToken
                },
            };

            return(new
            {
                user = usu,
                access_token = newToken
            });
        }
Exemple #20
0
        public async Task <IActionResult> Create(TokenViewModel tokenModel)
        {
            var service = await _serviceRepository.Get(tokenModel.ServiceId);

            var serviceMerchant = await _merchantRepository.Get(tokenModel.MerchantId);

            var paymentInstrument = await _paymentInstrumentRepository.Select(tokenModel.PaymentInstrumentId);

            if (service != null && serviceMerchant != null && paymentInstrument != null)
            {
                Token token = new Token()
                {
                    ServiceId           = service.Id,
                    MerchantId          = serviceMerchant.Id,
                    VProvisionedTokenID = tokenModel.VProvisionedTokenID,
                    TokenStatus         = tokenModel.TokenStatus,
                    TokenRequestorID    = tokenModel.TokenRequestorID,
                    TokenReferenceID    = tokenModel.TokenReferenceID,
                    Last4               = tokenModel.Last4,
                    ExpirationMonth     = tokenModel.ExpirationMonth,
                    ExpirationYear      = tokenModel.ExpirationYear,
                    AppPrgrmID          = tokenModel.AppPrgrmID,
                    TokenAccountNumber  = tokenModel.TokenAccountNumber,
                    PaymentInstrumentId = paymentInstrument.Id,
                    Status              = tokenModel.Status,
                    Created             = DateTime.UtcNow,
                    Updated             = null
                };

                await _tokenRepository.Insert(token);
            }

            return(RedirectToAction("List"));
        }
        public async Task <bool> SalvarToken(TokenViewModel token)
        {
            try
            {
                var tokenDB = await _tokenRepository.Get(x => x.TelefoneResp == token.TelefoneResp);

                Token newToken = new Token();
                if (tokenDB.Any())
                {
                    newToken        = tokenDB.FirstOrDefault();
                    newToken.UserId = token.UserId;
                    await BeginTransaction();

                    await Task.Run(() => _tokenRepository.Update(newToken));
                    await Commit();

                    return(true);
                }
                else
                {
                    newToken = Mapper.Map <Token>(token);
                    await BeginTransaction();

                    await Task.Run(() => _tokenRepository.Add(newToken));
                    await Commit();

                    return(true);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemple #22
0
        // GET: Location/Delete/5
        public async Task <ActionResult> Delete(string id)
        {
            TokenViewModel _token = HttpContext.Session.Get <TokenViewModel>(Constant.TOKEN);

            if (_token != null)
            {
                using (var client = new HttpClient())
                {
                    // TODO: Add insert logic here
                    client.BaseAddress = new Uri("https://cocshopwebapi20190925023900.azurewebsites.net/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_token.Access_token}");

                    HttpResponseMessage response = await client.DeleteAsync($"api/Locations/{id}");

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

                    var body = JsonConvert.DeserializeObject <BaseViewModel <string> >(jsonString);
                    if (response.IsSuccessStatusCode)
                    {
                        return(Json(new { status = true }));
                    }
                    else
                    {
                        return(Json(new { status = false, error = body.Description }));
                    }
                }
            }
            return(RedirectToAction("Login", "Auth"));
        }
        private async Task <ApiResponse <TokenViewModel> > GetTokenResponse(TokenRequestViewModel model)
        {
            var apiResp = new ApiResponse <TokenViewModel>
            {
                Type = ResponseType.Fail
            };

            var applicationUser = new ApplicationUser
            {
                Email    = model.EmailOrUsername,
                UserName = model.EmailOrUsername
            };

            var securityResp = await _security.GetToken(applicationUser, model.Password);

            if (securityResp.Type != ResponseType.Success)
            {
                apiResp.ErrorCode = securityResp.ErrorCode;
                return(apiResp);
            }

            var viewModel = new TokenViewModel
            {
                Username    = applicationUser.UserName,
                AccessToken = securityResp.Data,
                Email       = applicationUser.Email,
                NameSurname = applicationUser.NameSurname,
                Id          = applicationUser.Id.ToString()
            };

            apiResp.Data = viewModel;
            apiResp.Type = ResponseType.Success;

            return(apiResp);
        }
        public async Task <IActionResult> RefreshToken([FromBody] TokenViewModel model)
        {
            var refreshTokenValue = model.RefreshToken;

            if (string.IsNullOrWhiteSpace(refreshTokenValue))
            {
                return(BadRequest("refreshToken is not set."));
            }

            var token = await _tokenStoreService.FindTokenAsync(refreshTokenValue);

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

            var result = await _tokenFactoryService.CreateJwtTokensAsync(token.User);

            await _tokenStoreService.AddUserTokenAsync(token.User, result.RefreshTokenSerial, result.AccessToken, _tokenFactoryService.GetRefreshTokenSerial(refreshTokenValue));

            await _uow.SaveChangesAsync();

            _antiforgery.RegenerateAntiForgeryCookies(result.Claims);

            return(Ok(new { access_token = result.AccessToken, refresh_token = result.RefreshToken }));
        }
        private async Task <TokenViewModel> GerarTokenUsuario(Accounts accounts)
        {
            TokenViewModel token = new TokenViewModel();

            Task ts = new Task(delegate()
            {
                List <Claim> claims = new List <Claim>();

                claims.Add(new Claim(JwtRegisteredClaimNames.UniqueName, accounts.NOME));
                claims.Add(new Claim(JwtRegisteredClaimNames.NameId, accounts.CPF));
                claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));

                var std = new SecurityTokenDescriptor()
                {
                    Issuer             = _jwtTokenOptions.Issuer,
                    Audience           = _jwtTokenOptions.Audience,
                    Subject            = new ClaimsIdentity(claims),
                    NotBefore          = DateTime.Now,
                    Expires            = DateTime.Now.AddMinutes(_jwtTokenOptions.MinutesValid),
                    SigningCredentials = new SigningCredentialsConfiguration().SigningCredentials
                };

                SecurityToken securityToken = new JwtSecurityTokenHandler().CreateToken(std);

                token.date_generation = DateTime.Now;
                token.expires_in      = DateTime.Now.AddMinutes(_jwtTokenOptions.MinutesValid);
                token.access_token    = new JwtSecurityTokenHandler().WriteToken(securityToken);
            });

            ts.Start();
            await ts;

            return(token);
        }
Exemple #26
0
        public TokenViewModel GetTokenForAPI(LoginModel objAuthModel)
        {
            var    myrul     = HttpContext.Current.Request.Url.AbsoluteUri;
            string subdomain = System.Configuration.ConfigurationManager.AppSettings["SubDomain"].ToString();
            var    tokenUrl  = myrul.Replace(HttpContext.Current.Request.Url.AbsolutePath, subdomain + "/") + "token";

            var            request = string.Format("grant_type=password&username={0}&password={1}", HttpUtility.UrlEncode(objAuthModel.UserName), HttpUtility.UrlEncode(objAuthModel.Password));
            TokenViewModel token   = null;

            try
            {
                WebRequest webRequest = WebRequest.Create(tokenUrl);
                webRequest.ContentType = @"application/x-www-form-urlencoded";;
                webRequest.Method      = "POST";
                byte[] bytes = Encoding.ASCII.GetBytes(request);
                webRequest.ContentLength = bytes.Length;
                using (Stream outputStream = webRequest.GetRequestStream())
                {
                    outputStream.Write(bytes, 0, bytes.Length);
                }
                using (WebResponse webResponse = webRequest.GetResponse())
                {
                    StreamReader newstreamreader       = new StreamReader(webResponse.GetResponseStream());
                    string       newresponsefromserver = newstreamreader.ReadToEnd();
                    newresponsefromserver = newresponsefromserver.Replace(".expires", "expires").Replace(".issued", "issued");
                    token = Newtonsoft.Json.JsonConvert.DeserializeObject <TokenViewModel>(newresponsefromserver);
                }
            }
            catch (Exception ex)
            {
                token = null;
            }
            return(token);
        }
        /// <summary>
        /// Вход.
        /// </summary>
        public TokenViewModel SignInAsync(SignInViewModel model)
        {
            var(user, isSuccess) = _userService.TryToSignInAsync(model.Email, model.Password);
            if (!isSuccess)
            {
                throw new Exception("Invalid credentials.");
            }

            var jwt          = _jwtHandler.Create(model.Email);
            var refreshToken = _passwordHasher.HashPassword(model, Guid.NewGuid().ToString())
                               .Replace("+", string.Empty)
                               .Replace("=", string.Empty)
                               .Replace("/", string.Empty);

            jwt.RefreshToken = refreshToken;
            _refreshTokens.Add(new RefreshToken {
                Username = model.Email, Token = refreshToken
            });

            var tokenViewModel = new TokenViewModel
            {
                JsonWebToken = jwt,
                UserId       = user.Id,
                Role         = user.UserRole,
                FullName     = (user.LastName) +
                               (user.FirstName == String.Empty ? String.Empty : $" {user.FirstName}") +
                               (user.MiddleName == String.Empty ? String.Empty : $" {user.MiddleName}")
            };

            return(tokenViewModel);
        }
        public async Task <TokenViewModel> Login(LoginViewModel loginViewModel = null)
        {
            string         token;
            TokenViewModel result = null;

            if (loginViewModel == null)
            {
                token = await localStorage.GetItem <string>("token");
            }
            else
            {
                result = await Http.PostJsonAsync <TokenViewModel>("/api/Token/Login", loginViewModel);

                token = result.Token;
                await localStorage.SetItem <string>("token", token);
            }
            IsAuthorize = token != null;
            if (IsAuthorize)
            {
                Http.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
                try
                {
                    await UpdateUserData();
                }
                catch
                {
                    await Logout();
                }
                UpdateAfterAuthorization?.Invoke();
            }
            return(result);
        }
Exemple #29
0
        public async Task <TokenViewModel> InfoDeterminedBase(string market, decimal baseAmount)
        {
            TokenViewModel viewModel = new TokenViewModel();

            viewModel.BaseType = BaseType(market);
            viewModel.MinValue = MinTradeValue(viewModel.BaseType);
            using (var client = new BinanceClient())
            {
                var baseBalance = await client.GetAccountInfoAsync();

                if (baseBalance.Success)
                {
                    viewModel.BaseTotal  = baseBalance.Data.Balances.Where(b => b.Asset == viewModel.BaseType).Select(b => b.Free).Single();
                    viewModel.BaseAmount = baseAmount;
                    var currentPrice = await client.Get24HPriceAsync(market);

                    if (currentPrice.Success)
                    {
                        CalculateAmountDecimal amountDecimal = new CalculateAmountDecimal();
                        viewModel.Name      = market;
                        viewModel.LastPrice = currentPrice.Data.LastPrice;
                        viewModel.Amount    = decimal.Round(viewModel.BaseAmount / viewModel.LastPrice, await amountDecimal.OrderBookDecimal(market));
                        return(viewModel);
                    }
                }
            }
            return(null);
        }
Exemple #30
0
        public async Task <TokenViewModel> Info(string market, decimal amountPercent)
        {
            TokenViewModel viewModel = new TokenViewModel();

            viewModel.BaseType = BaseType(market);
            viewModel.MinValue = MinTradeValue(viewModel.BaseType);
            using (var client = new BinanceClient())
            {
                var baseBalance = await client.GetAccountInfoAsync();

                if (baseBalance.Success)
                {
                    CalculateAmountDecimal amountDecimal = new CalculateAmountDecimal();
                    viewModel.BaseDecimalAmount = viewModel.BaseType == "USDT" || viewModel.BaseType == "TUSD" || viewModel.BaseType == "USDC" || viewModel.BaseType == "PAX" ? 2 : await amountDecimal.OrderBookDecimal(viewModel.BaseType + "USDT");

                    viewModel.BaseTotal  = decimal.Round(baseBalance.Data.Balances.Where(b => b.Asset == viewModel.BaseType).Select(b => b.Free).Single(), viewModel.BaseDecimalAmount);
                    viewModel.BaseTotal  = decimal.Round(viewModel.BaseTotal - (viewModel.BaseTotal * 0.01m), viewModel.BaseDecimalAmount);
                    viewModel.BaseAmount = decimal.Round(viewModel.BaseTotal * amountPercent, viewModel.BaseDecimalAmount);
                    var currentPrice = await client.Get24HPriceAsync(market);

                    if (currentPrice.Success)
                    {
                        viewModel.PriceDecimalAmount = await amountDecimal.PriceDecimal(market);

                        viewModel.AssetDecimalAmount = await amountDecimal.OrderBookDecimal(market);

                        viewModel.Name      = market;
                        viewModel.LastPrice = currentPrice.Data.LastPrice;
                        viewModel.Amount    = decimal.Round(viewModel.BaseAmount / viewModel.LastPrice, viewModel.AssetDecimalAmount);
                        return(viewModel);
                    }
                }
            }
            return(null);
        }
        private void AuthUser(TokenViewModel token)
        {
            var ticket = new FormsAuthenticationTicket
            (
            1,
            token.LoginAD,
            DateTime.Now,
            DateTime.Now.AddMinutes(Convert.ToInt32(FormsAuthentication.Timeout.TotalMinutes)),
            true,
            token.LoginAD,
            FormsAuthentication.FormsCookiePath
            );

            var cookie = new System.Web.HttpCookie(
                FormsAuthentication.FormsCookieName,
                FormsAuthentication.Encrypt(ticket)
                )
            {
                HttpOnly = true
            };

            Response.Cookies.Add(cookie);

            TokenAcesso = token;
        }