public ActionResult <AuthenticateAccountResponse> Login([FromBody] AuthenticateAccountRequest request) { // Authenticate the account try { var response = _accountService.Authenticate(request); _logger.LogInformation("(AccountId: {accountId}, EmailAddress: {emailAddress}) logged in successfully", response.AccountId, response.EmailAddress); return(Ok(response)); } catch (Exception e) { _logger.LogWarning(e, "Email address {emailAddress} login failed!", request.EmailAddress); // Default status code int httpStatusCode = (int)HttpStatusCode.InternalServerError; if (e is AuthenticationFailedException) { // Status code if authentication failed httpStatusCode = (int)HttpStatusCode.Unauthorized; } return(StatusCode(httpStatusCode, e.GetType().Name)); } }
public AuthenticateAccountResponse Authenticate(AuthenticateAccountRequest request) { // Get the account if it exists var account = _context.Accounts.SingleOrDefault(x => x.EmailAddress == request.EmailAddress); // Gernerate password hash and test. Throw exception if email doesn't exists or password incorrect if (account == null || !BC.Verify(request.Password, account.PasswordHash)) { throw new AuthenticationFailedException(); } // Create a response that includes the access token var response = new AuthenticateAccountResponse { AccountId = account.AccountId, UserFullName = account.UserFullName, EmailAddress = account.EmailAddress, AccessToken = GenerateJsonWebToken(account) }; return(response); }