Files
social-media/backend/Modules/Identity/Handlers/Register.cs
Jonathan Bourdon df3e602015
Some checks failed
Backend CI/CD / build_and_deploy (push) Has been cancelled
Frontend CI/CD / build_and_deploy (push) Has been cancelled
feat: pivot to social media workflow app
2026-04-24 12:58:35 -04:00

80 lines
2.1 KiB
C#

using Socialize.Modules.Identity.Data;
using Socialize.Modules.Identity.Services;
using Microsoft.AspNetCore.Identity;
namespace Socialize.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);
}
}