using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Nexus.Api.Data; using Nexus.Api.DTOs; using Nexus.Api.Repositories; using Nexus.Api.Services; namespace Nexus.Api.Controllers; [ApiController] [Route("api/v1/admin")] [Authorize(Roles = "owner")] public class AdminController( IUserRepository userRepository, ILogger logger) : ControllerBase { /// /// List all registered users. /// [HttpGet("users")] public async Task GetUsers(CancellationToken ct) { var users = await userRepository.GetAllAsync(ct); var result = users.Select(u => new AdminUserInfo { Id = u.Id, Email = u.Email, DisplayName = u.DisplayName, Role = u.Role, CreatedAt = u.CreatedAt, LastLoginAt = u.LastLoginAt, }).ToList(); return Results.Ok(result); } /// /// Create a new user account (admin only). /// Email muss eindeutig sein, Passwort mindestens 10 Zeichen. /// [HttpPost("users")] public async Task CreateUser([FromBody] AdminCreateUserRequest request, CancellationToken ct) { if (string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.Password)) return Results.ValidationProblem(new Dictionary { ["request"] = ["Email and password are required."] }); if (request.Password.Length < 10) return Results.ValidationProblem(new Dictionary { ["password"] = ["Password must be at least 10 characters."] }); var normalizedEmail = AuthService.NormalizeEmail(request.Email); var existing = await userRepository.GetByEmailAsync(normalizedEmail, ct); if (existing is not null) return Results.Conflict(new { error = "A user with this email already exists." }); var user = new NexusUser { Email = request.Email.Trim(), NormalizedEmail = normalizedEmail, DisplayName = string.IsNullOrWhiteSpace(request.DisplayName) ? request.Email.Split('@')[0] : request.DisplayName.Trim(), PasswordHash = PasswordSecurity.Hash(request.Password), Role = string.IsNullOrWhiteSpace(request.Role) ? "user" : request.Role.Trim().ToLowerInvariant(), }; await userRepository.AddAsync(user, ct); logger.LogInformation("Admin created user {Email} with role {Role}", user.Email, user.Role); return Results.Created($"/api/v1/admin/users/{user.Id}", new AdminUserInfo { Id = user.Id, Email = user.Email, DisplayName = user.DisplayName, Role = user.Role, CreatedAt = user.CreatedAt, }); } /// /// Delete a user account (admin only, cannot delete owner). /// [HttpDelete("users/{id:guid}")] public async Task DeleteUser(Guid id, CancellationToken ct) { var user = await userRepository.GetByIdAsync(id, ct); if (user is null) return Results.NotFound(new { error = "User not found." }); if (string.Equals(user.Role, "owner", StringComparison.OrdinalIgnoreCase)) return Results.Forbid(); await userRepository.DeleteAsync(user, ct); logger.LogInformation("Admin deleted user {Email}", user.Email); return Results.NoContent(); } /// /// Update a user's role (admin only, cannot change owner role). /// [HttpPatch("users/{id:guid}/role")] public async Task UpdateUserRole(Guid id, [FromBody] AdminUpdateRoleRequest request, CancellationToken ct) { if (string.IsNullOrWhiteSpace(request.Role)) return Results.ValidationProblem(new Dictionary { ["role"] = ["Role is required."] }); var validRoles = new[] { "owner", "admin", "user", "viewer" }; if (!validRoles.Contains(request.Role.ToLowerInvariant())) return Results.ValidationProblem(new Dictionary { ["role"] = ["Invalid role. Valid roles: owner, admin, user, viewer."] }); var user = await userRepository.GetByIdAsync(id, ct); if (user is null) return Results.NotFound(new { error = "User not found." }); if (string.Equals(user.Role, "owner", StringComparison.OrdinalIgnoreCase)) return Results.Forbid(); user.Role = request.Role.Trim().ToLowerInvariant(); user.UpdatedAt = DateTimeOffset.UtcNow; await userRepository.UpdateAsync(user, ct); logger.LogInformation("Admin updated role for {Email} to {Role}", user.Email, user.Role); return Results.Ok(new AdminUserInfo { Id = user.Id, Email = user.Email, DisplayName = user.DisplayName, Role = user.Role, CreatedAt = user.CreatedAt, LastLoginAt = user.LastLoginAt, }); } }