Files
Heimdall/src/Heimdall.Infrastructure/Services/SiteService.cs
T
Arnaud Dartois b217c932e8 feat(mvp): implement MVP multi-site platform
Complete MVP implementation (Étape 1) covering:
- Domain: primitives (Entity<TId>, ValueObject), 10 entities, 6 enums
- EF Core: AppDbContext + Identity, 8 EntityTypeConfigurations, audit/soft-delete interceptors, initial migration
- Application: service interfaces, DTOs, FluentValidation, ServiceResult pattern
- Security: Identity + JWT + API Key multi-auth, role-based permissions, constant-time key validation
- API: Auth/Sites/Agents controllers with explicit auth scheme policies
- Workers: Hangfire PostgreSQL setup with schema isolation, HeartbeatMonitorJob
- Agent: registration service + 30s heartbeat loop
- Docker: multi-stage Dockerfiles for central + agent, docker-compose.yml
- CI/CD: GitHub Actions pipeline with build+test and Docker build
- Tests: 13 domain tests (Site, Agent, Camera entities)

Architecture decisions per deliberation council:
- API Key via AuthenticationHandler<T> (not middleware)
- Explicit [Authorize(AuthenticationSchemes)] on all endpoints
- Event/Recording/Person/Vehicle deferred from initial migration
- Hangfire compatible with .NET 10 (v1.8.17)
2026-07-16 20:53:56 +00:00

117 lines
4.3 KiB
C#

using System.Security.Cryptography;
using System.Text;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Infrastructure.Services;
public class SiteService : ISiteService
{
private readonly AppDbContext _db;
public SiteService(AppDbContext db) => _db = db;
public async Task<ServiceResult<SiteWithTokenResponse>> CreateAsync(CreateSiteRequest request, Guid userId, CancellationToken ct)
{
var existing = await _db.Sites.AnyAsync(s => s.Name == request.Name, ct);
if (existing)
return ServiceResult<SiteWithTokenResponse>.Conflict("A site with this name already exists");
var site = new Site(request.Name, request.Address, request.Timezone);
_db.Sites.Add(site);
// Generate registration token
var (plainToken, tokenHash, expiresAt) = GenerateRegistrationToken();
site.GenerateRegistrationToken(tokenHash, expiresAt);
await _db.SaveChangesAsync(ct);
// Audit log
_db.AuditLogs.Add(new AuditLog(userId, "Site.Created", "Site", site.Id.ToString()));
await _db.SaveChangesAsync(ct);
return ServiceResult<SiteWithTokenResponse>.Success(new SiteWithTokenResponse(
site.Id, site.Name, site.Address, site.Timezone,
plainToken, expiresAt, site.CreatedAt));
}
public async Task<ServiceResult<SiteResponse>> GetByIdAsync(Guid id, CancellationToken ct)
{
var site = await _db.Sites.FindAsync([id], ct);
if (site is null)
return ServiceResult<SiteResponse>.NotFound("Site not found");
return ServiceResult<SiteResponse>.Success(MapResponse(site));
}
public async Task<ServiceResult<PagedResult<SiteResponse>>> ListAsync(int page, int pageSize, CancellationToken ct)
{
var query = _db.Sites.OrderBy(s => s.Name);
var total = await query.CountAsync(ct);
var items = await query
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(s => MapResponse(s))
.ToListAsync(ct);
return ServiceResult<PagedResult<SiteResponse>>.Success(
new PagedResult<SiteResponse>(items, total, page, pageSize));
}
public async Task<ServiceResult<SiteResponse>> UpdateAsync(Guid id, UpdateSiteRequest request, CancellationToken ct)
{
var site = await _db.Sites.FindAsync([id], ct);
if (site is null)
return ServiceResult<SiteResponse>.NotFound("Site not found");
site.Update(request.Name, request.Address, request.Timezone);
await _db.SaveChangesAsync(ct);
return ServiceResult<SiteResponse>.Success(MapResponse(site));
}
public async Task<ServiceResult> DeleteAsync(Guid id, CancellationToken ct)
{
var site = await _db.Sites.FindAsync([id], ct);
if (site is null)
return ServiceResult.NotFound("Site not found");
site.SoftDelete();
await _db.SaveChangesAsync(ct);
return ServiceResult.Success();
}
public async Task<ServiceResult<RegistrationTokenResponse>> GenerateTokenAsync(Guid id, CancellationToken ct)
{
var site = await _db.Sites.FindAsync([id], ct);
if (site is null)
return ServiceResult<RegistrationTokenResponse>.NotFound("Site not found");
var (plainToken, tokenHash, expiresAt) = GenerateRegistrationToken();
site.GenerateRegistrationToken(tokenHash, expiresAt);
await _db.SaveChangesAsync(ct);
return ServiceResult<RegistrationTokenResponse>.Success(
new RegistrationTokenResponse(plainToken, expiresAt));
}
private static (string plainToken, string tokenHash, DateTime expiresAt) GenerateRegistrationToken()
{
var tokenBytes = new byte[32];
RandomNumberGenerator.Fill(tokenBytes);
var plainToken = Convert.ToHexString(tokenBytes).ToLowerInvariant();
var tokenHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(plainToken))).ToLowerInvariant();
var expiresAt = DateTime.UtcNow.AddDays(1);
return (plainToken, tokenHash, expiresAt);
}
private static SiteResponse MapResponse(Site s) => new(
s.Id, s.Name, s.Address, s.Timezone, s.Enabled, s.CreatedAt);
}