Exemplo n.º 1
0
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateRequestDto request)
        {
            // If validation fails, return error response
            if (!ModelState.IsValid)
            {
                return(ValidationProblem(ModelState));
            }

            // Authenticate user
            var result = await _signInManager.PasswordSignInAsync(request.Email, request.Password, isPersistent : false, lockoutOnFailure : false);

            if (result.Succeeded)
            {
                // Retrieve authenticated user if successfully authenticated
                var user = await _userManager.FindByEmailAsync(request.Email);

                // If email not yet confirmed, return error response
                if (!user.EmailConfirmed)
                {
                    return(Unauthorized(new ErrorDto(ErrorDto.EmailNotVerified, "Please verify your email address by clicking the link in the email you have been sent.")));
                }

                var tokenString = await _tokenGenerator.GenerateTokenForDefaultRole(user);

                // Return authentication token
                return(Ok(new AuthenticatedResponseDto
                {
                    Token = tokenString,
                }));
            }

            // If two factor auth is required, return success response
            if (result.RequiresTwoFactor)
            {
                return(Ok(new Require2FAResponseDto()));
            }

            // If user is locked out, return error response
            if (result.IsLockedOut)
            {
                return(Unauthorized(new ErrorDto(ErrorDto.UserLockedOut, "Account locked")));
            }

            // If authentication failed, return error response
            return(Unauthorized(new ErrorDto(ErrorDto.UserNotFound, "User not found matching the provided credentials")));
        }