public async Task <ActionResult <AuthToken> > UserLogIn(UserLoginDto data, [FromServices] IUsersService usersService, [FromServices] IUserPasswordAuthenticator authenticator, [FromQuery] bool saveAsCookie = false) { var authResult = await authenticator.AuthenticateAsync(data.EmailAddress, data.Password); if (authResult is null) { return(Unauthorized(new ErrorDto("authentication_failed", "Invalid login credentials."))); } var user = await usersService.GetUser(authResult.SubjectId) ?? throw new BaristaException("authentication_failed", "Could not retrieve authenticated user, please try again."); var validUntil = DateTimeOffset.UtcNow.AddHours(6); var token = GenerateToken(validUntil, new[] { new Claim(Claims.UserId, authResult.SubjectId.ToString("D")), new Claim(Claims.MeansId, authResult.MeansId.ToString("D")), new Claim(Claims.IsAdministrator, user.IsAdministrator.ToString()) }); if (saveAsCookie) { Response.Cookies.Append(JwtFromCookieLoadingMiddleware.JwtCookieName, token, new CookieOptions { HttpOnly = true, Expires = validUntil, SameSite = SameSiteMode.Lax, Domain = _configuration["JwtCookieDomain"], Secure = bool.Parse(_configuration["JwtCookieSecure"]) }); } return(new AuthToken( GenerateToken(validUntil, new[] { new Claim(Claims.UserId, authResult.SubjectId.ToString("D")), new Claim(Claims.MeansId, authResult.MeansId.ToString("D")), new Claim(Claims.IsAdministrator, user.IsAdministrator.ToString()) }), validUntil )); }
public async Task <ActionResult> ChangePassword(ChangePasswordDto newPwDto, [FromServices] IUserPasswordAuthenticator userPwAuthenticator, [FromServices] IMeansValueHasher pwHasher) { var userId = User.GetUserId(); var user = await _usersService.GetUser(userId); if (user is null) { return(NotFound()); } var authResult = await userPwAuthenticator.AuthenticateAsync(user.EmailAddress, newPwDto.OldPassword); if (authResult is null) { return(BadRequest(new ErrorDto("invalid_old_password", "The old password does not match. Please try again."))); } if (newPwDto.NewPassword != newPwDto.NewPasswordAgain) { return(BadRequest(new ErrorDto("invalid_new_passwords", "The new passwords do not match. Please try again."))); } return(await SendAndHandleOperationCommand(new UpdateAuthenticationMeansValue(authResult.MeansId, pwHasher.Hash(newPwDto.NewPassword)))); }