private async Task <IActionResult> GetToken(TokenRequestViewModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var identity = await GetClaimsIdentity(model.username, model.password);

                if (identity == null)
                {
                    return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState)));
                }

                // check if there's an user with the given username
                var user = await _userManager.FindByNameAsync(model.username);

                // fallback to support e-mail address instead of username
                if (user == null && model.username.Contains("@"))
                {
                    user = await _userManager.FindByEmailAsync(model.username);
                }

                if (user == null ||
                    !await _userManager.CheckPasswordAsync(user, model.password))
                {
                    // user does not exists or password mismatch
                    return(new UnauthorizedResult());
                }

                // username & password matches: create the refresh token
                var rt = CreateRefreshToken(model.client_id, user.Id);

                // add the new refresh token to the DB
                //DbContext.Tokens.Add(rt);
                //DbContext.SaveChanges();
                await _tokenRepository.AddToken(rt);

                // create & return the access token
                var t = await CreateAccessToken(model, rt.Value);

                //return Json(t);

                //return await Task.FromResult(Ok());
                return(new JsonResult(t));
            }
            catch (Exception ex)
            {
                return(new UnauthorizedResult());
            }
        }
예제 #2
0
        public Guid Signin(AccountModel model)
        {
            if (string.IsNullOrEmpty(model.Phone) || string.IsNullOrEmpty(model.Password))
            {
                return(Guid.Empty);
            }
            var account = _accountQueryRepository.GetByPhone(model.Phone);

            if (account == null)
            {
                return(Guid.Empty);
            }
            if (_md5Encrypter.Encrypt(model.Password).Equals(account.Password))
            {
                var token = Guid.NewGuid();
                Task.Run(() =>
                {
                    _tokenRepository.AddToken(new TokenEntity {
                        Token = token, IsValid = true
                    });
                });
                return(token);
            }
            return(Guid.Empty);
        }
예제 #3
0
        public async Task AddToken(string strToken, Guid userId)
        {
            Token token = new Token()
            {
                StrToken = strToken,
                UserId   = userId
            };

            if (!token.IsValidData())
            {
                throw new ArgumentException("Invalid arguments");
            }

            bool isExistsInDb = await _tokenRepository.CheckUserByToken(token);


            if (!isExistsInDb)
            {
                await _tokenRepository.AddToken(token);
            }
            else
            {
                throw new InvalidOperationException("Token exists already");
            }
        }
예제 #4
0
 /// <summary>
 /// Adds token to the database.
 /// </summary>
 /// <param name="jwt"></param>
 /// <param name="userID"></param>
 /// <returns></returns>
 public bool AddToken(string jwt, Guid userID)
 {
     try
     {
         Token token = new Token(jwt, userID);
         tokenRepo.AddToken(token);
         return(true);
     }catch (Exception)
     {
         return(false);
     }
 }
예제 #5
0
        private async Task <IActionResult> Login(AuthRequest authUserRequest)
        {
            var user = await userManager.FindByEmailAsync(authUserRequest.UserName);

            if (user != null)
            {
                var checkPwd = await signInManager.CheckPasswordSignInAsync(user, authUserRequest.Password, false);

                var roles = await userManager.GetRolesAsync(user);

                var roleString = JsonConvert.SerializeObject(roles);
                if (checkPwd.Succeeded)
                {
                    bool   refreshTokenDone = true;
                    string refreshToken     = null;
                    if (tokenSettings.Value.MultipleRefreshTokenEnabled)
                    {
                        refreshToken = Guid.NewGuid().ToString().Replace("-", "");
                        var tokenRepoModel = new TokenRepoModel
                        {
                            ClientId     = authUserRequest.ClientId,
                            RefreshToken = refreshToken,
                            Id           = Guid.NewGuid().ToString(),
                            IsStop       = 0
                        };
                        refreshTokenDone = tokenRepo.AddToken(tokenRepoModel);
                    }

                    if (refreshTokenDone)
                    {
                        var response = await GetJwt(user, roles, authUserRequest.ClientId, refreshToken);

                        return(Ok(response));
                    }
                    else
                    {
                        return(BadRequest(new
                        {
                            Code = "909",
                            Message = "can not add token to database",
                        }));
                    }
                }
            }


            return(BadRequest(
                       new
            {
                Code = "902",
                Message = "invalid user infomation",
            }));
        }
예제 #6
0
        public async Task HandlerAsync(LoginAsync command)
        {
            await _accountService.LoginAsync(command.Password, command.Email);

            var user = await _userRepository.GetAsyncByEmail(command.Email);

            var jwt = _jwtHandler.CreateToken(user.Email, "user");

            var refreshToken = new RefreshToken(user, _passwordHasher);

            jwt.RefreshTokens = refreshToken;
            await _tokenRepository.AddToken(refreshToken);

            _memoryCache.Set(command.TokenId, jwt, TimeSpan.FromMinutes(1));
        }
예제 #7
0
        public string GetRefreshToken(string email)
        {
            string      refreshToken = Generator.GenerateRandomString(12);
            TokenEntity tokenEntity  = _tokenRepository.GetTokenByEmail(email);

            if (tokenEntity == null)
            {
                tokenEntity = new TokenEntity()
                {
                    Email        = email,
                    RefreshToken = refreshToken
                };
                _tokenRepository.AddToken(tokenEntity);
            }
            else
            {
                tokenEntity.RefreshToken = refreshToken;
                _tokenRepository.UpdateToken(tokenEntity);
            }

            return(tokenEntity.RefreshToken);
        }
예제 #8
0
        public bool AddToken(string jwt, Guid userID)
        {
            Token token = new Token(jwt, userID);

            return(tokenRepo.AddToken(token));
        }
예제 #9
0
 public void AddToken(TokenDTO tokenDTO)
 {
     _tokenRepository.AddToken(tokenDTO);
 }