feat(admin): port site administration to API and PostIt
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
ba384ba4c0
commit
04c42d9380
29 changed files with 2580 additions and 53 deletions
169
src/Yavsc.Api/Administration.http
Normal file
169
src/Yavsc.Api/Administration.http
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
@baseUrl = https://localhost:5104
|
||||
@token = REPLACE_WITH_ADMINISTRATOR_ACCESS_TOKEN
|
||||
@root = {{baseUrl}}/api/v1/administration
|
||||
@roleId = REPLACE_WITH_ROLE_ID
|
||||
@userId = REPLACE_WITH_USER_ID
|
||||
@clientId = 1
|
||||
@rowId = 1
|
||||
@scopeId = 1
|
||||
@templateId = REPLACE_WITH_MAILING_CRITERION
|
||||
|
||||
### Protected OpenAPI document (development only)
|
||||
GET {{baseUrl}}/openapi/administration.json
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Summary
|
||||
GET {{root}}/summary
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Roles
|
||||
GET {{root}}/roles
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Initialize standard roles
|
||||
POST {{root}}/roles/ensure
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Members
|
||||
GET {{root}}/roles/{{roleId}}/members
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Enroll
|
||||
PUT {{root}}/roles/{{roleId}}/members/{{userId}}
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Remove membership (409 for last administrator)
|
||||
DELETE {{root}}/roles/{{roleId}}/members/{{userId}}
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Clients
|
||||
GET {{root}}/clients
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Client detail (metadata only for secrets)
|
||||
GET {{root}}/clients/{{clientId}}
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Create client
|
||||
POST {{root}}/clients
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
|
||||
{"clientId":"example-postit","clientName":"Example PostIt","requireClientSecret":false,"requirePkce":true}
|
||||
|
||||
### Update client: send all scalar settings from GET, retaining unedited values
|
||||
PUT {{root}}/clients/{{clientId}}
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
|
||||
{"clientId":"example-postit","clientName":"Example PostIt","requireClientSecret":false,"requirePkce":true}
|
||||
|
||||
### Add a collection row
|
||||
# Collections: RedirectUris, PostLogoutRedirectUris, Scopes, GrantTypes,
|
||||
# CorsOrigins, IdentityProviders, Claims, Properties.
|
||||
# Claims and Properties also require a "key".
|
||||
POST {{root}}/clients/{{clientId}}/collections/RedirectUris
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
|
||||
{"value":"postit://callback"}
|
||||
|
||||
### Remove collection row
|
||||
DELETE {{root}}/clients/{{clientId}}/collections/RedirectUris/{{rowId}}
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Generate an additional secret (plaintext returned once; stored as SHA-256)
|
||||
POST {{root}}/clients/{{clientId}}/secrets
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
|
||||
{"description":"Example generated secret"}
|
||||
|
||||
### Generate a replacement, removing all previous secrets
|
||||
POST {{root}}/clients/{{clientId}}/secrets/regenerate
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
|
||||
{"description":"Example rotation"}
|
||||
|
||||
### Remove a secret
|
||||
DELETE {{root}}/clients/{{clientId}}/secrets/{{rowId}}
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Delete client
|
||||
DELETE {{root}}/clients/{{clientId}}
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Scopes
|
||||
GET {{root}}/scopes
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Scope detail
|
||||
GET {{root}}/scopes/{{scopeId}}
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Create scope
|
||||
POST {{root}}/scopes
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
|
||||
{"name":"example-api","displayName":"Example API","enabled":true}
|
||||
|
||||
### Update scope
|
||||
PUT {{root}}/scopes/{{scopeId}}
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
|
||||
{"name":"example-api","displayName":"Example API","description":"Updated description","enabled":true}
|
||||
|
||||
### Delete scope
|
||||
DELETE {{root}}/scopes/{{scopeId}}
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Mailing criteria
|
||||
GET {{root}}/mailing-criteria
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Mailing templates
|
||||
GET {{root}}/mailing-templates
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Template detail
|
||||
GET {{root}}/mailing-templates/{{templateId}}
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Create template (use an ID returned by mailing-criteria)
|
||||
POST {{root}}/mailing-templates
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
|
||||
{"id":"{{templateId}}","topic":"Example topic","body":"Example body","replyToAddress":"reply@example.invalid","toSend":"OnDemand"}
|
||||
|
||||
### Update template
|
||||
PUT {{root}}/mailing-templates/{{templateId}}
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
|
||||
{"id":"{{templateId}}","topic":"Updated topic","body":"Updated body","replyToAddress":"reply@example.invalid","toSend":"Monthly"}
|
||||
|
||||
### Delete template
|
||||
DELETE {{root}}/mailing-templates/{{templateId}}
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Export business data, never account authentication material
|
||||
GET {{root}}/transfer
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Atomic import/upsert (16 MiB maximum; an empty transfer changes nothing)
|
||||
POST {{root}}/transfer
|
||||
Authorization: Bearer {{token}}
|
||||
Content-Type: application/json
|
||||
|
||||
{"version":1,"users":[],"blogs":[],"activities":[]}
|
||||
|
||||
### Missing resource
|
||||
GET {{root}}/clients/2147483647
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Anonymous access must be rejected (401)
|
||||
GET {{root}}/summary
|
||||
|
|
@ -78,7 +78,7 @@ public sealed class ResourceUsageApiController : Controller
|
|||
[HttpGet(Constants.ResourceUsageAdminRoute)]
|
||||
public async Task<ActionResult<List<ResourceUsageSummary>>> GetAdminOverview()
|
||||
{
|
||||
if (!User.IsInRole(Constants.AdminGroupName) && !User.IsInRole(Constants.BlogModeratorGroupName))
|
||||
if (!User.IsInRole(Constants.AdminGroupName))
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,215 @@
|
|||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Yavsc.Abstract.Administration;
|
||||
using Yavsc.Api.Services;
|
||||
|
||||
namespace Yavsc.ApiControllers.Administration;
|
||||
|
||||
[ApiController]
|
||||
[ApiExplorerSettings(GroupName = "administration")]
|
||||
[Authorize("AdministratorOnly")]
|
||||
[Route(Constants.APIPrefix + "/administration")]
|
||||
[Produces("application/json")]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
[ProducesResponseType<ProblemDetails>(400)]
|
||||
[ProducesResponseType<ProblemDetails>(404)]
|
||||
[ProducesResponseType<ProblemDetails>(409)]
|
||||
[ProducesResponseType(401)]
|
||||
[ProducesResponseType(403)]
|
||||
[ServiceFilter(typeof(AdministrationExceptionFilter))]
|
||||
public sealed class SiteAdministrationApiController(IAdministrationService service) : ControllerBase
|
||||
{
|
||||
[HttpGet("summary"), EndpointSummary("Statistiques du site et informations du logiciel")]
|
||||
[ProducesResponseType<AdministrationSummary>(200)]
|
||||
public async Task<ActionResult<AdministrationSummary>> Summary(CancellationToken ct)
|
||||
=> Ok(await service.GetSummaryAsync(ct));
|
||||
|
||||
[HttpGet("roles"), EndpointSummary("Lister les rôles et leurs effectifs")]
|
||||
public async Task<ActionResult<IReadOnlyList<AdministrationRole>>> Roles(CancellationToken ct)
|
||||
=> Ok(await service.GetRolesAsync(ct));
|
||||
|
||||
[HttpPost("roles/ensure"), EndpointSummary("Initialiser les rôles standards"), ProducesResponseType(204)]
|
||||
public async Task<IActionResult> EnsureRoles(CancellationToken ct)
|
||||
{
|
||||
await service.EnsureRolesAsync(ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpGet("roles/{id}/members"), EndpointSummary("Lister les membres d’un rôle")]
|
||||
public async Task<ActionResult<IReadOnlyList<RoleMember>>> RoleMembers(string id, CancellationToken ct)
|
||||
=> Ok(await service.GetRoleMembersAsync(id, ct));
|
||||
|
||||
[HttpPut("roles/{id}/members/{userId}"), EndpointSummary("Inscrire un utilisateur dans un rôle"), ProducesResponseType(204)]
|
||||
public async Task<IActionResult> Enroll(string id, string userId, CancellationToken ct)
|
||||
{
|
||||
await service.SetRoleMembershipAsync(id, userId, true, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpDelete("roles/{id}/members/{userId}"), EndpointSummary("Retirer un membre, sauf le dernier administrateur"), ProducesResponseType(204)]
|
||||
public async Task<IActionResult> Fire(string id, string userId, CancellationToken ct)
|
||||
{
|
||||
await service.SetRoleMembershipAsync(id, userId, false, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpGet("clients"), EndpointSummary("Lister les clients OAuth/OIDC sans exposer leurs secrets")]
|
||||
public async Task<ActionResult<IReadOnlyList<AdministrationClient>>> Clients(CancellationToken ct)
|
||||
=> Ok(await service.GetClientsAsync(ct));
|
||||
|
||||
[HttpGet("clients/{id:int}"), EndpointSummary("Consulter la configuration d’un client")]
|
||||
[ProducesResponseType<AdministrationClient>(200)]
|
||||
[ProducesResponseType(404)]
|
||||
public async Task<ActionResult<AdministrationClient>> Client(int id, CancellationToken ct)
|
||||
{
|
||||
var client = await service.GetClientAsync(id, ct);
|
||||
return client is null ? NotFound() : Ok(client);
|
||||
}
|
||||
|
||||
[HttpPost("clients"), EndpointSummary("Créer un client avec les valeurs par défaut PKCE")]
|
||||
[ProducesResponseType<AdministrationClient>(201)]
|
||||
public async Task<ActionResult<AdministrationClient>> CreateClient(ClientSettings settings, CancellationToken ct)
|
||||
{
|
||||
var client = await service.SaveClientAsync(null, settings, ct);
|
||||
return CreatedAtAction(nameof(Client), new { id = client.Id }, client);
|
||||
}
|
||||
|
||||
[HttpPut("clients/{id:int}"), EndpointSummary("Remplacer les paramètres scalaires d’un client")]
|
||||
public async Task<ActionResult<AdministrationClient>> UpdateClient(int id, ClientSettings settings, CancellationToken ct)
|
||||
=> Ok(await service.SaveClientAsync(id, settings, ct));
|
||||
|
||||
[HttpDelete("clients/{id:int}"), EndpointSummary("Supprimer un client et ses collections"), ProducesResponseType(204)]
|
||||
public async Task<IActionResult> DeleteClient(int id, CancellationToken ct)
|
||||
{
|
||||
await service.DeleteClientAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpPost("clients/{id:int}/collections/{collection}"), EndpointSummary("Ajouter une entrée à une collection du client"), ProducesResponseType(204)]
|
||||
public async Task<IActionResult> AddEntry(int id, ClientCollection collection, ClientEntry entry, CancellationToken ct)
|
||||
{
|
||||
await service.AddClientEntryAsync(id, collection, entry, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpDelete("clients/{id:int}/collections/{collection}/{rowId:int}"), EndpointSummary("Supprimer une entrée du client"), ProducesResponseType(204)]
|
||||
public async Task<IActionResult> DeleteEntry(int id, ClientCollection collection, int rowId, CancellationToken ct)
|
||||
{
|
||||
await service.DeleteClientEntryAsync(id, collection, rowId, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpPost("clients/{id:int}/secrets"), EndpointSummary("Ajouter un secret et le restituer une seule fois")]
|
||||
[ProducesResponseType<NewClientSecret>(201)]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public async Task<ActionResult<NewClientSecret>> AddSecret(int id, ClientSecretRequest request, CancellationToken ct)
|
||||
{
|
||||
var secret = await service.CreateSecretAsync(id, request, false, ct);
|
||||
return CreatedAtAction(nameof(Client), new { id }, secret);
|
||||
}
|
||||
|
||||
[HttpPost("clients/{id:int}/secrets/regenerate"), EndpointSummary("Générer un secret remplaçant tous les précédents")]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public async Task<ActionResult<NewClientSecret>> RegenerateSecret(int id, ClientSecretRequest request, CancellationToken ct)
|
||||
=> Ok(await service.CreateSecretAsync(id, request, true, ct));
|
||||
|
||||
[HttpDelete("clients/{id:int}/secrets/{secretId:int}"), EndpointSummary("Supprimer un secret du client"), ProducesResponseType(204)]
|
||||
public async Task<IActionResult> DeleteSecret(int id, int secretId, CancellationToken ct)
|
||||
{
|
||||
await service.DeleteSecretAsync(id, secretId, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpGet("scopes"), EndpointSummary("Lister les scopes API")]
|
||||
public async Task<ActionResult<IReadOnlyList<AdministrationScope>>> Scopes(CancellationToken ct)
|
||||
=> Ok(await service.GetScopesAsync(ct));
|
||||
|
||||
[HttpGet("scopes/{id:int}"), EndpointSummary("Consulter un scope API")]
|
||||
public async Task<ActionResult<AdministrationScope>> Scope(int id, CancellationToken ct)
|
||||
{
|
||||
var scope = (await service.GetScopesAsync(ct)).SingleOrDefault(scope => scope.Id == id);
|
||||
return scope is null ? NotFound() : Ok(scope);
|
||||
}
|
||||
|
||||
[HttpPost("scopes"), EndpointSummary("Créer un scope API")]
|
||||
[ProducesResponseType<AdministrationScope>(201)]
|
||||
public async Task<ActionResult<AdministrationScope>> CreateScope(ApiScopeSettings settings, CancellationToken ct)
|
||||
{
|
||||
var scope = await service.SaveScopeAsync(null, settings, ct);
|
||||
return CreatedAtAction(nameof(Scope), new { id = scope.Id }, scope);
|
||||
}
|
||||
|
||||
[HttpPut("scopes/{id:int}"), EndpointSummary("Modifier un scope API")]
|
||||
public async Task<ActionResult<AdministrationScope>> UpdateScope(int id, ApiScopeSettings settings, CancellationToken ct)
|
||||
=> Ok(await service.SaveScopeAsync(id, settings, ct));
|
||||
|
||||
[HttpDelete("scopes/{id:int}"), EndpointSummary("Supprimer un scope API"), ProducesResponseType(204)]
|
||||
public async Task<IActionResult> DeleteScope(int id, CancellationToken ct)
|
||||
{
|
||||
await service.DeleteScopeAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpGet("mailing-criteria"), EndpointSummary("Lister les critères de diffusion utilisables dans les modèles")]
|
||||
public ActionResult<IReadOnlyList<string>> MailingCriteria(CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return Ok(service.GetMailingCriteria());
|
||||
}
|
||||
|
||||
[HttpGet("mailing-templates"), EndpointSummary("Lister les modèles de courriels")]
|
||||
public async Task<ActionResult<IReadOnlyList<MailingTemplateSettings>>> MailingTemplates(CancellationToken ct)
|
||||
=> Ok(await service.GetMailingTemplatesAsync(ct));
|
||||
|
||||
[HttpGet("mailing-templates/{id}"), EndpointSummary("Consulter un modèle de courriel")]
|
||||
public async Task<ActionResult<MailingTemplateSettings>> MailingTemplate(string id, CancellationToken ct)
|
||||
{
|
||||
var template = (await service.GetMailingTemplatesAsync(ct)).SingleOrDefault(template => template.Id == id);
|
||||
return template is null ? NotFound() : Ok(template);
|
||||
}
|
||||
|
||||
[HttpPost("mailing-templates"), EndpointSummary("Créer un modèle de courriel")]
|
||||
[ProducesResponseType<MailingTemplateSettings>(201)]
|
||||
public async Task<ActionResult<MailingTemplateSettings>> CreateMailingTemplate(MailingTemplateSettings settings, CancellationToken ct)
|
||||
{
|
||||
var template = await service.SaveMailingTemplateAsync(null, settings, ct);
|
||||
return CreatedAtAction(nameof(MailingTemplate), new { id = template.Id }, template);
|
||||
}
|
||||
|
||||
[HttpPut("mailing-templates/{id}"), EndpointSummary("Modifier un modèle de courriel")]
|
||||
public async Task<ActionResult<MailingTemplateSettings>> UpdateMailingTemplate(string id, MailingTemplateSettings settings, CancellationToken ct)
|
||||
=> Ok(await service.SaveMailingTemplateAsync(id, settings, ct));
|
||||
|
||||
[HttpDelete("mailing-templates/{id}"), EndpointSummary("Supprimer un modèle de courriel"), ProducesResponseType(204)]
|
||||
public async Task<IActionResult> DeleteMailingTemplate(string id, CancellationToken ct)
|
||||
{
|
||||
await service.DeleteMailingTemplateAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpGet("transfer"), EndpointSummary("Exporter les données métier sans matériel d’authentification")]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public async Task<ActionResult<AdministrationTransfer>> Export(CancellationToken ct)
|
||||
=> Ok(await service.ExportAsync(ct));
|
||||
|
||||
[HttpPost("transfer"), EndpointSummary("Importer les données métier en une transaction, limite 16 Mio")]
|
||||
[RequestSizeLimit(16 * 1024 * 1024)]
|
||||
public async Task<ActionResult<ImportResult>> Import(AdministrationTransfer transfer, CancellationToken ct)
|
||||
=> Ok(await service.ImportAsync(transfer, ct));
|
||||
}
|
||||
|
||||
public sealed class AdministrationExceptionFilter(ILogger<AdministrationExceptionFilter> logger) : IExceptionFilter
|
||||
{
|
||||
public void OnException(ExceptionContext context)
|
||||
{
|
||||
if (context.Exception is not AdministrationOperationException exception)
|
||||
return;
|
||||
logger.LogWarning("Administration request rejected with status {Status}: {Reason}", exception.StatusCode, exception.Message);
|
||||
context.Result = new ObjectResult(new ProblemDetails
|
||||
{
|
||||
Status = exception.StatusCode, Title = exception.Message
|
||||
}) { StatusCode = exception.StatusCode };
|
||||
context.ExceptionHandled = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -7,7 +7,7 @@ using Yavsc.Server.Helpers;
|
|||
|
||||
namespace Yavsc.Controllers
|
||||
{
|
||||
[Produces("application/json"), Authorize]
|
||||
[Produces("application/json"), Authorize("AdministratorOnly")]
|
||||
[Route(Constants.APIPrefix + "/users")]
|
||||
public class ApplicationUserApiController : Controller
|
||||
{
|
||||
|
|
@ -19,7 +19,7 @@ namespace Yavsc.Controllers
|
|||
}
|
||||
|
||||
// GET: api/ApplicationUserApi
|
||||
[HttpGet, Authorize(Roles = Constants.AdminGroupName + "," + Constants.BlogModeratorGroupName)]
|
||||
[HttpGet]
|
||||
public IEnumerable<UserInfo> GetApplicationUser(int skip=0, int take = 25)
|
||||
{
|
||||
return _context.Users
|
||||
|
|
@ -41,7 +41,7 @@ namespace Yavsc.Controllers
|
|||
});
|
||||
}
|
||||
|
||||
[HttpGet("search/{pattern}"), Authorize(Roles = Constants.AdminGroupName + "," + Constants.BlogModeratorGroupName)]
|
||||
[HttpGet("search/{pattern}")]
|
||||
public IEnumerable<UserInfo> SearchApplicationUser(string pattern, int skip=0, int take = 25)
|
||||
{
|
||||
var normalizedPattern = pattern ?? string.Empty;
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ using Yavsc;
|
|||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.Services;
|
||||
using Yavsc.Server.Hubs;
|
||||
using Yavsc.Api.Services;
|
||||
|
||||
internal class Program
|
||||
{
|
||||
|
|
@ -25,6 +26,7 @@ internal class Program
|
|||
builder.AddConfiguration("api");
|
||||
|
||||
var services = builder.Services;
|
||||
services.AddSiteAdministration();
|
||||
|
||||
// Anthropic client
|
||||
builder.Services.AddSingleton<AnthropicClient>(_ =>
|
||||
|
|
@ -132,7 +134,10 @@ internal class Program
|
|||
using (var app = builder.Build())
|
||||
{
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseDeveloperExceptionPage();
|
||||
app.MapOpenApi().RequireAuthorization("AdministratorOnly");
|
||||
}
|
||||
|
||||
app
|
||||
.UseRouting()
|
||||
|
|
|
|||
196
src/Yavsc.Api/Services/AdministrationService.Transfers.cs
Normal file
196
src/Yavsc.Api/Services/AdministrationService.Transfers.cs
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Yavsc.Abstract.Administration;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Access;
|
||||
using Yavsc.Models.Blog;
|
||||
using Yavsc.Models.Relationship;
|
||||
using Yavsc.Models.Workflow;
|
||||
|
||||
namespace Yavsc.Api.Services;
|
||||
|
||||
public sealed partial class AdministrationService
|
||||
{
|
||||
public async Task<AdministrationTransfer> ExportAsync(CancellationToken ct)
|
||||
{
|
||||
var userData = await db.Users.AsNoTracking().OrderBy(user => user.Id)
|
||||
.Select(user => new UserBusinessData
|
||||
{
|
||||
Id = user.Id, UserName = user.UserName!, Email = user.Email!, FullName = user.FullName,
|
||||
Avatar = user.Avatar, DedicatedGoogleCalendar = user.DedicatedGoogleCalendar,
|
||||
AllowMonthlyEmail = user.AllowMonthlyEmail, DiskQuota = user.DiskQuota, MaxFileSize = user.MaxFileSize
|
||||
}).ToArrayAsync(ct);
|
||||
var blogs = await db.BlogSpot.AsNoTracking().Include(post => post.ACL).Include(post => post.Publication)
|
||||
.Include(post => post.Tags).ThenInclude(tag => tag.Tag).OrderBy(post => post.Id).AsSplitQuery().ToListAsync(ct);
|
||||
var activities = await db.Activities.AsNoTracking().OrderBy(activity => activity.Code)
|
||||
.Select(activity => new ActivityBusinessData
|
||||
{
|
||||
Code = activity.Code, Name = activity.Name, ParentCode = activity.ParentCode,
|
||||
Description = activity.Description, Photo = activity.Photo, Moderated = activity.Moderated,
|
||||
ModeratorGroupName = activity.ModeratorGroupName, Rate = activity.Rate,
|
||||
SettingsClassName = activity.SettingsClassName, Hidden = activity.Hidden
|
||||
}).ToArrayAsync(ct);
|
||||
return new AdministrationTransfer
|
||||
{
|
||||
Users = userData, Activities = activities,
|
||||
Blogs = blogs.Select(post => new BlogBusinessData
|
||||
{
|
||||
Id = post.Id, AuthorId = post.AuthorId!, Title = post.Title, Article = post.Article, Photo = post.Photo,
|
||||
DateCreated = Utc(post.DateCreated), Published = post.Publication is not null,
|
||||
CircleIds = post.ACL?.Select(acl => acl.CircleId).ToArray() ?? [],
|
||||
Tags = post.Tags.Select(tag => tag.Tag.Name).ToArray()
|
||||
}).ToArray()
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<ImportResult> ImportAsync(AdministrationTransfer transfer, CancellationToken ct)
|
||||
{
|
||||
Validate(transfer);
|
||||
foreach (var item in transfer.Users) Validate(item);
|
||||
foreach (var item in transfer.Blogs)
|
||||
{
|
||||
Validate(item);
|
||||
if (item.CircleIds is null || item.Tags is null || item.Tags.Any(string.IsNullOrWhiteSpace))
|
||||
throw Invalid("Les cercles et étiquettes d’un billet doivent être valides.");
|
||||
}
|
||||
foreach (var item in transfer.Activities) Validate(item);
|
||||
Unique(transfer.Users.Select(user => user.Id));
|
||||
Unique(transfer.Users.Select(user => user.UserName.ToUpperInvariant()));
|
||||
Unique(transfer.Blogs.Select(post => post.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||
Unique(transfer.Activities.Select(activity => activity.Code));
|
||||
|
||||
await using var transaction = await db.Database.BeginTransactionAsync(ct);
|
||||
if (transfer.Blogs.Length > 0 && db.Database.IsNpgsql())
|
||||
await db.Database.ExecuteSqlRawAsync("""LOCK TABLE "BlogSpot" IN SHARE ROW EXCLUSIVE MODE""", ct);
|
||||
foreach (var item in transfer.Users)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var user = await users.FindByIdAsync(item.Id);
|
||||
var isNew = user is null;
|
||||
if (user is not null && user.Email != item.Email)
|
||||
throw Conflict("L’adresse e-mail d’un compte existant est une clé métier ; elle ne peut pas changer par import.");
|
||||
user ??= new ApplicationUser { Id = item.Id };
|
||||
if (user.Email != item.Email)
|
||||
user.EmailConfirmed = false;
|
||||
user.UserName = item.UserName;
|
||||
user.Email = item.Email;
|
||||
user.FullName = item.FullName;
|
||||
user.Avatar = item.Avatar;
|
||||
user.DedicatedGoogleCalendar = item.DedicatedGoogleCalendar;
|
||||
user.AllowMonthlyEmail = item.AllowMonthlyEmail;
|
||||
user.DiskQuota = item.DiskQuota;
|
||||
user.MaxFileSize = item.MaxFileSize;
|
||||
CheckIdentity(isNew ? await users.CreateAsync(user) : await users.UpdateAsync(user));
|
||||
}
|
||||
|
||||
var activities = await db.Activities.ToDictionaryAsync(activity => activity.Code, ct);
|
||||
foreach (var item in transfer.Activities)
|
||||
{
|
||||
if (!activities.TryGetValue(item.Code, out var activity))
|
||||
{
|
||||
activity = new Activity { Code = item.Code };
|
||||
activities.Add(item.Code, activity);
|
||||
db.Activities.Add(activity);
|
||||
}
|
||||
activity.Name = item.Name;
|
||||
activity.ParentCode = item.ParentCode;
|
||||
activity.Description = item.Description;
|
||||
activity.Photo = item.Photo;
|
||||
activity.Moderated = item.Moderated;
|
||||
activity.ModeratorGroupName = item.ModeratorGroupName;
|
||||
activity.Rate = item.Rate;
|
||||
activity.SettingsClassName = item.SettingsClassName;
|
||||
activity.Hidden = item.Hidden;
|
||||
}
|
||||
foreach (var item in transfer.Activities)
|
||||
{
|
||||
var visited = new HashSet<string> { item.Code };
|
||||
var parent = item.ParentCode;
|
||||
while (parent is not null)
|
||||
{
|
||||
if (!visited.Add(parent)) throw Invalid("Le graphe des activités contient un cycle.");
|
||||
if (!activities.TryGetValue(parent, out var ancestor)) throw Invalid($"Activité parent inconnue : {parent}.");
|
||||
parent = ancestor.ParentCode;
|
||||
}
|
||||
}
|
||||
await db.SaveChangesAsync(Actor, ct);
|
||||
|
||||
var existingTags = await db.Tags.OrderBy(tag => tag.Id).ToListAsync(ct);
|
||||
var tags = existingTags.GroupBy(tag => tag.Name).ToDictionary(group => group.Key, group => group.First());
|
||||
foreach (var item in transfer.Blogs)
|
||||
{
|
||||
if (!await db.Users.AnyAsync(user => user.Id == item.AuthorId, ct))
|
||||
throw Invalid($"Auteur inconnu : {item.AuthorId}.");
|
||||
foreach (var circleId in item.CircleIds.Distinct())
|
||||
{
|
||||
if (!await db.Circle.AnyAsync(circle => circle.Id == circleId, ct))
|
||||
throw Invalid($"Cercle inconnu : {circleId}. Les droits du billet ne peuvent pas être élargis.");
|
||||
}
|
||||
var post = await db.BlogSpot.Include(post => post.ACL).Include(post => post.Tags)
|
||||
.Include(post => post.Publication).SingleOrDefaultAsync(post => post.Id == item.Id, ct);
|
||||
if (post is null)
|
||||
{
|
||||
post = new BlogPost { Id = item.Id, ACL = [], Tags = [] };
|
||||
db.BlogSpot.Add(post);
|
||||
}
|
||||
else if (post.AuthorId != item.AuthorId)
|
||||
throw Conflict("Un import ne peut pas changer l’auteur d’un billet existant.");
|
||||
post.AuthorId = item.AuthorId;
|
||||
post.Title = item.Title;
|
||||
post.Article = item.Article;
|
||||
post.Photo = item.Photo;
|
||||
post.DateCreated = item.DateCreated.UtcDateTime;
|
||||
post.DateModified = DateTime.UtcNow;
|
||||
post.UserModified = Actor;
|
||||
post.UserCreated ??= item.AuthorId;
|
||||
post.ACL ??= [];
|
||||
post.Tags ??= [];
|
||||
db.RemoveRange(post.ACL);
|
||||
post.ACL = item.CircleIds.Distinct().Select(id => new CircleAuthorizationToBlogPost { CircleId = id }).ToList();
|
||||
db.RemoveRange(post.Tags);
|
||||
post.Tags = item.Tags.Distinct().Select(name =>
|
||||
{
|
||||
if (!tags.TryGetValue(name, out var tag))
|
||||
{
|
||||
tag = new Tag { Name = name };
|
||||
tags.Add(name, tag);
|
||||
}
|
||||
return new BlogTag { Tag = tag };
|
||||
}).ToList();
|
||||
if (item.Published && post.Publication is null)
|
||||
post.Publication = new BlogSpotPublication();
|
||||
else if (!item.Published && post.Publication is not null)
|
||||
{
|
||||
db.Remove(post.Publication);
|
||||
post.Publication = null!;
|
||||
}
|
||||
}
|
||||
await db.SaveChangesAsync(ct);
|
||||
if (transfer.Blogs.Length > 0 && db.Database.IsNpgsql())
|
||||
{
|
||||
// Explicit imported IDs must not collide with subsequently generated IDs.
|
||||
await db.Database.ExecuteSqlRawAsync("""
|
||||
SELECT setval(pg_get_serial_sequence('"BlogSpot"', 'Id'),
|
||||
GREATEST(COALESCE((SELECT MAX("Id") FROM "BlogSpot"), 1),
|
||||
COALESCE(pg_sequence_last_value(pg_get_serial_sequence('"BlogSpot"', 'Id')::regclass), 1)), true)
|
||||
""", ct);
|
||||
}
|
||||
await transaction.CommitAsync(ct);
|
||||
return new(transfer.Users.Length, transfer.Blogs.Length, transfer.Activities.Length);
|
||||
}
|
||||
|
||||
private static void Validate(object? value)
|
||||
{
|
||||
if (value is null) throw Invalid("Une ligne de transfert ne peut pas être nulle.");
|
||||
var errors = new List<ValidationResult>();
|
||||
if (!Validator.TryValidateObject(value, new ValidationContext(value), errors, true))
|
||||
throw Invalid(string.Join("; ", errors.Select(error => error.ErrorMessage)));
|
||||
}
|
||||
|
||||
private static void Unique(IEnumerable<string> keys)
|
||||
{
|
||||
var values = keys.ToArray();
|
||||
if (values.Distinct(StringComparer.Ordinal).Count() != values.Length)
|
||||
throw Invalid("Le transfert contient des identifiants en double.");
|
||||
}
|
||||
}
|
||||
336
src/Yavsc.Api/Services/AdministrationService.cs
Normal file
336
src/Yavsc.Api/Services/AdministrationService.cs
Normal file
|
|
@ -0,0 +1,336 @@
|
|||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using IdentityServer8.EntityFramework.Entities;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Yavsc.Abstract.Administration;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.Server.Models.Calendar;
|
||||
using Yavsc.Server.Models.EMailing;
|
||||
using Yavsc.Server.Settings;
|
||||
|
||||
namespace Yavsc.Api.Services;
|
||||
|
||||
public sealed partial class AdministrationService(
|
||||
ApplicationDbContext db, UserManager<ApplicationUser> users, RoleManager<IdentityRole> roles,
|
||||
IHttpContextAccessor httpContext) : IAdministrationService
|
||||
{
|
||||
private string Actor => httpContext.HttpContext?.User.GetUserId()
|
||||
?? throw new AdministrationOperationException(401, "Session administrateur indisponible.");
|
||||
|
||||
private static AdministrationOperationException Missing() => new(404, "Ressource introuvable.");
|
||||
private static AdministrationOperationException Invalid(string message) => new(400, message);
|
||||
private static AdministrationOperationException Conflict(string message) => new(409, message);
|
||||
|
||||
private static void CheckIdentity(IdentityResult result)
|
||||
{
|
||||
if (!result.Succeeded)
|
||||
throw Invalid(string.Join("; ", result.Errors.Select(error => error.Description)));
|
||||
}
|
||||
|
||||
public async Task<AdministrationSummary> GetSummaryAsync(CancellationToken ct)
|
||||
=> new(await db.Users.CountAsync(ct),
|
||||
(await users.GetUsersInRoleAsync(Constants.AdminGroupName)).Count,
|
||||
typeof(AdministrationService).Assembly.GetName().ToString(), System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
|
||||
|
||||
public async Task<IReadOnlyList<AdministrationRole>> GetRolesAsync(CancellationToken ct)
|
||||
{
|
||||
var all = await roles.Roles.OrderBy(role => role.Name).ToListAsync(ct);
|
||||
var result = new List<AdministrationRole>();
|
||||
foreach (var role in all)
|
||||
result.Add(new(role.Id, role.Name!, await db.UserRoles.CountAsync(row => row.RoleId == role.Id, ct)));
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task EnsureRolesAsync(CancellationToken ct)
|
||||
{
|
||||
foreach (var name in new[] { Constants.AdminGroupName, Constants.StarGroupName, Constants.PerformerGroupName,
|
||||
Constants.FrontOfficeGroupName, Constants.StarHunterGroupName, Constants.BlogModeratorGroupName })
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (!await roles.RoleExistsAsync(name))
|
||||
CheckIdentity(await roles.CreateAsync(new IdentityRole(name)));
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<RoleMember>> GetRoleMembersAsync(string roleId, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var role = await roles.FindByIdAsync(roleId) ?? throw Missing();
|
||||
return (await users.GetUsersInRoleAsync(role.Name!))
|
||||
.Select(user => new RoleMember(user.Id, user.UserName!, user.Email)).ToArray();
|
||||
}
|
||||
|
||||
public async Task SetRoleMembershipAsync(string roleId, string userId, bool member, CancellationToken ct)
|
||||
{
|
||||
await using var transaction = await db.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable, ct);
|
||||
var role = await roles.FindByIdAsync(roleId) ?? throw Missing();
|
||||
var user = await users.FindByIdAsync(userId) ?? throw Missing();
|
||||
var alreadyMember = await users.IsInRoleAsync(user, role.Name!);
|
||||
if (member && !alreadyMember)
|
||||
CheckIdentity(await users.AddToRoleAsync(user, role.Name!));
|
||||
else if (!member && alreadyMember)
|
||||
{
|
||||
if (role.Name == Constants.AdminGroupName &&
|
||||
(await users.GetUsersInRoleAsync(role.Name)).Count <= 1)
|
||||
throw Conflict("Impossible de retirer le dernier administrateur.");
|
||||
CheckIdentity(await users.RemoveFromRoleAsync(user, role.Name!));
|
||||
}
|
||||
await transaction.CommitAsync(ct);
|
||||
}
|
||||
|
||||
private IQueryable<Client> ClientQuery => db.Clients
|
||||
.Include(client => client.RedirectUris).Include(client => client.PostLogoutRedirectUris)
|
||||
.Include(client => client.AllowedScopes).Include(client => client.AllowedGrantTypes)
|
||||
.Include(client => client.AllowedCorsOrigins).Include(client => client.IdentityProviderRestrictions)
|
||||
.Include(client => client.Claims).Include(client => client.Properties).Include(client => client.ClientSecrets)
|
||||
.AsSplitQuery();
|
||||
|
||||
public async Task<IReadOnlyList<AdministrationClient>> GetClientsAsync(CancellationToken ct)
|
||||
=> (await ClientQuery.AsNoTracking().OrderBy(client => client.ClientId).ToListAsync(ct)).Select(ToClient).ToArray();
|
||||
|
||||
public async Task<AdministrationClient?> GetClientAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var client = await ClientQuery.AsNoTracking().SingleOrDefaultAsync(client => client.Id == id, ct);
|
||||
return client is null ? null : ToClient(client);
|
||||
}
|
||||
|
||||
public async Task<AdministrationClient> SaveClientAsync(int? id, ClientSettings settings, CancellationToken ct)
|
||||
{
|
||||
if (await db.Clients.AnyAsync(client => client.ClientId == settings.ClientId && client.Id != id, ct))
|
||||
throw Conflict("Cet identifiant client existe déjà.");
|
||||
var client = id.HasValue
|
||||
? await ClientQuery.SingleOrDefaultAsync(client => client.Id == id, ct) ?? throw Missing()
|
||||
: new Client { Created = DateTime.UtcNow };
|
||||
ApplySettings(client, settings);
|
||||
client.Updated = DateTime.UtcNow;
|
||||
if (!id.HasValue)
|
||||
{
|
||||
client.AllowedGrantTypes = [new ClientGrantType { GrantType = "authorization_code" }];
|
||||
client.AllowedScopes = [new ClientScope { Scope = "openid" }, new ClientScope { Scope = "profile" }];
|
||||
db.Clients.Add(client);
|
||||
}
|
||||
await db.SaveChangesAsync(Actor, ct);
|
||||
return await GetClientAsync(client.Id, ct) ?? throw Missing();
|
||||
}
|
||||
|
||||
public async Task DeleteClientAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var client = await ClientQuery.SingleOrDefaultAsync(client => client.Id == id, ct) ?? throw Missing();
|
||||
db.Clients.Remove(client);
|
||||
await db.SaveChangesAsync(Actor, ct);
|
||||
}
|
||||
|
||||
public async Task AddClientEntryAsync(int id, ClientCollection collection, ClientEntry entry, CancellationToken ct)
|
||||
{
|
||||
var client = await ClientQuery.SingleOrDefaultAsync(client => client.Id == id, ct) ?? throw Missing();
|
||||
if (ToClient(client).Entries.Any(row => row.Collection == collection && row.Key == entry.Key &&
|
||||
(row.Value == entry.Value || collection == ClientCollection.Properties)))
|
||||
throw Conflict("Cette entrée existe déjà.");
|
||||
if (collection is ClientCollection.Claims or ClientCollection.Properties && string.IsNullOrWhiteSpace(entry.Key))
|
||||
throw Invalid("Une clé est requise.");
|
||||
if (collection is ClientCollection.RedirectUris or ClientCollection.PostLogoutRedirectUris or ClientCollection.CorsOrigins)
|
||||
{
|
||||
if (!Uri.TryCreate(entry.Value, UriKind.Absolute, out var uri) ||
|
||||
uri.Scheme is "javascript" or "data" || !string.IsNullOrEmpty(uri.Fragment))
|
||||
throw Invalid("Une URI absolue sans fragment est requise.");
|
||||
if (collection == ClientCollection.CorsOrigins &&
|
||||
(uri.Scheme is not ("http" or "https") || uri.AbsolutePath != "/" || uri.Query.Length != 0))
|
||||
throw Invalid("Une origine HTTP(S) sans chemin est requise.");
|
||||
}
|
||||
object row = collection switch
|
||||
{
|
||||
ClientCollection.RedirectUris => new ClientRedirectUri { ClientId = id, RedirectUri = entry.Value },
|
||||
ClientCollection.PostLogoutRedirectUris => new ClientPostLogoutRedirectUri { ClientId = id, PostLogoutRedirectUri = entry.Value },
|
||||
ClientCollection.Scopes => new ClientScope { ClientId = id, Scope = entry.Value },
|
||||
ClientCollection.GrantTypes => new ClientGrantType { ClientId = id, GrantType = entry.Value },
|
||||
ClientCollection.CorsOrigins => new ClientCorsOrigin { ClientId = id, Origin = entry.Value },
|
||||
ClientCollection.IdentityProviders => new ClientIdPRestriction { ClientId = id, Provider = entry.Value },
|
||||
ClientCollection.Claims => new ClientClaim { ClientId = id, Type = entry.Key!, Value = entry.Value },
|
||||
ClientCollection.Properties => new ClientProperty { ClientId = id, Key = entry.Key!, Value = entry.Value },
|
||||
_ => throw Invalid("Collection inconnue.")
|
||||
};
|
||||
db.Add(row);
|
||||
await db.SaveChangesAsync(Actor, ct);
|
||||
}
|
||||
|
||||
public async Task DeleteClientEntryAsync(int id, ClientCollection collection, int rowId, CancellationToken ct)
|
||||
{
|
||||
var client = await ClientQuery.SingleOrDefaultAsync(client => client.Id == id, ct) ?? throw Missing();
|
||||
object? row = collection switch
|
||||
{
|
||||
ClientCollection.RedirectUris => client.RedirectUris.SingleOrDefault(row => row.Id == rowId),
|
||||
ClientCollection.PostLogoutRedirectUris => client.PostLogoutRedirectUris.SingleOrDefault(row => row.Id == rowId),
|
||||
ClientCollection.Scopes => client.AllowedScopes.SingleOrDefault(row => row.Id == rowId),
|
||||
ClientCollection.GrantTypes => client.AllowedGrantTypes.SingleOrDefault(row => row.Id == rowId),
|
||||
ClientCollection.CorsOrigins => client.AllowedCorsOrigins.SingleOrDefault(row => row.Id == rowId),
|
||||
ClientCollection.IdentityProviders => client.IdentityProviderRestrictions.SingleOrDefault(row => row.Id == rowId),
|
||||
ClientCollection.Claims => client.Claims.SingleOrDefault(row => row.Id == rowId),
|
||||
ClientCollection.Properties => client.Properties.SingleOrDefault(row => row.Id == rowId),
|
||||
_ => throw Invalid("Collection inconnue.")
|
||||
};
|
||||
db.Remove(row ?? throw Missing());
|
||||
await db.SaveChangesAsync(Actor, ct);
|
||||
}
|
||||
|
||||
public async Task<NewClientSecret> CreateSecretAsync(int id, ClientSecretRequest request, bool replace, CancellationToken ct)
|
||||
{
|
||||
var client = await db.Clients.Include(client => client.ClientSecrets).SingleOrDefaultAsync(client => client.Id == id, ct)
|
||||
?? throw Missing();
|
||||
if (request.Expiration <= DateTimeOffset.UtcNow)
|
||||
throw Invalid("L’expiration doit être dans le futur.");
|
||||
var expiration = request.Expiration ?? (replace ? DateTimeOffset.UtcNow.AddDays(90) : null);
|
||||
var raw = replace || string.IsNullOrWhiteSpace(request.Value)
|
||||
? Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
|
||||
: request.Value;
|
||||
if (replace)
|
||||
db.ClientSecrets.RemoveRange(client.ClientSecrets);
|
||||
var secret = new ClientSecret
|
||||
{
|
||||
ClientId = id, Type = "SharedSecret",
|
||||
Value = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(raw))),
|
||||
Description = request.Description, Created = DateTime.UtcNow, Expiration = expiration?.UtcDateTime
|
||||
};
|
||||
db.ClientSecrets.Add(secret);
|
||||
await db.SaveChangesAsync(Actor, ct);
|
||||
return new(secret.Id, raw, expiration);
|
||||
}
|
||||
|
||||
public async Task DeleteSecretAsync(int id, int secretId, CancellationToken ct)
|
||||
{
|
||||
var secret = await db.ClientSecrets.SingleOrDefaultAsync(secret => secret.ClientId == id && secret.Id == secretId, ct)
|
||||
?? throw Missing();
|
||||
db.ClientSecrets.Remove(secret);
|
||||
await db.SaveChangesAsync(Actor, ct);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<AdministrationScope>> GetScopesAsync(CancellationToken ct)
|
||||
=> (await db.ApiScopes.AsNoTracking().OrderBy(scope => scope.Name).ToListAsync(ct)).Select(ToScope).ToArray();
|
||||
|
||||
public async Task<AdministrationScope> SaveScopeAsync(int? id, ApiScopeSettings settings, CancellationToken ct)
|
||||
{
|
||||
if (await db.ApiScopes.AnyAsync(scope => scope.Name == settings.Name && scope.Id != id, ct))
|
||||
throw Conflict("Ce scope existe déjà.");
|
||||
var scope = id.HasValue ? await db.ApiScopes.FindAsync([id.Value], ct) ?? throw Missing() : new ApiScope();
|
||||
scope.Name = settings.Name;
|
||||
scope.DisplayName = settings.DisplayName;
|
||||
scope.Description = settings.Description;
|
||||
scope.Enabled = settings.Enabled;
|
||||
scope.Required = settings.Required;
|
||||
scope.Emphasize = settings.Emphasize;
|
||||
scope.ShowInDiscoveryDocument = settings.ShowInDiscoveryDocument;
|
||||
if (!id.HasValue) db.ApiScopes.Add(scope);
|
||||
await db.SaveChangesAsync(Actor, ct);
|
||||
return ToScope(scope);
|
||||
}
|
||||
|
||||
public async Task DeleteScopeAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var scope = await db.ApiScopes.FindAsync([id], ct) ?? throw Missing();
|
||||
db.ApiScopes.Remove(scope);
|
||||
await db.SaveChangesAsync(Actor, ct);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<MailingTemplateSettings>> GetMailingTemplatesAsync(CancellationToken ct)
|
||||
=> (await db.MailingTemplate.AsNoTracking().OrderBy(template => template.Id).ToListAsync(ct))
|
||||
.Select(template => new MailingTemplateSettings { Id = template.Id, Topic = template.Topic,
|
||||
Body = template.Body, ReplyToAddress = template.ReplyToAddress, ToSend = (MailPeriodicity)template.ToSend }).ToArray();
|
||||
|
||||
public IReadOnlyList<string> GetMailingCriteria() => UserPolicies.Criterias.Keys.Order().ToArray();
|
||||
|
||||
public async Task<MailingTemplateSettings> SaveMailingTemplateAsync(string? id, MailingTemplateSettings settings, CancellationToken ct)
|
||||
{
|
||||
if (id is not null && id != settings.Id) throw Invalid("L’identifiant du modèle ne peut pas changer.");
|
||||
if (id is null && await db.MailingTemplate.AnyAsync(template => template.Id == settings.Id, ct))
|
||||
throw Conflict("Ce modèle existe déjà.");
|
||||
if (!UserPolicies.Criterias.ContainsKey(settings.Id))
|
||||
throw Invalid("Le modèle doit correspondre à un critère de diffusion connu.");
|
||||
var template = id is null ? new MailingTemplate { Id = settings.Id }
|
||||
: await db.MailingTemplate.FindAsync([id], ct) ?? throw Missing();
|
||||
template.Topic = settings.Topic;
|
||||
template.Body = settings.Body;
|
||||
template.ReplyToAddress = settings.ReplyToAddress;
|
||||
template.ToSend = (Periodicity)settings.ToSend;
|
||||
if (id is null) db.MailingTemplate.Add(template);
|
||||
await db.SaveChangesAsync(Actor, ct);
|
||||
return settings;
|
||||
}
|
||||
|
||||
public async Task DeleteMailingTemplateAsync(string id, CancellationToken ct)
|
||||
{
|
||||
var template = await db.MailingTemplate.FindAsync([id], ct) ?? throw Missing();
|
||||
db.MailingTemplate.Remove(template);
|
||||
await db.SaveChangesAsync(Actor, ct);
|
||||
}
|
||||
|
||||
private static DateTimeOffset Utc(DateTime date) => new(DateTime.SpecifyKind(date, DateTimeKind.Utc));
|
||||
|
||||
private static AdministrationScope ToScope(ApiScope scope) => new(scope.Id, new ApiScopeSettings
|
||||
{
|
||||
Name = scope.Name, DisplayName = scope.DisplayName, Description = scope.Description, Enabled = scope.Enabled,
|
||||
Required = scope.Required, Emphasize = scope.Emphasize, ShowInDiscoveryDocument = scope.ShowInDiscoveryDocument
|
||||
});
|
||||
|
||||
private static AdministrationClient ToClient(Client client)
|
||||
{
|
||||
var entries = new List<ClientEntryResponse>();
|
||||
entries.AddRange(client.RedirectUris.Select(row => new ClientEntryResponse(row.Id, ClientCollection.RedirectUris, null, row.RedirectUri)));
|
||||
entries.AddRange(client.PostLogoutRedirectUris.Select(row => new ClientEntryResponse(row.Id, ClientCollection.PostLogoutRedirectUris, null, row.PostLogoutRedirectUri)));
|
||||
entries.AddRange(client.AllowedScopes.Select(row => new ClientEntryResponse(row.Id, ClientCollection.Scopes, null, row.Scope)));
|
||||
entries.AddRange(client.AllowedGrantTypes.Select(row => new ClientEntryResponse(row.Id, ClientCollection.GrantTypes, null, row.GrantType)));
|
||||
entries.AddRange(client.AllowedCorsOrigins.Select(row => new ClientEntryResponse(row.Id, ClientCollection.CorsOrigins, null, row.Origin)));
|
||||
entries.AddRange(client.IdentityProviderRestrictions.Select(row => new ClientEntryResponse(row.Id, ClientCollection.IdentityProviders, null, row.Provider)));
|
||||
entries.AddRange(client.Claims.Select(row => new ClientEntryResponse(row.Id, ClientCollection.Claims, row.Type, row.Value)));
|
||||
entries.AddRange(client.Properties.Select(row => new ClientEntryResponse(row.Id, ClientCollection.Properties, row.Key, row.Value)));
|
||||
return new(client.Id, ReadSettings(client), entries,
|
||||
client.ClientSecrets.Select(secret => new ClientSecretInfo(secret.Id, secret.Description,
|
||||
Utc(secret.Created), secret.Expiration.HasValue ? Utc(secret.Expiration.Value) : null)).ToArray());
|
||||
}
|
||||
|
||||
private static ClientSettings ReadSettings(Client client) => new()
|
||||
{
|
||||
ClientId = client.ClientId, ClientName = client.ClientName, Enabled = client.Enabled, Description = client.Description,
|
||||
ClientUri = client.ClientUri, LogoUri = client.LogoUri, ProtocolType = client.ProtocolType,
|
||||
RequireClientSecret = client.RequireClientSecret, RequireConsent = client.RequireConsent,
|
||||
AllowRememberConsent = client.AllowRememberConsent, AlwaysIncludeUserClaimsInIdToken = client.AlwaysIncludeUserClaimsInIdToken,
|
||||
RequirePkce = client.RequirePkce, AllowPlainTextPkce = client.AllowPlainTextPkce, RequireRequestObject = client.RequireRequestObject,
|
||||
AllowAccessTokensViaBrowser = client.AllowAccessTokensViaBrowser, FrontChannelLogoutUri = client.FrontChannelLogoutUri,
|
||||
FrontChannelLogoutSessionRequired = client.FrontChannelLogoutSessionRequired, BackChannelLogoutUri = client.BackChannelLogoutUri,
|
||||
BackChannelLogoutSessionRequired = client.BackChannelLogoutSessionRequired, AllowOfflineAccess = client.AllowOfflineAccess,
|
||||
IdentityTokenLifetime = client.IdentityTokenLifetime, AccessTokenLifetime = client.AccessTokenLifetime,
|
||||
AuthorizationCodeLifetime = client.AuthorizationCodeLifetime, AbsoluteRefreshTokenLifetime = client.AbsoluteRefreshTokenLifetime,
|
||||
SlidingRefreshTokenLifetime = client.SlidingRefreshTokenLifetime, ConsentLifetime = client.ConsentLifetime,
|
||||
AccessTokenType = (ClientAccessTokenType)client.AccessTokenType,
|
||||
RefreshTokenExpiration = (ClientRefreshTokenExpiration)client.RefreshTokenExpiration,
|
||||
RefreshTokenUsage = (ClientRefreshTokenUsage)client.RefreshTokenUsage, UpdateAccessTokenClaimsOnRefresh = client.UpdateAccessTokenClaimsOnRefresh,
|
||||
EnableLocalLogin = client.EnableLocalLogin, IncludeJwtId = client.IncludeJwtId, AlwaysSendClientClaims = client.AlwaysSendClientClaims,
|
||||
ClientClaimsPrefix = client.ClientClaimsPrefix, PairWiseSubjectSalt = client.PairWiseSubjectSalt,
|
||||
UserSsoLifetime = client.UserSsoLifetime, UserCodeType = client.UserCodeType, DeviceCodeLifetime = client.DeviceCodeLifetime,
|
||||
AllowedIdentityTokenSigningAlgorithms = client.AllowedIdentityTokenSigningAlgorithms
|
||||
};
|
||||
|
||||
private static void ApplySettings(Client client, ClientSettings settings)
|
||||
{
|
||||
client.ClientId = settings.ClientId; client.ClientName = settings.ClientName; client.Enabled = settings.Enabled;
|
||||
client.Description = settings.Description; client.ClientUri = settings.ClientUri; client.LogoUri = settings.LogoUri;
|
||||
client.ProtocolType = settings.ProtocolType; client.RequireClientSecret = settings.RequireClientSecret;
|
||||
client.RequireConsent = settings.RequireConsent; client.AllowRememberConsent = settings.AllowRememberConsent;
|
||||
client.AlwaysIncludeUserClaimsInIdToken = settings.AlwaysIncludeUserClaimsInIdToken;
|
||||
client.RequirePkce = settings.RequirePkce; client.AllowPlainTextPkce = settings.AllowPlainTextPkce;
|
||||
client.RequireRequestObject = settings.RequireRequestObject; client.AllowAccessTokensViaBrowser = settings.AllowAccessTokensViaBrowser;
|
||||
client.FrontChannelLogoutUri = settings.FrontChannelLogoutUri; client.FrontChannelLogoutSessionRequired = settings.FrontChannelLogoutSessionRequired;
|
||||
client.BackChannelLogoutUri = settings.BackChannelLogoutUri; client.BackChannelLogoutSessionRequired = settings.BackChannelLogoutSessionRequired;
|
||||
client.AllowOfflineAccess = settings.AllowOfflineAccess; client.IdentityTokenLifetime = settings.IdentityTokenLifetime;
|
||||
client.AccessTokenLifetime = settings.AccessTokenLifetime; client.AuthorizationCodeLifetime = settings.AuthorizationCodeLifetime;
|
||||
client.AbsoluteRefreshTokenLifetime = settings.AbsoluteRefreshTokenLifetime; client.SlidingRefreshTokenLifetime = settings.SlidingRefreshTokenLifetime;
|
||||
client.ConsentLifetime = settings.ConsentLifetime; client.AccessTokenType = (int)settings.AccessTokenType;
|
||||
client.RefreshTokenExpiration = (int)settings.RefreshTokenExpiration; client.RefreshTokenUsage = (int)settings.RefreshTokenUsage;
|
||||
client.UpdateAccessTokenClaimsOnRefresh = settings.UpdateAccessTokenClaimsOnRefresh; client.EnableLocalLogin = settings.EnableLocalLogin;
|
||||
client.IncludeJwtId = settings.IncludeJwtId; client.AlwaysSendClientClaims = settings.AlwaysSendClientClaims;
|
||||
client.ClientClaimsPrefix = settings.ClientClaimsPrefix; client.PairWiseSubjectSalt = settings.PairWiseSubjectSalt;
|
||||
client.UserSsoLifetime = settings.UserSsoLifetime; client.UserCodeType = settings.UserCodeType;
|
||||
client.DeviceCodeLifetime = settings.DeviceCodeLifetime; client.AllowedIdentityTokenSigningAlgorithms = settings.AllowedIdentityTokenSigningAlgorithms;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
using Yavsc.ApiControllers.Administration;
|
||||
|
||||
namespace Yavsc.Api.Services;
|
||||
|
||||
public static class AdministrationServiceCollectionExtensions
|
||||
{
|
||||
public static IServiceCollection AddSiteAdministration(this IServiceCollection services)
|
||||
{
|
||||
services.AddHttpContextAccessor();
|
||||
services.AddScoped<IAdministrationService, AdministrationService>();
|
||||
services.AddScoped<AdministrationExceptionFilter>();
|
||||
services.AddOpenApi("administration", options =>
|
||||
options.ShouldInclude = description => description.GroupName == "administration");
|
||||
return services;
|
||||
}
|
||||
}
|
||||
34
src/Yavsc.Api/Services/IAdministrationService.cs
Normal file
34
src/Yavsc.Api/Services/IAdministrationService.cs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
using Yavsc.Abstract.Administration;
|
||||
|
||||
namespace Yavsc.Api.Services;
|
||||
|
||||
public interface IAdministrationService
|
||||
{
|
||||
Task<AdministrationSummary> GetSummaryAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<AdministrationRole>> GetRolesAsync(CancellationToken ct);
|
||||
Task EnsureRolesAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<RoleMember>> GetRoleMembersAsync(string roleId, CancellationToken ct);
|
||||
Task SetRoleMembershipAsync(string roleId, string userId, bool member, CancellationToken ct);
|
||||
Task<IReadOnlyList<AdministrationClient>> GetClientsAsync(CancellationToken ct);
|
||||
Task<AdministrationClient?> GetClientAsync(int id, CancellationToken ct);
|
||||
Task<AdministrationClient> SaveClientAsync(int? id, ClientSettings settings, CancellationToken ct);
|
||||
Task DeleteClientAsync(int id, CancellationToken ct);
|
||||
Task AddClientEntryAsync(int id, ClientCollection collection, ClientEntry entry, CancellationToken ct);
|
||||
Task DeleteClientEntryAsync(int id, ClientCollection collection, int rowId, CancellationToken ct);
|
||||
Task<NewClientSecret> CreateSecretAsync(int id, ClientSecretRequest request, bool replace, CancellationToken ct);
|
||||
Task DeleteSecretAsync(int id, int secretId, CancellationToken ct);
|
||||
Task<IReadOnlyList<AdministrationScope>> GetScopesAsync(CancellationToken ct);
|
||||
Task<AdministrationScope> SaveScopeAsync(int? id, ApiScopeSettings settings, CancellationToken ct);
|
||||
Task DeleteScopeAsync(int id, CancellationToken ct);
|
||||
Task<IReadOnlyList<MailingTemplateSettings>> GetMailingTemplatesAsync(CancellationToken ct);
|
||||
IReadOnlyList<string> GetMailingCriteria();
|
||||
Task<MailingTemplateSettings> SaveMailingTemplateAsync(string? id, MailingTemplateSettings settings, CancellationToken ct);
|
||||
Task DeleteMailingTemplateAsync(string id, CancellationToken ct);
|
||||
Task<AdministrationTransfer> ExportAsync(CancellationToken ct);
|
||||
Task<ImportResult> ImportAsync(AdministrationTransfer transfer, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class AdministrationOperationException(int statusCode, string message) : Exception(message)
|
||||
{
|
||||
public int StatusCode { get; } = statusCode;
|
||||
}
|
||||
|
|
@ -12,6 +12,7 @@
|
|||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" />
|
||||
<ProjectReference Include="../Yavsc.Server/Yavsc.Server.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Loading…
Reference in a new issue