Exemplo n.º 1
0
        /// <inheritdoc />
        public async Task <Result <TokenResponse> > Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            Result <Email> emailResult = Email.Create(request.Email);

            if (emailResult.IsFailure)
            {
                return(Result.Failure <TokenResponse>(DomainErrors.Authentication.InvalidEmailOrPassword));
            }

            Maybe <User> maybeUser = await _userRepository.GetByEmailAsync(emailResult.Value);

            if (maybeUser.HasNoValue)
            {
                return(Result.Failure <TokenResponse>(DomainErrors.Authentication.InvalidEmailOrPassword));
            }

            User user = maybeUser.Value;

            bool passwordValid = user.VerifyPasswordHash(request.Password, _passwordHashChecker);

            if (!passwordValid)
            {
                return(Result.Failure <TokenResponse>(DomainErrors.Authentication.InvalidEmailOrPassword));
            }

            string token = _jwtProvider.Create(user);

            return(Result.Success(new TokenResponse(token)));
        }
        public async Task <AuthDto> HandleAsync(UseRefreshToken request)
        {
            var token = await _refreshTokenRepository.GetAsync(request.RefreshToken);

            if (token is null)
            {
                throw new InvalidRefreshTokenException();
            }

            if (token.Revoked)
            {
                throw new RevokedRefreshTokenException();
            }

            var user = await _userRepository.GetAsync(token.UserId);

            if (user is null)
            {
                throw new UserNotFoundException(token.UserId);
            }

            var auth = _jwtProvider.Create(token.UserId, user.Role);

            auth.RefreshToken = request.RefreshToken;

            return(auth);
        }
        public async Task HandleAsync(UseRefreshToken command)
        {
            var token = await _refreshTokenRepository.GetAsync(command.RefreshToken);

            if (token is null)
            {
                throw new InvalidRefreshTokenException();
            }

            if (token.Revoked)
            {
                throw new RevokedRefreshTokenException();
            }

            var user = await _userRepository.GetAsync(token.UserId);

            if (user is null)
            {
                throw new UserNotFoundException(token.UserId);
            }

            var claims = user.Permissions.Any()
                ? new Dictionary <string, IEnumerable <string> >
            {
                ["permissions"] = user.Permissions
            }
                : null;
            var auth = _jwtProvider.Create(token.UserId, user.Name, user.Role, claims: claims);

            auth.RefreshToken = command.RefreshToken;
            _storage.Set(command.Id, auth);
        }
Exemplo n.º 4
0
        public async Task <AuthDto> UseAsync(string refreshToken)
        {
            var token = await _refreshTokenRepository.GetAsync(refreshToken);

            if (token is null)
            {
                throw new InvalidRefreshTokenException();
            }

            if (token.Revoked)
            {
                throw new RevokedRefreshTokenException();
            }

            var user = await _userRepository.GetAsync(token.UserId);

            if (user is null)
            {
                throw new UserNotFoundException(token.UserId);
            }

            var claims = user.Permissions.Any()
                ? new Dictionary <string, IEnumerable <string> >
            {
                ["permissions"] = user.Permissions
            }
                : null;
            var auth = _jwtProvider.Create(token.UserId, user.Role, claims: claims);

            auth.RefreshToken = refreshToken;

            return(auth);
        }
        public async Task <AuthDto> SignInAsync(SignIn command)
        {
            if (!EmailRegex.IsMatch(command.Email))
            {
                throw new InvalidEmailException(command.Email);
            }

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

            if (user is null || !_passwordService.IsValid(user.Password, command.Password))
            {
                throw new InvalidCredentialException(command.Email);
            }

            var claims = user.Permissions.Any()
                ? new Dictionary <string, IEnumerable <string> >
            {
                ["permissions"] = user.Permissions
            }
                : null;

            var auth = _jwtProvider.Create(user.Id, user.Role, claims: claims);

            auth.RefreshToken = await _refreshTokenService.CreateAsync(user.Id);

            return(auth);
        }
        public async Task HandleAsync(SignIn command)
        {
            var user = await _userRepository.GetByNameAsync(command.Name);

            if (user is null || !_passwordService.IsValid(user.Password, command.Password))
            {
                _logger.LogError($"User with name: {command.Name} was not found.");
                throw new InvalidCredentialsException(command.Name);
            }

            if (user.Locked)
            {
                throw new UserLockedException(user.Id);
            }

            var claims = user.Permissions.Any()
                ? new Dictionary <string, IEnumerable <string> >
            {
                ["permissions"] = user.Permissions
            }
                : null;
            var auth = _jwtProvider.Create(user.Id, user.Name, user.Role, claims: claims);

            auth.RefreshToken = await CreateRefreshTokenAsync(user.Id);

            _storage.Set(command.Id, auth);
            _logger.LogInformation($"User with ID: {user.Id} has been authenticated.");
            await _messageBroker.PublishAsync(new SignedIn(user.Id));
        }
Exemplo n.º 7
0
    public async Task <AuthDto> UseAsync(string refreshToken)
    {
        var token = await _refreshTokenRepository.Get(refreshToken);

        if (token is null)
        {
            throw new InvalidRefreshTokenException();
        }

        if (DateTime.Compare(DateTime.Now, token.RevokedAt.Value) > 0)
        {
            throw new RevokedRefreshTokenException();
        }

        var user = await _userRepository.FindAsync(token.UserId);

        if (user is null)
        {
            throw new UserNotFoundException(token.UserId);
        }

        var auth = _jwtProvider.Create(token.UserId, user.Email, user.Role);
        await _refreshTokenRepository.Update(new(token.Id, token.Token,
                                                 DateTime.UtcNow, token.UserId, DateTime.UtcNow.AddDays(7)));

        auth.RefreshToken = refreshToken;

        return(auth);
    }
        /// <inheritdoc />
        public async Task <Result <TokenResponse> > Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            Result <FirstName> firstNameResult = FirstName.Create(request.FirstName);
            Result <LastName>  lastNameResult  = LastName.Create(request.LastName);
            Result <Email>     emailResult     = Email.Create(request.Email);
            Result <Password>  passwordResult  = Password.Create(request.Password);

            Result firstFailureOrSuccess = Result.FirstFailureOrSuccess(firstNameResult, lastNameResult, emailResult, passwordResult);

            if (firstFailureOrSuccess.IsFailure)
            {
                return(Result.Failure <TokenResponse>(firstFailureOrSuccess.Error));
            }

            if (!await _userRepository.IsEmailUniqueAsync(emailResult.Value))
            {
                return(Result.Failure <TokenResponse>(DomainErrors.User.DuplicateEmail));
            }

            string passwordHash = _passwordHasher.HashPassword(passwordResult.Value);

            var user = User.Create(firstNameResult.Value, lastNameResult.Value, emailResult.Value, passwordHash);

            _userRepository.Insert(user);

            await _unitOfWork.SaveChangesAsync(cancellationToken);

            string token = _jwtProvider.Create(user);

            return(Result.Success(new TokenResponse(token)));
        }
Exemplo n.º 9
0
        public void AuthorizeUser(DomainUserDto userDto, HttpContext context)
        {
            var jwt = _jwtProvider.Create(userDto, userDto.Roles);

            context.User        = new ClaimsPrincipal(jwt.Identity);
            userDto.AccessToken = jwt.AccessToken;
        }
        public async Task <AuthDto> SignInAsync(SignIn command)
        {
            if (!EmailRegex.IsMatch(command.Email))
            {
                _logger.LogError($"Invalid email: {command.Email}");
                throw new InvalidEmailException(command.Email);
            }

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

            if (user is null || !_passwordService.IsValid(user.Password, command.Password))
            {
                _logger.LogError($"User with email: {command.Email} was not found.");
                throw new InvalidCredentialsException(command.Email);
            }

            var claims = user.Permissions.Any()
               ? new Dictionary <string, IEnumerable <string> >
            {
                ["permissions"] = user.Permissions
            }
               : null;

            var auth = _jwtProvider.Create(user.Id, user.Role, claims: claims);

            auth.RefreshToken = await _refreshTokenService.CreateAsync(user.Id);

            _logger.LogInformation($"User with id: {user.Id} has been authenticated.");
            await _messageBroker.PublishAsync(new SignedIn(user.Id, user.Role));

            return(auth);
        }
Exemplo n.º 11
0
        public async Task <JwtDto> SignInAsync(SignIn command)
        {
            if (!EmailRegex.IsMatch(command.Email))
            {
                var exception = new InvalidCredentialsException(command.Email);
                await _messageBroker.PublishAsync(new SignInRejected(command.Email, exception.Message, exception.Code));

                throw exception;
            }

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

            if (user is null || !_passwordService.IsValid(user.Password, command.Password))
            {
                var exception = new InvalidCredentialsException(command.Email);
                await _messageBroker.PublishAsync(new SignInRejected(command.Email, exception.Message, exception.Code));

                throw exception;
            }

            var token = _jwtProvider.Create(user.Id, user.Role);
            await _messageBroker.PublishAsync(new SignedIn(user.Id, user.Role));

            return(token);
        }
Exemplo n.º 12
0
        public async Task <JwtDto> SignInAsync(SignIn command)
        {
            if (!EmailRegex.IsMatch(command.Email))
            {
                _logger.LogWarning($"Invalid email address: {command.Email}.");
                var exception = new InvalidCredentialsException(command.Email);
                await _messageBroker.PublishAsync(new SignInRejected(command.Email, exception.Message, exception.Code));

                throw exception;
            }

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

            if (user is null || !_passwordService.IsValid(user.Password, command.Password))
            {
                var exception = new InvalidCredentialsException(command.Email);
                await _messageBroker.PublishAsync(new SignInRejected(command.Email, exception.Message, exception.Code));

                throw exception;
            }

            var token = _jwtProvider.Create(user.Id, user.Role);
            await _messageBroker.PublishAsync(new SignedIn(user.Id, user.Role));

            _logger.LogInformation($"User with id: {user.Id} has been authenticated.");

            return(token);
        }
        public async Task <AuthDto> HandleAsync(SignIn request)
        {
            if (!EmailRegex.IsMatch(request.Email))
            {
                _logger.LogWarning($"Invalid email: {request.Email}");
                throw new InvalidEmailException(request.Email);
            }

            var user = await _userRepository.GetAsync(request.Email);

            if (user is null)
            {
                _logger.LogWarning($"User with email: {request.Email} was not found.");
                throw new InvalidCredentialsException(request.Email);
            }

            if (user.IsLockedOut)
            {
                throw new UserLockedOutException(user.LockoutEnd.Subtract(DateTime.Now).Hours);
            }

            if (!_passwordService.IsValid(user.Password, request.Password))
            {
                _logger.LogWarning($"Invalid authentication for user with id: {user.Id.Value}", user);
                user.InvalidLogin();
                await _userRepository.UpdateAsync(user);

                if (user.IsLockedOut)
                {
                    _logger.LogWarning($"Locked out user with Id: {user.Id.Value}", user);

                    throw new UserLockedOutException(user.LockoutEnd.Subtract(DateTime.Now).Hours);
                }

                throw new InvalidCredentialsException(request.Email);
            }

            var claims = user.Permissions.Any()
                ? new Dictionary <string, IEnumerable <string> >
            {
                ["permissions"] = user.Permissions
            }
                : null;
            var auth = _jwtProvider.Create(user.Id, user.Role, claims: claims);

            auth.RefreshToken = await _refreshTokenService.CreateAsync(user.Id);

            user.ValidLogin();
            await _userRepository.UpdateAsync(user);


            _logger.LogInformation($"User with id: {user.Id} has been authenticated.", user);
            await _messageBroker.PublishAsync(new SignedIn(user.Id, user.Role));

            return(auth);
        }
Exemplo n.º 14
0
        public void AuthorizeUser(JwtUserDto userDto, HttpContext context)
        {
            var jwt = _jwtProvider.Create(userDto, userDto.Roles);

            jwt.Claims.TryGetValue(JwtRegisteredClaimNames.GivenName, out var firstName);
            jwt.Claims.TryGetValue(JwtRegisteredClaimNames.FamilyName, out var lastName);

            context.User        = new ClaimsPrincipal(jwt.Identity);
            userDto.AccessToken = jwt.AccessToken;
            userDto.Id          = jwt.Id;
            userDto.FirstName   = firstName;
            userDto.LastName    = lastName;
        }
Exemplo n.º 15
0
        public async Task <AuthDto> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var user = await _userManager.FindByEmailAsync(request.Email);

            // var isPasswordCorrect = await _userManager.CheckPasswordAsync(user, request.Password);
            // Console.Write($"User Detail {user.Email} Password Result {isPasswordCorrect}");
            if (user != null && await _userManager.CheckPasswordAsync(user, request.Password))
            {
                var identity = new ClaimsIdentity();
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.Email));

                // user logged in
                string role = user.IsAdmin ? "Admin" : "User";
                return(_jwtProvider.Create(user, role));
            }
            Console.Write(user);
            throw new InvalidCredentialsException(request.Email);
        }
Exemplo n.º 16
0
        public async Task <JsonWebToken> SignInAsync(SignIn command)
        {
            var user = _users.SingleOrDefault(x => x.Username == command.Username);

            if (user == null)
            {
                throw new Exception("Invalid credentials.");
            }

            var passwordResult = _passwordHasher.VerifyHashedPassword(user,
                                                                      user.Password, command.Password);

            if (passwordResult == PasswordVerificationResult.Failed)
            {
                throw new Exception("Invalid credentials.");
            }

            await Task.CompletedTask;

            return(_jwtProvider.Create(user.Id, user.Role));
        }
Exemplo n.º 17
0
        public async Task <AuthDto> SignInAsync(SignIn command)
        {
            var user = await _userRepository.GetByUserNameAsync(command.UserName);

            if (user is null)
            {
                _logger.LogError($"User with user name: {command.UserName} was not found.");
                throw new InvalidCredentialsException(command.UserName);
            }

            if (!_passwordService.IsValid(user.Password, command.Password))
            {
                _logger.LogError($"Invalid password for user with id: {user.Id.Value}");
                throw new InvalidCredentialsException(command.UserName);
            }

            var auth = _jwtProvider.Create(user.Id, "user");

            _logger.LogInformation($"User with id: {user.Id} has been authenticated.");

            return(auth);
        }
Exemplo n.º 18
0
        public IActionResult Login()
        {
            JwtToken token = _jwtProvider.Create("1", "*****@*****.**", null);

            return(Json(token));
        }