Ajoute une zone d'administration des utilisateurs
This commit is contained in:
@@ -1,9 +1,12 @@
|
||||
using System.Security.Claims;
|
||||
using System.Net.Mail;
|
||||
using ChessCubing.Server.Admin;
|
||||
using ChessCubing.Server.Auth;
|
||||
using ChessCubing.Server.Data;
|
||||
using ChessCubing.Server.Users;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
@@ -58,7 +61,10 @@ builder.Services
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddAuthorization(options =>
|
||||
{
|
||||
options.AddPolicy("AdminOnly", policy => policy.RequireRole("admin"));
|
||||
});
|
||||
builder.Services.AddHttpClient<KeycloakAuthService>();
|
||||
builder.Services.AddSingleton<MySqlUserProfileStore>();
|
||||
|
||||
@@ -116,6 +122,109 @@ app.MapPut("/api/users/me", async Task<IResult> (
|
||||
}
|
||||
}).RequireAuthorization();
|
||||
|
||||
var adminGroup = app.MapGroup("/api/admin")
|
||||
.RequireAuthorization("AdminOnly");
|
||||
|
||||
adminGroup.MapGet("/users", async Task<IResult> (
|
||||
KeycloakAuthService keycloak,
|
||||
MySqlUserProfileStore profileStore,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var identityUsersTask = keycloak.GetAdminUsersAsync(cancellationToken);
|
||||
var siteProfilesTask = profileStore.ListAsync(cancellationToken);
|
||||
|
||||
await Task.WhenAll(identityUsersTask, siteProfilesTask);
|
||||
|
||||
var siteProfilesBySubject = (await siteProfilesTask)
|
||||
.ToDictionary(profile => profile.Subject, StringComparer.Ordinal);
|
||||
|
||||
var users = (await identityUsersTask)
|
||||
.Select(identity => MapAdminSummary(identity, siteProfilesBySubject.GetValueOrDefault(identity.Subject)))
|
||||
.OrderByDescending(user => user.SiteProfileUpdatedUtc ?? user.AccountCreatedUtc ?? DateTime.MinValue)
|
||||
.ThenBy(user => user.Username, StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
return TypedResults.Ok(users);
|
||||
});
|
||||
|
||||
adminGroup.MapGet("/users/{subject}", async Task<IResult> (
|
||||
string subject,
|
||||
KeycloakAuthService keycloak,
|
||||
MySqlUserProfileStore profileStore,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var identityTask = keycloak.GetAdminUserAsync(subject, cancellationToken);
|
||||
var profileTask = profileStore.FindBySubjectAsync(subject, cancellationToken);
|
||||
|
||||
await Task.WhenAll(identityTask, profileTask);
|
||||
return TypedResults.Ok(MapAdminDetail(await identityTask, await profileTask));
|
||||
}
|
||||
catch (KeycloakAuthException exception)
|
||||
{
|
||||
return TypedResults.Json(new ApiErrorResponse(exception.Message), statusCode: exception.StatusCode);
|
||||
}
|
||||
});
|
||||
|
||||
adminGroup.MapPut("/users/{subject}", async Task<IResult> (
|
||||
string subject,
|
||||
AdminUpdateUserRequest request,
|
||||
KeycloakAuthService keycloak,
|
||||
MySqlUserProfileStore profileStore,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var normalized = NormalizeAdminUpdate(request);
|
||||
var fallbackDisplayName = BuildIdentityDisplayNameFromParts(normalized.FirstName, normalized.LastName, normalized.Username);
|
||||
var siteProfileRequest = new UpdateUserProfileRequest
|
||||
{
|
||||
DisplayName = request.DisplayName,
|
||||
Club = request.Club,
|
||||
City = request.City,
|
||||
PreferredFormat = request.PreferredFormat,
|
||||
FavoriteCube = request.FavoriteCube,
|
||||
Bio = request.Bio,
|
||||
};
|
||||
|
||||
profileStore.ValidateAdminUpdate(fallbackDisplayName, siteProfileRequest);
|
||||
|
||||
var updatedIdentity = await keycloak.UpdateAdminUserAsync(
|
||||
subject,
|
||||
new AdminIdentityUserUpdateRequest(
|
||||
normalized.Username,
|
||||
normalized.Email,
|
||||
normalized.FirstName,
|
||||
normalized.LastName,
|
||||
normalized.IsEnabled,
|
||||
normalized.IsEmailVerified),
|
||||
cancellationToken);
|
||||
|
||||
var updatedProfile = await profileStore.AdminUpsertAsync(
|
||||
updatedIdentity.Subject,
|
||||
updatedIdentity.Username,
|
||||
updatedIdentity.Email,
|
||||
BuildIdentityDisplayName(updatedIdentity),
|
||||
siteProfileRequest,
|
||||
cancellationToken);
|
||||
|
||||
return TypedResults.Ok(MapAdminDetail(updatedIdentity, updatedProfile));
|
||||
}
|
||||
catch (AdminUserValidationException exception)
|
||||
{
|
||||
return TypedResults.BadRequest(new ApiErrorResponse(exception.Message));
|
||||
}
|
||||
catch (UserProfileValidationException exception)
|
||||
{
|
||||
return TypedResults.BadRequest(new ApiErrorResponse(exception.Message));
|
||||
}
|
||||
catch (KeycloakAuthException exception)
|
||||
{
|
||||
return TypedResults.Json(new ApiErrorResponse(exception.Message), statusCode: exception.StatusCode);
|
||||
}
|
||||
});
|
||||
|
||||
app.MapPost("/api/auth/login", async Task<IResult> (
|
||||
LoginRequest request,
|
||||
HttpContext httpContext,
|
||||
@@ -184,6 +293,119 @@ app.MapPost("/api/auth/logout", async Task<IResult> (HttpContext httpContext) =>
|
||||
|
||||
app.Run();
|
||||
|
||||
static AdminUserSummaryResponse MapAdminSummary(AdminIdentityUser identity, UserProfileResponse? profile)
|
||||
=> new()
|
||||
{
|
||||
Subject = identity.Subject,
|
||||
Username = identity.Username,
|
||||
Email = identity.Email,
|
||||
IdentityDisplayName = BuildIdentityDisplayName(identity),
|
||||
SiteDisplayName = profile?.DisplayName,
|
||||
IsEnabled = identity.IsEnabled,
|
||||
IsEmailVerified = identity.IsEmailVerified,
|
||||
HasSiteProfile = profile is not null,
|
||||
Club = profile?.Club,
|
||||
City = profile?.City,
|
||||
PreferredFormat = profile?.PreferredFormat,
|
||||
AccountCreatedUtc = identity.CreatedUtc,
|
||||
SiteProfileUpdatedUtc = profile?.UpdatedUtc,
|
||||
};
|
||||
|
||||
static AdminUserDetailResponse MapAdminDetail(AdminIdentityUser identity, UserProfileResponse? profile)
|
||||
{
|
||||
var identityDisplayName = BuildIdentityDisplayName(identity);
|
||||
|
||||
return new AdminUserDetailResponse
|
||||
{
|
||||
Subject = identity.Subject,
|
||||
Username = identity.Username,
|
||||
Email = identity.Email,
|
||||
FirstName = identity.FirstName,
|
||||
LastName = identity.LastName,
|
||||
IdentityDisplayName = identityDisplayName,
|
||||
IsEnabled = identity.IsEnabled,
|
||||
IsEmailVerified = identity.IsEmailVerified,
|
||||
AccountCreatedUtc = identity.CreatedUtc,
|
||||
HasSiteProfile = profile is not null,
|
||||
DisplayName = profile?.DisplayName ?? identityDisplayName,
|
||||
Club = profile?.Club,
|
||||
City = profile?.City,
|
||||
PreferredFormat = profile?.PreferredFormat,
|
||||
FavoriteCube = profile?.FavoriteCube,
|
||||
Bio = profile?.Bio,
|
||||
SiteProfileCreatedUtc = profile?.CreatedUtc,
|
||||
SiteProfileUpdatedUtc = profile?.UpdatedUtc,
|
||||
};
|
||||
}
|
||||
|
||||
static NormalizedAdminUserUpdate NormalizeAdminUpdate(AdminUpdateUserRequest request)
|
||||
{
|
||||
var username = NormalizeRequiredValue(request.Username, "nom d'utilisateur", 120);
|
||||
var email = NormalizeEmail(request.Email);
|
||||
var firstName = NormalizeOptionalValue(request.FirstName, "prenom", 120);
|
||||
var lastName = NormalizeOptionalValue(request.LastName, "nom", 120);
|
||||
|
||||
return new NormalizedAdminUserUpdate(
|
||||
username,
|
||||
email,
|
||||
firstName,
|
||||
lastName,
|
||||
request.IsEnabled,
|
||||
request.IsEmailVerified);
|
||||
}
|
||||
|
||||
static string BuildIdentityDisplayName(AdminIdentityUser identity)
|
||||
=> BuildIdentityDisplayNameFromParts(identity.FirstName, identity.LastName, identity.Username);
|
||||
|
||||
static string BuildIdentityDisplayNameFromParts(string? firstName, string? lastName, string username)
|
||||
{
|
||||
var fullName = string.Join(' ', new[] { firstName, lastName }.Where(value => !string.IsNullOrWhiteSpace(value)));
|
||||
return string.IsNullOrWhiteSpace(fullName)
|
||||
? username
|
||||
: fullName;
|
||||
}
|
||||
|
||||
static string NormalizeRequiredValue(string? value, string fieldName, int maxLength)
|
||||
{
|
||||
var normalized = NormalizeOptionalValue(value, fieldName, maxLength);
|
||||
return normalized ?? throw new AdminUserValidationException($"Le champ {fieldName} est obligatoire.");
|
||||
}
|
||||
|
||||
static string? NormalizeEmail(string? value)
|
||||
{
|
||||
var normalized = NormalizeOptionalValue(value, "email", 255);
|
||||
if (normalized is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_ = new MailAddress(normalized);
|
||||
return normalized;
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
throw new AdminUserValidationException("L'email n'est pas valide.");
|
||||
}
|
||||
}
|
||||
|
||||
static string? NormalizeOptionalValue(string? value, string fieldName, int maxLength)
|
||||
{
|
||||
var trimmed = value?.Trim();
|
||||
if (string.IsNullOrWhiteSpace(trimmed))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (trimmed.Length > maxLength)
|
||||
{
|
||||
throw new AdminUserValidationException($"Le champ {fieldName} depasse {maxLength} caracteres.");
|
||||
}
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
static async Task SignInAsync(HttpContext httpContext, KeycloakUserInfo userInfo)
|
||||
{
|
||||
var claims = new List<Claim>();
|
||||
@@ -232,3 +454,11 @@ static async Task SignInAsync(HttpContext httpContext, KeycloakUserInfo userInfo
|
||||
|
||||
httpContext.User = principal;
|
||||
}
|
||||
|
||||
sealed record NormalizedAdminUserUpdate(
|
||||
string Username,
|
||||
string? Email,
|
||||
string? FirstName,
|
||||
string? LastName,
|
||||
bool IsEnabled,
|
||||
bool IsEmailVerified);
|
||||
|
||||
Reference in New Issue
Block a user