| 1 | using AgentForge.Contracts; |
| 2 | using AgentForge.Data; |
| 3 | using AgentForge.Data.Entities; |
| 4 | using AgentForge.Models; |
| 5 | using AgentForge.Plugin.Sdk; |
| 6 | using AgentForge.Services; |
| 7 | using Microsoft.AspNetCore.Builder; |
| 8 | using Microsoft.AspNetCore.Http; |
| 9 | using Microsoft.AspNetCore.Routing; |
| 10 | |
| 11 | namespace AgentForge.Plugin.Instance.UserManagement.Endpoints; |
| 12 | |
| 13 | internal static class ForgeInstanceAdminEndpoints |
| 14 | { |
| 15 | internal static RouteGroupBuilder MapInstanceAdminEndpoints(this RouteGroupBuilder api) |
| 16 | { |
| 17 | api.MapGet("/instance/admins", ListAdmins); |
| 18 | api.MapPost("/instance/admins", AddAdmin); |
| 19 | api.MapDelete("/instance/admins/{login}", RemoveAdmin); |
| 20 | return api; |
| 21 | } |
| 22 | |
| 23 | private static IResult ListAdmins( |
| 24 | HttpContext context, |
| 25 | ForgeRepository repository, |
| 26 | ForgeRepoAccessService access) |
| 27 | { |
| 28 | access.EnsureHostAdminRead(access.Resolve(context)); |
| 29 | |
| 30 | var admins = repository.ListInstanceAdmins() |
| 31 | .Select(pair => ToResponse(pair.Identity, pair.Admin)) |
| 32 | .ToList(); |
| 33 | return Results.Ok(new InstanceAdminListResponse(admins.Count, admins)); |
| 34 | } |
| 35 | |
| 36 | private static IResult AddAdmin( |
| 37 | AddInstanceAdminRequest request, |
| 38 | HttpContext context, |
| 39 | ForgeRepository repository, |
| 40 | ForgeRepoAccessService access) |
| 41 | { |
| 42 | access.EnsureHostAdmin(access.Resolve(context)); |
| 43 | if (string.IsNullOrWhiteSpace(request.Provider) || string.IsNullOrWhiteSpace(request.Login)) |
| 44 | throw new ForgeApiException(400, "provider and login required."); |
| 45 | |
| 46 | var identity = repository.FindIdentityByOAuthLogin(request.Provider.Trim(), request.Login.Trim()) |
| 47 | ?? throw new ForgeApiException(404, "Identity not found. User must sign in via OAuth first."); |
| 48 | |
| 49 | var admin = repository.InsertInstanceAdmin(identity.Id); |
| 50 | return Results.Created($"/api/v1/instance/admins/{identity.Login}", ToResponse(identity, admin)); |
| 51 | } |
| 52 | |
| 53 | private static IResult RemoveAdmin( |
| 54 | string login, |
| 55 | HttpContext context, |
| 56 | ForgeRepository repository, |
| 57 | ForgeRepoAccessService access) |
| 58 | { |
| 59 | access.EnsureHostAdmin(access.Resolve(context)); |
| 60 | |
| 61 | var identity = repository.FindIdentityByOAuthLogin("github", login.Trim()) |
| 62 | ?? throw new ForgeApiException(404, "Identity not found."); |
| 63 | |
| 64 | if (!repository.RemoveInstanceAdmin(identity.Id)) |
| 65 | throw new ForgeApiException(404, "Instance admin not found."); |
| 66 | |
| 67 | return Results.NoContent(); |
| 68 | } |
| 69 | |
| 70 | private static InstanceAdminResponse ToResponse(ForgeIdentityEntity identity, ForgeInstanceAdminEntity admin) => |
| 71 | new(identity.Login, identity.DisplayName, admin.CreatedAt); |
| 72 | } |
| 73 | |