Files
social-media/backend/Modules/Identity/Handlers/Register.cs

80 lines
2.1 KiB
C#

using Hutopy.Modules.Identity.Data;
using Hutopy.Modules.Identity.Services;
using Microsoft.AspNetCore.Identity;
namespace Hutopy.Modules.Identity.Handlers;
[PublicAPI]
public record RegisterRequest(
string Email,
string Password,
string Name);
[PublicAPI]
public record RegisterResponse(
string Message);
[PublicAPI]
public class RegisterHandler(
UserManager userManager,
EmailVerificationService emailVerificationService)
: Endpoint<RegisterRequest, RegisterResponse>
{
public override void Configure()
{
AllowAnonymous();
Post("/api/users/register");
Options(o => o.WithTags("Users"));
}
public override async Task HandleAsync(
RegisterRequest request,
CancellationToken ct)
{
// Check if the user already exists
User? existingUser = await userManager.FindByEmailAsync(request.Email);
if (existingUser is not null)
{
await SendStringAsync(
"A user with this email already exists",
400,
cancellation: ct);
return;
}
// Split the name into firstname and lastname (if provided)
string[] nameParts = request.Name.Split(' ', 2);
string firstname = nameParts[0];
string lastname = nameParts.Length > 1 ? nameParts[1] : string.Empty;
// Create a new user
User user = new()
{
UserName = request.Email,
Email = request.Email,
Firstname = firstname,
Lastname = lastname,
Alias = request.Name
};
IdentityResult result = await userManager.CreateAsync(
user,
request.Password);
if (!result.Succeeded)
{
await SendStringAsync(
result.Errors.First().Description,
400,
cancellation: ct);
return;
}
await emailVerificationService.SendVerificationEmailAsync(user);
await SendOkAsync(
new RegisterResponse("Registration successful! Please check your email to verify your account."),
ct);
}
}