public async Task <LoginResponseModel> LoginUser(LoginRequestModel model)
        {
            var getUserIdByCredentialsRequest = new GetUserIdByCredentialsRequest
            {
                Email    = model.Email,
                Password = _sha512Service.GetBase64Hash(model.Password)
            };

            var userIdResponse = await _userManagementService.GetIdByCredentials(getUserIdByCredentialsRequest);

            var randomString = _randomStringService.GetRandomString(128);

            var accessToken = _accessTokenService.Create(new UserAccessTokenPayload
            {
                Id = userIdResponse.Id
            }, randomString);

            await _userManagementService.UpdateRefreshToken(new UpdateUserRefreshTokenRequest
            {
                Id           = userIdResponse.Id,
                RefreshToken = randomString
            });

            return(new LoginResponseModel
            {
                RefreshToken = randomString,
                AccessToken = accessToken
            });
        }
Ejemplo n.º 2
0
        public async Task <TokenResponse> Handle(SignUpCommand request, CancellationToken cancellationToken)
        {
            var otherUser = await _userRepository.GetByEmailAsync(request.Email);

            if (otherUser != null)
            {
                throw new IdentityDomainException("Other user has the same email");
            }

            var password = _passwordHasher.Hash(request.Password);
            var user     = new User(request.Email, password, Role.User);

            user.SetLastLoginToNow();
            _userRepository.AddUser(user);

            await _userRepository.UnitOfWork.SaveChangesAndDispatchDomainEventsAsync(cancellationToken);

            var userClaims   = user.ExtractUserClaims();
            var accessToken  = _accessTokenService.Create(userClaims);
            var refreshToken = await _refreshTokenService.GetOrCreateAsync(user);

            _httpContext.Response.Cookies.Append("accessToken", accessToken, CookieSettings.PrivateCookie);
            _httpContext.Response.Cookies.Append("refreshToken", refreshToken.Token, CookieSettings.PrivateCookie);

            var accessTokenExp = DateTimeOffset.UtcNow
                                 .AddMinutes(_jwtConfig.AccessTokenExpirationInMinutes).ToUnixTimeSeconds();

            _httpContext.Response.Cookies.Append("accessTokenExp", $"{accessTokenExp}", CookieSettings.PublicCookie);

            return(new TokenResponse
            {
                AccessToken = accessToken,
                RefreshToken = refreshToken.Token
            });
        }
        public async Task <TokenResponse> Handle(SignInCommand request, CancellationToken cancellationToken)
        {
            var user = await _userRepository.GetByEmailAsync(request.Email);

            if (user == null)
            {
                throw new UnauthorizedException();
            }

            var isPasswordValid = _passwordHasher.Verify(request.Password, user.HashedPassword);

            if (!isPasswordValid)
            {
                throw new UnauthorizedException();
            }

            if (user.IsLocked)
            {
                throw new ForbiddenException();
            }

            var userClaims   = user.ExtractUserClaims();
            var accessToken  = _accessTokenService.Create(userClaims);
            var refreshToken = await _refreshTokenService.GetOrCreateAsync(user);

            user.SetLastLoginToNow();

            _userRepository.Update(user);
            await _userRepository.UnitOfWork.SaveChangesAndDispatchDomainEventsAsync(cancellationToken);

            _httpContext.Response.Cookies.Append("accessToken", accessToken, CookieSettings.PrivateCookie);
            _httpContext.Response.Cookies.Append("refreshToken", refreshToken.Token, CookieSettings.PrivateCookie);

            var accessTokenExp = DateTimeOffset.UtcNow
                                 .AddMinutes(_jwtConfig.AccessTokenExpirationInMinutes).ToUnixTimeSeconds();

            _httpContext.Response.Cookies.Append("accessTokenExp", $"{accessTokenExp}", CookieSettings.PublicCookie);

            return(new TokenResponse
            {
                AccessToken = accessToken,
                RefreshToken = refreshToken.Token
            });
        }
Ejemplo n.º 4
0
        public async Task <string> RefreshAccessToken(string refreshTokenStr)
        {
            var decodedRefreshToken = _refreshTokenDecoder.Decode(refreshTokenStr);

            if (decodedRefreshToken == null)
            {
                _logger.LogWarning("Cannot refresh access token - decoding failure");
                return(null);
            }

            var refreshToken = await _refreshTokenRepository.GetByIdAsync(decodedRefreshToken.Id);

            if (refreshToken?.IsRevoked ?? false)
            {
                _logger.LogWarning("Cannot refresh access token - no such refresh token or token is revoked");
                return(null);
            }

            return(_accessTokenService.Create(decodedRefreshToken.UserClaims));
        }
Ejemplo n.º 5
0
        private async Task <AccessTokenModel> GenerateRefreshAndAccessToken(Guid userId)
        {
            var refreshToken = _randomStringGenerationService.Generate(length: 128);

            var token = _accessTokenService.Create(new AuthPayload
            {
                UserId = userId
            },
                                                   refreshToken);

            await CommandBus.Execute(new SetRefreshTokenCommand
            {
                UserId       = userId,
                RefreshToken = refreshToken
            });

            return(new AccessTokenModel
            {
                RefreshToken = refreshToken,
                AccessToken = token
            });
        }