Example #1
0
        public override async Task <AuthenticateCommand> HandleAsync(AuthenticateCommand command, CancellationToken cancellationToken = new CancellationToken())
        {
            var account = await _accountRepository.GetAccountByEmail(command.Email, cancellationToken);

            if (account == null || !account.IsVerified || !BC.Verify(command.Password, account.PasswordHash))
            {
                throw new UnauthorizedException();
            }

            var jwtToken     = _tokenGenerator.GenerateJwtToken(account);
            var refreshToken = _tokenGenerator.GenerateRefreshToken(_ipAddressGetter.GetIPAddressFromRequest());

            await _accountRepository.AddRefreshToken(refreshToken, account.Id, cancellationToken);

            await _accountRepository.RemoveOldRefreshTokens(account, _settings.RefreshTokenTTLInDays, cancellationToken);

            command.Response = new TokenResponse
            {
                Account      = account,
                JwtToken     = jwtToken,
                RefreshToken = refreshToken.Token
            };

            return(await base.HandleAsync(command, cancellationToken));
        }
Example #2
0
        public override async Task <RefreshTokenCommand> HandleAsync(RefreshTokenCommand command, CancellationToken cancellationToken = default)
        {
            _logger.LogInformation("Refreshing token");

            if (command.Token == null)
            {
                _logger.LogInformation("Refresh token provided is null");
                throw new BadRequestException();
            }
            var refreshToken = await _accountRepository.GetRefreshToken(command.Token, cancellationToken);

            if (refreshToken == null)
            {
                _logger.LogInformation("Refresh token provided is invalid/not issued");
                throw new NotFoundException();
            }

            var account = await _accountRepository.GetAccountById(refreshToken.AccountId, cancellationToken);

            if (account == null)
            {
                _logger.LogInformation("Account related to Refresh token not found");
                throw new NotFoundException();
            }

            var ipAddress = _ipAddressGetter.GetIPAddressFromRequest();

            var newRefreshToken = _tokenGenerator.GenerateRefreshToken(ipAddress);

            await _accountRepository.RevokeRefreshToken(refreshToken.Token, ipAddress, newRefreshToken.Token, cancellationToken);

            await _accountRepository.RemoveOldRefreshTokens(account, _settings.RefreshTokenTTLInDays, cancellationToken);

            var jwtToken = _tokenGenerator.GenerateJwtToken(account);

            command.Response = new TokenResponse
            {
                Account      = account,
                JwtToken     = jwtToken,
                RefreshToken = refreshToken.Token
            };

            return(await base.HandleAsync(command, cancellationToken));
        }