52 lines
1.3 KiB
C#
52 lines
1.3 KiB
C#
using Hutopy.Infrastructure.Security;
|
|
using Hutopy.Modules.Identity.Data;
|
|
using Microsoft.AspNetCore.Identity;
|
|
|
|
namespace Hutopy.Modules.Identity.Handlers;
|
|
|
|
[PublicAPI]
|
|
public record SetPasswordRequest(
|
|
string NewPassword);
|
|
|
|
[PublicAPI]
|
|
public class SetPasswordHandler(
|
|
UserManager userManager)
|
|
: Endpoint<SetPasswordRequest>
|
|
{
|
|
public override void Configure()
|
|
{
|
|
Post("/api/users/set-password");
|
|
Options(o => o.WithTags("Users"));
|
|
}
|
|
|
|
public override async Task HandleAsync(
|
|
SetPasswordRequest request,
|
|
CancellationToken ct)
|
|
{
|
|
// Get current user id from claims
|
|
string userId = User.GetUserId().ToString();
|
|
|
|
// Get user from database
|
|
User? user = await userManager.FindByIdAsync(userId);
|
|
if (user is null)
|
|
{
|
|
await SendForbiddenAsync(ct);
|
|
return;
|
|
}
|
|
|
|
string resetToken = await userManager.GeneratePasswordResetTokenAsync(user);
|
|
IdentityResult result = await userManager.ResetPasswordAsync(user, resetToken, request.NewPassword);
|
|
|
|
if (!result.Succeeded)
|
|
{
|
|
await SendStringAsync(
|
|
result.Errors.First().Description,
|
|
400,
|
|
cancellation: ct);
|
|
return;
|
|
}
|
|
|
|
await SendOkAsync(ct);
|
|
}
|
|
}
|