using System.Globalization; using Titano.Core.Model; using Titano.Data; using Titano.Protocol; using Titano.Server.Security; namespace Titano.Server.Api; /// /api/v1/users (admin): accounts, roles, quotas, render-node right, temporary passwords. public static class UserEndpoints { private const int MaxDisplayName = 100; public static void Map(RouteGroupBuilder api) { var users = api.MapGroup("/users").Requires(Permissions.ManageUsers); users.MapGet("", ListAsync); users.MapPost("", CreateAsync); users.MapGet("/{id:guid}", GetAsync); users.MapPatch("/{id:guid}", UpdateAsync); users.MapDelete("/{id:guid}", DeleteAsync); users.MapPost("/{id:guid}/reset-password", ResetPasswordAsync); } private static async Task ListAsync(HttpContext context, TitanoDatabase db, TimeProvider time) { var ct = context.RequestAborted; var users = await db.Users.ListAsync(ct); var latest = await db.Tokens.LatestByUserAsync(ct); var uploads = await db.Uploads.CommittedCountByUserAsync(time.GetUtcNow().AddDays(-30), ct); var rows = users.Select(u => { var token = latest.GetValueOrDefault(u.Id); return new UserSummaryDto(Dto.User(u), token?.LastUsed ?? u.LastLogin, token?.ClientName, uploads.GetValueOrDefault(u.Id)); }).ToList(); return Results.Json(rows, ProtocolJson.Default.ListUserSummaryDto); } private static async Task GetAsync(HttpContext context, Guid id, TitanoDatabase db) => await db.Users.GetAsync(id, context.RequestAborted) is { } user ? Results.Json(Dto.User(user), ProtocolJson.Default.UserDto) : ApiErrors.NotFound(context, "user"); private static async Task CreateAsync(HttpContext context, Caller caller, CreateUserRequest request, TitanoDatabase db, AuditLog audit, TimeProvider time) { var username = request.Username?.Trim(); if (!Accounts.IsValidUsername(username)) return ApiErrors.BadRequest(context, "invalid_username"); if (!Accounts.TryParseRole(request.Role, out var role)) return ApiErrors.BadRequest(context, "invalid_role"); if (request.QuotaBytes < 0) return ApiErrors.BadRequest(context, "bad_request", "quotaBytes"); var password = string.IsNullOrEmpty(request.Password) ? TemporaryPassword.Generate() : request.Password; if (!PasswordHasher.IsAcceptable(password)) return WeakPassword(context); var user = new User { Id = Guid.CreateVersion7(), Username = username!, DisplayName = Clean(request.DisplayName), PasswordHash = PasswordHasher.Hash(password), Role = role, Permissions = Accounts.PermissionsFor(role, request.AllowRenderNode), QuotaBytes = request.QuotaBytes, MustChangePassword = true, Created = time.GetUtcNow(), }; try { await db.Users.CreateAsync(user, context.RequestAborted); } catch (DatabaseException ex) when (ex.IsUniqueViolation) { return ApiErrors.Conflict(context, "username_taken"); } await audit.WriteAsync(caller, context, "user_created", "user", user.Id.ToString(), $"{user.Username} · {Dto.Role(role)}"); return Results.Json(new TemporaryPasswordResponse(Dto.User(user), password), ProtocolJson.Default.TemporaryPasswordResponse, statusCode: StatusCodes.Status201Created); } private static async Task UpdateAsync(HttpContext context, Caller caller, Guid id, UpdateUserRequest request, TitanoDatabase db, AuditLog audit) { var ct = context.RequestAborted; if (await db.Users.GetAsync(id, ct) is not { } user) return ApiErrors.NotFound(context, "user"); var role = user.Role; if (request.Role is not null && !Accounts.TryParseRole(request.Role, out role)) return ApiErrors.BadRequest(context, "invalid_role"); if (request.QuotaBytes < 0) return ApiErrors.BadRequest(context, "bad_request", "quotaBytes"); var updated = user with { DisplayName = request.DisplayName is null ? user.DisplayName : Clean(request.DisplayName), Role = role, Permissions = Accounts.PermissionsFor(role, request.AllowRenderNode ?? user.Permissions.HasFlag(Permissions.RenderNode)), QuotaBytes = request.QuotaBytes ?? user.QuotaBytes, Disabled = request.Disabled ?? user.Disabled, }; var losesAdmin = IsActiveAdmin(user) && !IsActiveAdmin(updated); if (losesAdmin && user.Id == caller.Id) return ApiErrors.Conflict(context, "self"); if (losesAdmin && !await HasOtherActiveAdminAsync(db, user.Id, ct)) return ApiErrors.Conflict(context, "last_admin"); await db.Users.UpdateAsync(updated, ct); if (updated.Disabled && !user.Disabled) await db.Tokens.RevokeAllAsync(id, ct); await audit.WriteAsync(caller, context, "user_updated", "user", id.ToString(), Changes(user, updated)); return Results.Json(Dto.User(updated), ProtocolJson.Default.UserDto); } private static async Task DeleteAsync(HttpContext context, Caller caller, Guid id, TitanoDatabase db, AuditLog audit) { var ct = context.RequestAborted; if (id == caller.Id) return ApiErrors.Conflict(context, "self"); if (await db.Users.GetAsync(id, ct) is not { } user) return ApiErrors.NotFound(context, "user"); if (IsActiveAdmin(user) && !await HasOtherActiveAdminAsync(db, id, ct)) return ApiErrors.Conflict(context, "last_admin"); // Render jobs of the user's nodes go back to the queue before the nodes disappear with the account. foreach (var node in (await db.RenderNodes.ListAsync(ct)).Where(n => n.UserId == id)) await db.Jobs.RequeueRunningAsync(node.Id.ToString(), ct); var reassigned = await db.Sequences.ReassignOwnerAsync(id, caller.Id, ct); await db.Users.DeleteAsync(id, ct); await audit.WriteAsync(caller, context, "user_deleted", "user", id.ToString(), $"{user.Username} · {reassigned.ToString(CultureInfo.InvariantCulture)}"); return Results.NoContent(); } private static async Task ResetPasswordAsync(HttpContext context, Caller caller, Guid id, ResetPasswordRequest? request, TitanoDatabase db, AuditLog audit) { var ct = context.RequestAborted; if (await db.Users.GetAsync(id, ct) is not { } user) return ApiErrors.NotFound(context, "user"); var password = string.IsNullOrEmpty(request?.Password) ? TemporaryPassword.Generate() : request.Password; if (!PasswordHasher.IsAcceptable(password)) return WeakPassword(context); var updated = user with { PasswordHash = PasswordHasher.Hash(password), MustChangePassword = true }; await db.Users.UpdateAsync(updated, ct); await db.Tokens.RevokeAllAsync(id, ct); await audit.WriteAsync(caller, context, "password_reset", "user", id.ToString(), user.Username); return Results.Json(new TemporaryPasswordResponse(Dto.User(updated), password), ProtocolJson.Default.TemporaryPasswordResponse); } private static bool IsActiveAdmin(User user) => user.Role == UserRole.Admin && !user.Disabled; private static async Task HasOtherActiveAdminAsync(TitanoDatabase db, Guid except, CancellationToken ct) => (await db.Users.ListAsync(ct)).Any(u => u.Id != except && IsActiveAdmin(u)); private static IResult WeakPassword(HttpContext context) => ApiErrors.BadRequest(context, "weak_password", PasswordHasher.MinimumLength.ToString(CultureInfo.InvariantCulture), PasswordHasher.MinimumLength); private static string? Clean(string? displayName) { var trimmed = displayName?.Trim(); return string.IsNullOrEmpty(trimmed) ? null : trimmed[..Math.Min(trimmed.Length, MaxDisplayName)]; } /// Audit detail listing the fields an edit changed (never secrets). private static string Changes(User before, User after) { var changes = new List(); if (before.DisplayName != after.DisplayName) changes.Add("displayName"); if (before.Role != after.Role) changes.Add("role=" + Dto.Role(after.Role)); if (before.Permissions != after.Permissions) changes.Add("permissions"); if (before.QuotaBytes != after.QuotaBytes) changes.Add("quota=" + after.QuotaBytes.ToString(CultureInfo.InvariantCulture)); if (before.Disabled != after.Disabled) changes.Add(after.Disabled ? "disabled" : "enabled"); return string.Join(", ", changes); } }