Esempio n. 1
0
        public async Task <Result <TokenViewModel> > RefreshToken(TokenModel model)
        {
            // TODO check on null

            var principal = _jwtTokenHelper.GetPrincipalFromExpiredToken(model.AccessToken);

            var userId = principal.Claims.FirstOrDefault(x => x.Type == nameof(User.Id))?.Value;

            if (!int.TryParse(userId, out var result))
            {
                return(Result.Fail <TokenViewModel>(EC.UserNotFound, ET.UserNotFound));
            }

            var user = await _userRepository.GetUserByIdAsync(result);

            if (user == null || user.RefreshToken != model.RefreshToken)
            {
                return(Result.Fail <TokenViewModel>(EC.UserNotFound, ET.UserNotFound));
            }

            var newJwtToken     = _jwtTokenHelper.GenerateToken(user);
            var newRefreshToken = _jwtTokenHelper.GenerateRefreshToken(user);

            user.RefreshToken = newRefreshToken;
            _userRepository.Put(user);
            await _unitOfWorks.CommitAsync();

            var tokenViewModel = new TokenViewModel
            {
                RefreshToken = newRefreshToken,
                AccessToken  = new AccessToken
                {
                    Token     = newJwtToken,
                    ExpiresIn = _globalSettings.Jwt.Expiration
                }
            };

            return(Result.OK(tokenViewModel));
        }