Beispiel #1
0
        public async Task <LoginResponse> RefreshLoginAsync(RefreshLoginRequest request)
        {
            var validateResult = await ValidateRefreshTokenAsync(request.RefreshToken);

            if (validateResult.ResponseMessage.Status != ResponseStatus.Status.Success ||
                validateResult.ClaimsPrincipal == null)
            {
                return(new LoginResponse
                {
                    ResponseMessage = new ResponseMessage(ResponseStatus.Status.Fail, @"Token is invalid")
                });
            }

            var userName = validateResult.ClaimsPrincipal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);

            if (userName == null)
            {
                throw new ArgumentNullException($"Cannot retrive user name");
            }

            var user = await _userManager.FindByNameAsync(userName.Value);

            if (user != null)
            {
                if (user.Status == UserStatus.Inactive)
                {
                    return(new LoginResponse
                    {
                        ResponseMessage = new ResponseMessage(ResponseStatus.Status.Fail, @"User is not activated")
                    });
                }

                var token = await GenerateJwtTokenAsync(user, false);

                if (token != null)
                {
                    // for security, each refresh token only use once
                    // delete old refresh token from DB
                    if (!string.IsNullOrEmpty(validateResult.RefreshTokenKey))
                    {
                        await _userTokenRepository.DeleteAsync(x =>
                                                               x.UserId == user.Id && x.RefreshTokenKey == validateResult.RefreshTokenKey);
                    }

                    return(new LoginResponse
                    {
                        ResponseMessage = new ResponseMessage(ResponseStatus.Status.Success),
                        AccessToken = token.AccessToken,
                        RefreshAccessToken = await GenerateJwtRefreshTokenAsync(user) // new refresh token
                    });
                }
            }

            return(new LoginResponse
            {
                ResponseMessage = new ResponseMessage(ResponseStatus.Status.Fail, @"RefreshLoginAsync failed")
            });
        }