fix(identity): harden user lifecycle and permissions (#136)
Heimdall Gitea / Detect CI scope (push) Successful in 7s
Heimdall Gitea / Build and tests (push) Successful in 14m48s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 4m27s
Heimdall Gitea / Build and scan agent image (push) Successful in 15m42s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m27s
Heimdall Gitea / CI policy (push) Successful in 2s
Heimdall Gitea / Detect CI scope (push) Successful in 7s
Heimdall Gitea / Build and tests (push) Successful in 14m48s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 4m27s
Heimdall Gitea / Build and scan agent image (push) Successful in 15m42s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m27s
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
This commit was merged in pull request #136.
This commit is contained in:
1 parent
ea5f0b7589
commit
89c4c43922
153 files changed
+5218
-1681
No files matched your search
@@ -119,7 +119,7 @@ jobs:
|
||||
needs: [changes]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:0d99ebf1ccad15037b5c98c9fe8979d6b8dbac23812feae2277a0b277b5c5ffa
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine@sha256:b0f9560a2de083e2cc7382e75f808c7381a32852a7ec49117deedb300e552b24
|
||||
@@ -208,7 +208,7 @@ jobs:
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:0d99ebf1ccad15037b5c98c9fe8979d6b8dbac23812feae2277a0b277b5c5ffa
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
@@ -250,7 +250,7 @@ jobs:
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:0d99ebf1ccad15037b5c98c9fe8979d6b8dbac23812feae2277a0b277b5c5ffa
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
@@ -292,7 +292,7 @@ jobs:
|
||||
needs: [changes, server_image, agent_image]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:0d99ebf1ccad15037b5c98c9fe8979d6b8dbac23812feae2277a0b277b5c5ffa
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
@@ -327,7 +327,7 @@ jobs:
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:0d99ebf1ccad15037b5c98c9fe8979d6b8dbac23812feae2277a0b277b5c5ffa
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
# Server/PWA: restore the complete project graph from locked dependencies.
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:0d99ebf1ccad15037b5c98c9fe8979d6b8dbac23812feae2277a0b277b5c5ffa AS build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b AS build
|
||||
WORKDIR /src
|
||||
ARG VERSION=0.0.0-local
|
||||
COPY global.json Directory.Build.props Directory.Build.targets ./
|
||||
@@ -8,7 +8,7 @@ COPY install/ ./install/
|
||||
RUN dotnet restore src/Heimdall.Web/Heimdall.Web.csproj --locked-mode
|
||||
RUN dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release --no-restore -o /out -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:d5633778c754e89a386882eddf8dbee6942447a8a4b8267c19cf1e1158d0b0ac
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee
|
||||
WORKDIR /app
|
||||
RUN apt-get update -qq && apt-get install -y --no-install-recommends wget tzdata && rm -rf /var/lib/apt/lists/*
|
||||
ENV ASPNETCORE_URLS=http://+:8080
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# CPU agent: use glibc for ONNX native dependencies. GPU variants need a
|
||||
# separately validated .NET/native-library runtime and are not published here.
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:0d99ebf1ccad15037b5c98c9fe8979d6b8dbac23812feae2277a0b277b5c5ffa AS build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:de4fe90a98845d75910b9769662465c84de1a934665c431279d1382b2bddc02b AS build
|
||||
WORKDIR /src
|
||||
ARG VERSION=0.0.0-local
|
||||
ARG TARGET_RUNTIME=cpu
|
||||
@@ -10,7 +10,7 @@ COPY src/ ./src/
|
||||
RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj --locked-mode
|
||||
RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-restore -o /out -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:d5633778c754e89a386882eddf8dbee6942447a8a4b8267c19cf1e1158d0b0ac
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:de0ee358cdd672f7017a003bed21e9ac9ed48a27c922a59b18175b6e82fa7fee
|
||||
WORKDIR /app
|
||||
RUN apt-get update -qq && apt-get install -y --no-install-recommends ffmpeg wget libgomp1 tzdata && rm -rf /var/lib/apt/lists/*
|
||||
RUN install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall
|
||||
|
||||
@@ -245,7 +245,7 @@ Interfaces, DTOs, validateurs.
|
||||
|
||||
| Service | Méthodes |
|
||||
|---------|----------|
|
||||
| `IAuthService` | Register, Login, Verify2fa, RefreshToken, RegisterAdmin |
|
||||
| `IAuthService` | BootstrapAdmin, Login, Verify2fa, RefreshToken, ChangePassword |
|
||||
| `ISiteService` | Create, GetById, List, Update, Delete, GenerateToken |
|
||||
| `IAgentService` | Register, Heartbeat, GetById, ListBySite |
|
||||
| `IUserService` | List, GetById, Create, Update, AssignRoles, AssignSites, ResetPassword, Lock, Unlock |
|
||||
@@ -285,11 +285,15 @@ Authentification AVANT d'exposer l'API.
|
||||
|
||||
| Méthode | Route | Auth | Status |
|
||||
|---|---|---|---|
|
||||
| `POST` | `/api/auth/register` | — | ✅ |
|
||||
| `GET` | `/api/auth/bootstrap-status` | — | ✅ |
|
||||
| `POST` | `/api/auth/bootstrap-admin` | — (first account only) | ✅ |
|
||||
| `POST` | `/api/auth/login` | — | ✅ |
|
||||
| `POST` | `/api/auth/2fa/verify` | — | ✅ |
|
||||
| `POST` | `/api/auth/refresh` | — | ✅ |
|
||||
| `POST` | `/api/auth/register-admin` | Test/Dev only | ✅ |
|
||||
| `POST` | `/api/auth/register` | Retired (404) | ✅ |
|
||||
| `POST` | `/api/auth/register-admin` | Retired (404) | ✅ |
|
||||
| `/api/users/*` | User creation and lifecycle | Admin.Users; surfaced in `/users` UI | ✅ |
|
||||
| `PUT` | `/api/roles/{name}/permissions` | Admin.Manage; surfaced in `/admin/claims` UI (Admin role fixed) | ✅ |
|
||||
|
||||
---
|
||||
|
||||
|
||||
+7
-1
@@ -1 +1,7 @@
|
||||
{"sdk":{"version":"10.0.402","rollForward":"disable","allowPrerelease":false}}
|
||||
{
|
||||
"sdk": {
|
||||
"version": "10.0.100",
|
||||
"rollForward": "latestFeature",
|
||||
"allowPrerelease": false
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
#:property RestoreLockedMode=true
|
||||
#:package Microsoft.Playwright@1.61.0
|
||||
return Microsoft.Playwright.Program.Main(args);
|
||||
@@ -1,55 +0,0 @@
|
||||
{
|
||||
"version": 1,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"Microsoft.DotNet.ILCompiler": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.13, )",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "MnT222WlxhelguLZTQx9soBHKW7TeY6A9YUwVaprjUd+ARlhLAkfsXGFNX9w6kRq89/yxUcAQ/lzvmgndSFfOw=="
|
||||
},
|
||||
"Microsoft.NET.ILLink.Tasks": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.13, )",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "40yrBMsLEcjixBR4G+FiUaBPvxXIPSKJ2OgSrbOZcmSDBda4Sb0k7BWrfDpIvn3IvvDzwOL/tEPa6gDQfh6aRw=="
|
||||
},
|
||||
"Microsoft.Playwright": {
|
||||
"type": "Direct",
|
||||
"requested": "[1.61.0, )",
|
||||
"resolved": "1.61.0",
|
||||
"contentHash": "VM149rQ2Pu+3xAzrO2gvh2WRgrWNbIl0jL9LG2oMC9xKUVYDnUrsh+E/5S+NQToVV4S+yhZ3NHsa6kf1PdHeag==",
|
||||
"dependencies": {
|
||||
"Microsoft.Bcl.AsyncInterfaces": "6.0.0",
|
||||
"System.ComponentModel.Annotations": "5.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Bcl.AsyncInterfaces": {
|
||||
"type": "Transitive",
|
||||
"resolved": "6.0.0",
|
||||
"contentHash": "UcSjPsst+DfAdJGVDsu346FX0ci0ah+lw3WRtn18NUwEqRt70HaOQ7lI72vy3+1LxtqI3T5GWwV39rQSrCzAeg=="
|
||||
},
|
||||
"System.ComponentModel.Annotations": {
|
||||
"type": "Transitive",
|
||||
"resolved": "5.0.0",
|
||||
"contentHash": "dMkqfy2el8A8/I76n2Hi1oBFEbG1SfxD2l5nhwXV3XjlnOmwxJlQbYpJH4W51odnU9sARCSAgv7S3CyAFMkpYg=="
|
||||
}
|
||||
},
|
||||
"net10.0/linux-x64": {
|
||||
"Microsoft.DotNet.ILCompiler": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.13, )",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "MnT222WlxhelguLZTQx9soBHKW7TeY6A9YUwVaprjUd+ARlhLAkfsXGFNX9w6kRq89/yxUcAQ/lzvmgndSFfOw==",
|
||||
"dependencies": {
|
||||
"runtime.linux-x64.Microsoft.DotNet.ILCompiler": "10.0.13"
|
||||
}
|
||||
},
|
||||
"runtime.linux-x64.Microsoft.DotNet.ILCompiler": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "cyR6nLIi+teN7+T6pYDeeoVRTzz4RQYimON6CxqvRVTylz0XVCWj/wcfa1IsI4yR/3zKkX6hfR4E2cEuAit49A=="
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ if [[ "$status" != 0 ]]; then exit "$status"; fi
|
||||
dbname="ci_${name//./_}"
|
||||
psql --no-password -v ON_ERROR_STOP=1 -c "CREATE DATABASE \"$dbname\"" >/dev/null
|
||||
if [[ "$name" == Heimdall.E2E.Tests ]]; then
|
||||
dotnet run scripts/ci/install-chromium.cs -- install --with-deps chromium
|
||||
node tests/Heimdall.E2E.Tests/bin/Release/net10.0/.playwright/package/cli.js install --with-deps chromium
|
||||
fi
|
||||
coverage_args=()
|
||||
if [[ "$name" == Heimdall.Application.Tests || "$name" == Heimdall.Infrastructure.Tests || "$name" == Heimdall.Web.Tests ]]; then
|
||||
|
||||
@@ -25,7 +25,7 @@ for project in tests/*/*.csproj; do
|
||||
dotnet test "$project" -c Release --no-build --no-restore \
|
||||
--logger 'trx;LogFileName=results.trx' --results-directory "artifacts/tests/$name" || status=1
|
||||
done
|
||||
dotnet run scripts/ci/install-chromium.cs -- install --with-deps chromium
|
||||
dotnet run --runtime linux-x64 scripts/ci/install-chromium.cs -- install --with-deps chromium
|
||||
psql --no-password -v ON_ERROR_STOP=1 -c "CREATE DATABASE ci_e2e" >/dev/null
|
||||
DATABASE_URL="$DATABASE_URL;Database=ci_e2e" \
|
||||
dotnet test tests/Heimdall.E2E.Tests -c Release --no-build --no-restore \
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
name: heimdall-identity
|
||||
description: Implement and review Heimdall account, password, session, email confirmation, lockout, and two-factor authentication flows built on ASP.NET Core Identity.
|
||||
---
|
||||
|
||||
# Heimdall Identity workflow
|
||||
|
||||
Read `AGENTS.md`, the `AUTH-BOOTSTRAP` entry in `todo.md`, and the Identity wiring in `Infrastructure/DependencyInjection.cs` and `Web/Program.cs` before changing authentication.
|
||||
|
||||
- Identity owns password hashing, normalized account lookup, role membership, lockout, authenticator tokens, and email/password tokens. Do not duplicate password or token cryptography in Heimdall.
|
||||
- Keep ASP.NET Core Identity packages and types inside Infrastructure. Domain must not reference Identity; Application uses `IIdentityAccountService` and `IdentityAccount` only. Put Identity EF entities (`IdentityAppUser`, `IdentityAppRole`) and `UserManager`/`RoleManager` adapters in Infrastructure. Keep user-related Domain relationships keyed by `Guid UserId`; configure their foreign keys to the Infrastructure user entity.
|
||||
- When creating an Identity user, copy the generated `SecurityStamp` back into the application account before building the first session/JWT. Cover bootstrap and regular user creation with a relational session validation test.
|
||||
- Moving Identity model classes without changing tables should produce an explicit empty EF migration and a snapshot containing the Infrastructure entity types. Verify migration compatibility against PostgreSQL before release.
|
||||
- Keep bootstrap one-time and PostgreSQL-serializable. Anonymous registration stays disabled after bootstrap; role and account creation failures must not be reported as success.
|
||||
- Keep public login/reset responses generic so they do not reveal account existence, lockout state, or Identity policy details. Logs must not contain emails, passwords, tokens, authenticator keys, recovery codes, or Identity error descriptions; log safe error codes only when needed.
|
||||
- Rotate `SecurityStamp` after password changes/resets, email or role changes, lock/unlock, and 2FA changes. Verify existing cookies, JWTs, and refresh tokens are rejected after the change.
|
||||
- Enroll an authenticator in two steps: create/show the setup key while 2FA remains disabled; renew the user's access token and cookie after Identity rotates the security stamp; verify a TOTP code before enabling 2FA and creating one-time recovery codes. Persist only hashes of recovery codes, redeem each atomically once, and clear them when 2FA is disabled.
|
||||
- Check every `IdentityResult` before proceeding. Avoid partial account creation; clean up the created user if role assignment fails.
|
||||
- Keep first-account provisioning on `/setup` → `/api/auth/bootstrap-admin`; later accounts and role assignment use `/users` → `/api/users`. Do not reintroduce a second Admin-registration endpoint.
|
||||
- Keep the three supported role names seeded by Identity. Seed their default permission claims once using a durable role-claim marker; the Admin permission set stays immutable. Manage Supervisor/Viewer permission claims from `/admin/claims`, then include those persisted claims in login, refresh, cookie, and 2FA auth responses.
|
||||
- When role membership or role permissions change, rotate every affected user's security stamp and record the acting administrator in the audit log. Protect last-admin demotion, deletion, and lockout based on unlocked Admin accounts.
|
||||
- Apply `[Collection("E2E")]` on each concrete Playwright test class deriving from `E2ETestBase`; xUnit does not reliably inherit the PostgreSQL fixture attribute from its abstract base.
|
||||
- Configure Identity options explicitly and review changes to password, unique email, confirmed email, lockout, cookie, token-provider, and Data Protection behavior.
|
||||
- CI installs Chromium through the Playwright CLI already copied beside the Release E2E test assembly (`node tests/Heimdall.E2E.Tests/bin/Release/net10.0/.playwright/package/cli.js install --with-deps chromium`). This keeps browser tooling on the test project's locked Playwright dependency graph and avoids an independently restored C# script project.
|
||||
- Keep PostgreSQL-specific transaction and concurrency guarantees in Infrastructure. Use relational integration tests for bootstrap races, recovery-code redemption, session revocation, and migration compatibility.
|
||||
- For behavior changes, update FR/EN resources and UI/API contracts, add focused tests, update `todo.md`, and run the disposable Compose acceptance recipe with unique credentials, ports, volumes, project name, and network.
|
||||
- Acceptance must exercise bootstrap through the setup UI, user lifecycle and role editing through `/users`, permission editing through `/admin/claims`, and verify the resulting JWT/API allow and deny decisions. Check that stale sessions fail after a role/permission change and that the last usable Admin cannot be demoted, deleted, or locked.
|
||||
|
||||
Useful official references: [ASP.NET Core Identity configuration](https://learn.microsoft.com/aspnet/core/security/authentication/identity-configuration), [Two-factor authentication](https://learn.microsoft.com/aspnet/core/security/authentication/identity-enable-qrcodes), and [Data Protection](https://learn.microsoft.com/aspnet/core/security/data-protection/introduction).
|
||||
+4
-5
@@ -4,6 +4,7 @@ using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Assignments.Commands.CreateUserCameraAccess;
|
||||
|
||||
@@ -16,16 +17,14 @@ public record CreateUserCameraAccessCommand(
|
||||
public class CreateUserCameraAccessHandler : IRequestHandler<CreateUserCameraAccessCommand, ServiceResult<UserCameraAccessResponse>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly IIdentityAccountService _identity;
|
||||
|
||||
public CreateUserCameraAccessHandler(IApplicationDbContext db) => _db = db;
|
||||
public CreateUserCameraAccessHandler(IApplicationDbContext db, IIdentityAccountService identity) => (_db, _identity) = (db, identity);
|
||||
|
||||
public async Task<ServiceResult<UserCameraAccessResponse>> Handle(CreateUserCameraAccessCommand request, CancellationToken ct)
|
||||
{
|
||||
// Verify user exists
|
||||
var user = await _db.Users
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(u => u.Id == request.UserId, ct)
|
||||
.ConfigureAwait(false);
|
||||
var user = await _identity.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
return ServiceResult<UserCameraAccessResponse>.NotFound("User not found");
|
||||
|
||||
|
||||
+4
-4
@@ -4,6 +4,7 @@ using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Text.Json;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Assignments.Commands.ReplaceUserCameraAccess;
|
||||
|
||||
@@ -12,15 +13,14 @@ public sealed class ReplaceUserCameraAccessCommandHandler
|
||||
{
|
||||
private const int MaximumGrantCount = 500;
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly IIdentityAccountService _identity;
|
||||
|
||||
public ReplaceUserCameraAccessCommandHandler(IApplicationDbContext db) => _db = db;
|
||||
public ReplaceUserCameraAccessCommandHandler(IApplicationDbContext db, IIdentityAccountService identity) => (_db, _identity) = (db, identity);
|
||||
|
||||
public async Task<ServiceResult<IReadOnlyList<UserCameraAccessResponse>>> Handle(
|
||||
ReplaceUserCameraAccessCommand request, CancellationToken ct)
|
||||
{
|
||||
var userExists = await _db.Users.AsNoTracking().AnyAsync(u => u.Id == request.UserId, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (!userExists)
|
||||
if (await _identity.FindByIdAsync(request.UserId, ct).ConfigureAwait(false) is null)
|
||||
return ServiceResult<IReadOnlyList<UserCameraAccessResponse>>.NotFound("User not found");
|
||||
|
||||
if (request.Grants.Count > MaximumGrantCount)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -19,7 +20,8 @@ public class GetAuditLogsQueryHandler
|
||||
: IRequestHandler<GetAuditLogsQuery, ServiceResult<PagedResult<AuditLogResponse>>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
public GetAuditLogsQueryHandler(IApplicationDbContext db) => _db = db;
|
||||
private readonly IUserRepository _users;
|
||||
public GetAuditLogsQueryHandler(IApplicationDbContext db, IUserRepository users) => (_db, _users) = (db, users);
|
||||
public async Task<ServiceResult<PagedResult<AuditLogResponse>>> Handle(
|
||||
GetAuditLogsQuery request, CancellationToken ct)
|
||||
{
|
||||
@@ -49,11 +51,19 @@ public class GetAuditLogsQueryHandler
|
||||
.Take(request.PageSize)
|
||||
.Select(al => new AuditLogResponse(
|
||||
al.Id, al.UserId,
|
||||
al.User != null ? al.User.Email : null,
|
||||
(string?)null,
|
||||
al.Action, al.ResourceType, al.ResourceId,
|
||||
al.OldValue, al.NewValue, al.IpAddress, al.Timestamp))
|
||||
.ToListAsync(ct);
|
||||
|
||||
var userIds = items.Where(item => item.UserId.HasValue).Select(item => item.UserId!.Value).Distinct().ToArray();
|
||||
var emails = userIds.Length == 0
|
||||
? new Dictionary<Guid, string?>()
|
||||
: await _users.GetEmailsAsync(userIds, ct).ConfigureAwait(false);
|
||||
items = items.Select(item => item.UserId.HasValue && emails.TryGetValue(item.UserId.Value, out var email)
|
||||
? item with { UserEmail = email }
|
||||
: item).ToList();
|
||||
|
||||
// Batch-resolve resource names
|
||||
var siteIds = items.Where(i => i.ResourceType == "Site" && i.ResourceId != null)
|
||||
.Select(i => Guid.Parse(i.ResourceId!)).Distinct().ToList();
|
||||
|
||||
@@ -2,21 +2,21 @@ using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Application.Auth;
|
||||
|
||||
internal static class AuthHelper
|
||||
{
|
||||
internal static async Task<ServiceResult<AuthResponse>> CreateAuthResponseAsync(
|
||||
AppUser user,
|
||||
IdentityAccount user,
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
UserManager<AppUser> userManager,
|
||||
DateTime? sessionStarted = null)
|
||||
IIdentityAccountService userManager,
|
||||
DateTime? sessionStarted = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var roles = await userManager.GetRolesAsync(user).ConfigureAwait(false);
|
||||
var permissions = rolePermissionService.GetPermissionsForRoles(roles);
|
||||
var roles = await userManager.GetRolesAsync(user, ct).ConfigureAwait(false);
|
||||
var permissions = await rolePermissionService.GetPermissionsForRolesAsync(roles, ct).ConfigureAwait(false);
|
||||
|
||||
var (accessToken, expiresAt) = sessionStarted is null
|
||||
? jwtService.GenerateAccessToken(user, roles, permissions)
|
||||
@@ -30,12 +30,14 @@ internal static class AuthHelper
|
||||
refreshToken,
|
||||
expiresAt,
|
||||
false,
|
||||
new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles])));
|
||||
new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles], [.. permissions])));
|
||||
}
|
||||
|
||||
internal static async Task<UserInfo> MapUserInfoAsync(AppUser user, UserManager<AppUser> userManager)
|
||||
internal static async Task<UserInfo> MapUserInfoAsync(IdentityAccount user, IIdentityAccountService userManager,
|
||||
IRolePermissionService rolePermissionService, CancellationToken ct)
|
||||
{
|
||||
var roles = await userManager.GetRolesAsync(user).ConfigureAwait(false);
|
||||
return new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles]);
|
||||
var roles = await userManager.GetRolesAsync(user, ct).ConfigureAwait(false);
|
||||
var permissions = await rolePermissionService.GetPermissionsForRolesAsync(roles, ct).ConfigureAwait(false);
|
||||
return new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles], [.. permissions]);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.BootstrapAdmin;
|
||||
@@ -11,13 +10,13 @@ namespace Heimdall.Application.Auth.Commands.BootstrapAdmin;
|
||||
public sealed class BootstrapAdminHandler : IRequestHandler<BootstrapAdminCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly IAuthDataService _authData;
|
||||
private readonly UserManager<AppUser> _users;
|
||||
private readonly IIdentityAccountService _users;
|
||||
private readonly IJwtService _jwt;
|
||||
private readonly IRolePermissionService _permissions;
|
||||
private readonly IPasswordBreachChecker _breachChecker;
|
||||
private readonly ILogger<BootstrapAdminHandler> _logger;
|
||||
|
||||
public BootstrapAdminHandler(IAuthDataService authData, UserManager<AppUser> users, IJwtService jwt,
|
||||
public BootstrapAdminHandler(IAuthDataService authData, IIdentityAccountService users, IJwtService jwt,
|
||||
IRolePermissionService permissions, IPasswordBreachChecker breachChecker,
|
||||
ILogger<BootstrapAdminHandler> logger)
|
||||
{
|
||||
@@ -39,25 +38,32 @@ public sealed class BootstrapAdminHandler : IRequestHandler<BootstrapAdminComman
|
||||
if (await _authData.HasAnyUsersAsync(token).ConfigureAwait(false))
|
||||
return ServiceResult<AuthResponse>.Conflict("Initial administrator setup has already been completed.");
|
||||
|
||||
var user = new AppUser
|
||||
var user = new IdentityAccount
|
||||
{
|
||||
UserName = request.Email,
|
||||
Email = request.Email,
|
||||
DisplayName = request.DisplayName,
|
||||
EmailConfirmed = true
|
||||
};
|
||||
var created = await _users.CreateAsync(user, request.Password).ConfigureAwait(false);
|
||||
var created = await _users.CreateAsync(user, request.Password, ct).ConfigureAwait(false);
|
||||
if (!created.Succeeded)
|
||||
return ServiceResult<AuthResponse>.Failure(string.Join(", ", created.Errors.Select(e => e.Description)));
|
||||
{
|
||||
_logger.LogWarning("Identity rejected initial administrator creation with codes {Codes}", string.Join(',', created.ErrorCodes));
|
||||
return ServiceResult<AuthResponse>.Failure("Initial administrator creation failed");
|
||||
}
|
||||
|
||||
var role = await _users.AddToRoleAsync(user, "Admin").ConfigureAwait(false);
|
||||
var role = await _users.AddToRoleAsync(user, "Admin", token).ConfigureAwait(false);
|
||||
if (!role.Succeeded)
|
||||
return ServiceResult<AuthResponse>.Failure(string.Join(", ", role.Errors.Select(e => e.Description)));
|
||||
{
|
||||
await _users.DeleteAsync(user, ct).ConfigureAwait(false);
|
||||
_logger.LogWarning("Identity rejected initial administrator role assignment with codes {Codes}", string.Join(',', role.ErrorCodes));
|
||||
return ServiceResult<AuthResponse>.Failure("Initial administrator creation failed");
|
||||
}
|
||||
|
||||
await _authData.SetSettingValueAsync("auth.public-registration.enabled", "false", "auth",
|
||||
"Public registration is disabled; accounts are created by administrators.", token).ConfigureAwait(false);
|
||||
_logger.LogInformation("Initial administrator account created for {Email}", request.Email);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwt, _permissions, _users).ConfigureAwait(false);
|
||||
_logger.LogInformation("Initial administrator account created");
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwt, _permissions, _users, ct: token).ConfigureAwait(false);
|
||||
}, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,18 @@ using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.ChangePassword;
|
||||
|
||||
public class ChangePasswordHandler : IRequestHandler<ChangePasswordCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IPasswordBreachChecker _breachChecker;
|
||||
private readonly ILogger<ChangePasswordHandler> _logger;
|
||||
|
||||
public ChangePasswordHandler(
|
||||
UserManager<AppUser> userManager,
|
||||
IIdentityAccountService userManager,
|
||||
IPasswordBreachChecker breachChecker,
|
||||
ILogger<ChangePasswordHandler> logger)
|
||||
{
|
||||
@@ -27,7 +26,7 @@ public class ChangePasswordHandler : IRequestHandler<ChangePasswordCommand, Serv
|
||||
{
|
||||
_logger.LogDebug("ChangePassword: UserId={UserId}", request.UserId);
|
||||
|
||||
var user = await _userManager.FindByIdAsync(request.UserId.ToString()).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("ChangePassword: User not found UserId={UserId}", request.UserId);
|
||||
@@ -42,12 +41,18 @@ public class ChangePasswordHandler : IRequestHandler<ChangePasswordCommand, Serv
|
||||
"This password has appeared in a data breach. Please choose a different password.");
|
||||
}
|
||||
|
||||
var result = await _userManager.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword).ConfigureAwait(false);
|
||||
var result = await _userManager.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword, ct).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
|
||||
_logger.LogError("ChangePassword: Failed UserId={UserId}: {Errors}", request.UserId, errors);
|
||||
return ServiceResult.Failure(errors);
|
||||
_logger.LogWarning("Identity rejected password change with codes {Codes}", string.Join(',', result.ErrorCodes));
|
||||
return ServiceResult.Failure("Password change failed");
|
||||
}
|
||||
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
|
||||
if (!stamp)
|
||||
{
|
||||
_logger.LogError("Identity could not revoke sessions after password change for user {UserId}", request.UserId);
|
||||
return ServiceResult.Failure("Password changed but active sessions could not be revoked", 500);
|
||||
}
|
||||
|
||||
_logger.LogInformation("ChangePassword: Success UserId={UserId}", request.UserId);
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Complete2faSetup;
|
||||
|
||||
public sealed record Complete2faSetupCommand(Guid UserId, string Code) : IRequest<ServiceResult<Complete2faSetupResponse>>;
|
||||
@@ -0,0 +1,69 @@
|
||||
using Heimdall.Application.Auth.Services;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Complete2faSetup;
|
||||
|
||||
public sealed class Complete2faSetupHandler : IRequestHandler<Complete2faSetupCommand, ServiceResult<Complete2faSetupResponse>>
|
||||
{
|
||||
private readonly IIdentityAccountService _users;
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly ILogger<Complete2faSetupHandler> _logger;
|
||||
|
||||
public Complete2faSetupHandler(IIdentityAccountService users, IApplicationDbContext db, ILogger<Complete2faSetupHandler> logger)
|
||||
{
|
||||
_users = users;
|
||||
_db = db;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<Complete2faSetupResponse>> Handle(Complete2faSetupCommand request, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.Code) || request.Code.Trim().Length != 6)
|
||||
return ServiceResult<Complete2faSetupResponse>.Failure("Invalid authenticator code", 400);
|
||||
var user = await _users.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null) return ServiceResult<Complete2faSetupResponse>.NotFound("User not found");
|
||||
if (await _users.GetTwoFactorEnabledAsync(user, ct).ConfigureAwait(false))
|
||||
return ServiceResult<Complete2faSetupResponse>.Conflict("Two-factor authentication is already enabled");
|
||||
|
||||
var valid = await _users.VerifyAuthenticatorTokenAsync(user, request.Code.Trim(), ct).ConfigureAwait(false);
|
||||
if (!valid) return ServiceResult<Complete2faSetupResponse>.Failure("Invalid authenticator code", 400);
|
||||
|
||||
var oldCodes = await _db.UserRecoveryCodes.Where(x => x.UserId == user.Id).ToListAsync(ct).ConfigureAwait(false);
|
||||
if (oldCodes.Count > 0) _db.UserRecoveryCodes.RemoveRange(oldCodes);
|
||||
var codes = RecoveryCodeService.Generate(10);
|
||||
foreach (var code in codes) _db.UserRecoveryCodes.Add(new UserRecoveryCode(user.Id, RecoveryCodeService.Hash(code)));
|
||||
|
||||
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
var result = await _users.SetTwoFactorEnabledAsync(user, true, ct).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
_logger.LogWarning("Identity rejected enabling two-factor authentication for user {UserId}", request.UserId);
|
||||
await RemoveRecoveryCodesAsync(user.Id, ct).ConfigureAwait(false);
|
||||
return ServiceResult<Complete2faSetupResponse>.Failure("Unable to enable two-factor authentication");
|
||||
}
|
||||
|
||||
var stamp = await _users.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
|
||||
if (!stamp)
|
||||
{
|
||||
await _users.SetTwoFactorEnabledAsync(user, false, ct).ConfigureAwait(false);
|
||||
await RemoveRecoveryCodesAsync(user.Id, ct).ConfigureAwait(false);
|
||||
_logger.LogError("Identity could not revoke existing sessions after enabling two-factor authentication for user {UserId}", user.Id);
|
||||
return ServiceResult<Complete2faSetupResponse>.Failure("Unable to complete two-factor setup");
|
||||
}
|
||||
return ServiceResult<Complete2faSetupResponse>.Success(new Complete2faSetupResponse(codes, codes.Count));
|
||||
}
|
||||
|
||||
private async Task RemoveRecoveryCodesAsync(Guid userId, CancellationToken ct)
|
||||
{
|
||||
var codes = await _db.UserRecoveryCodes.Where(x => x.UserId == userId).ToListAsync(ct).ConfigureAwait(false);
|
||||
if (codes.Count == 0) return;
|
||||
_db.UserRecoveryCodes.RemoveRange(codes);
|
||||
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Complete2faSetup;
|
||||
|
||||
public sealed class Complete2faSetupValidator : AbstractValidator<Complete2faSetupCommand>
|
||||
{
|
||||
public Complete2faSetupValidator() => RuleFor(x => x.Code).NotEmpty().Length(6);
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.ConfirmEmail;
|
||||
|
||||
public class ConfirmEmailHandler : IRequestHandler<ConfirmEmailCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly ILogger<ConfirmEmailHandler> _logger;
|
||||
|
||||
public ConfirmEmailHandler(UserManager<AppUser> userManager, ILogger<ConfirmEmailHandler> logger)
|
||||
public ConfirmEmailHandler(IIdentityAccountService userManager, ILogger<ConfirmEmailHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_logger = logger;
|
||||
@@ -27,7 +27,7 @@ public class ConfirmEmailHandler : IRequestHandler<ConfirmEmailCommand, ServiceR
|
||||
return ServiceResult.Failure("Invalid user ID");
|
||||
}
|
||||
|
||||
var user = await _userManager.FindByIdAsync(request.UserId).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByIdAsync(Guid.TryParse(request.UserId, out var parsedUserId) ? parsedUserId : Guid.Empty, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("ConfirmEmail: User not found UserId={UserId}", request.UserId);
|
||||
@@ -41,12 +41,11 @@ public class ConfirmEmailHandler : IRequestHandler<ConfirmEmailCommand, ServiceR
|
||||
}
|
||||
|
||||
var decodedToken = Uri.UnescapeDataString(request.Token);
|
||||
var result = await _userManager.ConfirmEmailAsync(user, decodedToken).ConfigureAwait(false);
|
||||
var result = await _userManager.ConfirmEmailAsync(user, decodedToken, ct).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
|
||||
_logger.LogWarning("ConfirmEmail: Failed UserId={UserId}: {Errors}", request.UserId, errors);
|
||||
return ServiceResult.Failure(errors);
|
||||
_logger.LogWarning("Identity rejected email confirmation with codes {Codes}", string.Join(',', result.ErrorCodes));
|
||||
return ServiceResult.Failure("Email confirmation failed");
|
||||
}
|
||||
|
||||
_logger.LogInformation("ConfirmEmail: Confirmed successfully UserId={UserId}", request.UserId);
|
||||
|
||||
@@ -3,4 +3,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Disable2fa;
|
||||
|
||||
public record Disable2faCommand(Guid UserId) : IRequest<ServiceResult>;
|
||||
public record Disable2faCommand(Guid UserId, string CurrentPassword) : IRequest<ServiceResult>;
|
||||
@@ -1,19 +1,19 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Disable2fa;
|
||||
|
||||
public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly ILogger<Disable2faHandler> _logger;
|
||||
|
||||
public Disable2faHandler(UserManager<AppUser> userManager, IApplicationDbContext db, ILogger<Disable2faHandler> logger)
|
||||
public Disable2faHandler(IIdentityAccountService userManager, IApplicationDbContext db, ILogger<Disable2faHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_db = db;
|
||||
@@ -24,20 +24,27 @@ public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResul
|
||||
{
|
||||
_logger.LogDebug("Disable2fa: UserId={UserId}", request.UserId);
|
||||
|
||||
var user = await _userManager.FindByIdAsync(request.UserId.ToString()).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("Disable2fa: User not found UserId={UserId}", request.UserId);
|
||||
return ServiceResult.NotFound("User not found");
|
||||
}
|
||||
|
||||
var result = await _userManager.SetTwoFactorEnabledAsync(user, false).ConfigureAwait(false);
|
||||
if (string.IsNullOrEmpty(request.CurrentPassword)
|
||||
|| !await _userManager.CheckPasswordAsync(user, request.CurrentPassword, ct).ConfigureAwait(false))
|
||||
return ServiceResult.Failure("Current password is incorrect", 400);
|
||||
|
||||
var result = await _userManager.SetTwoFactorEnabledAsync(user, false, ct).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
_logger.LogError("Disable2fa: Failed UserId={UserId}", request.UserId);
|
||||
return ServiceResult.Failure("Failed to disable 2FA");
|
||||
}
|
||||
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
|
||||
if (!stamp) return ServiceResult.Failure("Unable to revoke existing sessions");
|
||||
|
||||
// Purger les codes de récupération — ils ne sont plus valables
|
||||
var codes = await _db.UserRecoveryCodes
|
||||
.Where(r => r.UserId == request.UserId)
|
||||
|
||||
@@ -4,4 +4,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Enable2fa;
|
||||
|
||||
public record Enable2faCommand(Guid UserId) : IRequest<ServiceResult<Enable2faResponse>>;
|
||||
public record Enable2faCommand(Guid UserId, string CurrentPassword) : IRequest<ServiceResult<Enable2faResponse>>;
|
||||
@@ -3,19 +3,19 @@ using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Enable2fa;
|
||||
|
||||
public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<Enable2faResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly ILogger<Enable2faHandler> _logger;
|
||||
|
||||
public Enable2faHandler(UserManager<AppUser> userManager, IApplicationDbContext db, ILogger<Enable2faHandler> logger)
|
||||
public Enable2faHandler(IIdentityAccountService userManager, IApplicationDbContext db, ILogger<Enable2faHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_db = db;
|
||||
@@ -26,40 +26,34 @@ public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<
|
||||
{
|
||||
_logger.LogDebug("Enable2fa: UserId={UserId}", request.UserId);
|
||||
|
||||
var user = await _userManager.FindByIdAsync(request.UserId.ToString()).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("Enable2fa: User not found UserId={UserId}", request.UserId);
|
||||
return ServiceResult<Enable2faResponse>.NotFound("User not found");
|
||||
}
|
||||
|
||||
var result = await _userManager.SetTwoFactorEnabledAsync(user, true).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
_logger.LogError("Enable2fa: Failed UserId={UserId}", request.UserId);
|
||||
return ServiceResult<Enable2faResponse>.Failure("Failed to enable 2FA");
|
||||
}
|
||||
if (string.IsNullOrEmpty(request.CurrentPassword)
|
||||
|| !await _userManager.CheckPasswordAsync(user, request.CurrentPassword, ct).ConfigureAwait(false))
|
||||
return ServiceResult<Enable2faResponse>.Failure("Current password is incorrect", 400);
|
||||
|
||||
if (await _userManager.GetTwoFactorEnabledAsync(user, ct).ConfigureAwait(false))
|
||||
return ServiceResult<Enable2faResponse>.Conflict("Two-factor authentication is already enabled");
|
||||
|
||||
// Generate authenticator key for the QR code setup (l'utilisateur doit scanner le code avec son app)
|
||||
// Note: key is generated AFTER enabling 2FA so it's available immediately
|
||||
await _userManager.ResetAuthenticatorKeyAsync(user).ConfigureAwait(false);
|
||||
var key = await _userManager.GetAuthenticatorKeyAsync(user).ConfigureAwait(false);
|
||||
var reset = await _userManager.ResetAuthenticatorKeyAsync(user, ct).ConfigureAwait(false);
|
||||
if (!reset.Succeeded)
|
||||
return ServiceResult<Enable2faResponse>.Failure("Unable to initialize authenticator setup");
|
||||
var key = await _userManager.GetAuthenticatorKeyAsync(user, ct).ConfigureAwait(false);
|
||||
if (string.IsNullOrEmpty(key))
|
||||
{
|
||||
_logger.LogError("Enable2fa: Failed to generate authenticator key UserId={UserId}", request.UserId);
|
||||
return ServiceResult<Enable2faResponse>.Failure("Failed to generate 2FA key");
|
||||
}
|
||||
|
||||
// Générer 10 codes de récupération (P0 spec 4.3) — affichés UNE seule fois, stockés hashés
|
||||
var recoveryCodes = RecoveryCodeService.Generate(10);
|
||||
foreach (var code in recoveryCodes)
|
||||
{
|
||||
_db.UserRecoveryCodes.Add(new UserRecoveryCode(request.UserId, RecoveryCodeService.Hash(code)));
|
||||
}
|
||||
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
|
||||
var qrCodeUri = $"otpauth://totp/Heimdall:{user.Email}?secret={key}&issuer=Heimdall&algorithm=SHA1&digits=6&period=30";
|
||||
_logger.LogInformation("Enable2fa: Enabled UserId={UserId} with {Count} recovery codes", request.UserId, recoveryCodes.Count);
|
||||
return ServiceResult<Enable2faResponse>.Success(new Enable2faResponse(key, qrCodeUri, recoveryCodes, recoveryCodes.Count));
|
||||
_logger.LogInformation("Authenticator setup initialized for user {UserId}; confirmation is still required", request.UserId);
|
||||
return ServiceResult<Enable2faResponse>.Success(new Enable2faResponse(key, qrCodeUri));
|
||||
}
|
||||
}
|
||||
@@ -4,19 +4,18 @@ using Heimdall.Application.Localization;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.ForgotPassword;
|
||||
|
||||
public class ForgotPasswordHandler : IRequestHandler<ForgotPasswordCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IEmailService _emailService;
|
||||
private readonly ILogger<ForgotPasswordHandler> _logger;
|
||||
|
||||
public ForgotPasswordHandler(
|
||||
UserManager<AppUser> userManager,
|
||||
IIdentityAccountService userManager,
|
||||
IEmailService emailService,
|
||||
ILogger<ForgotPasswordHandler> logger)
|
||||
{
|
||||
@@ -27,17 +26,17 @@ public class ForgotPasswordHandler : IRequestHandler<ForgotPasswordCommand, Serv
|
||||
|
||||
public async Task<ServiceResult> Handle(ForgotPasswordCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("ForgotPassword: Email={Email}", request.Email);
|
||||
_logger.LogInformation("Password reset request received");
|
||||
|
||||
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByEmailAsync(request.Email, ct).ConfigureAwait(false);
|
||||
// Ne pas divulguer si l'email existe ou pas
|
||||
if (user is null || !await _userManager.IsEmailConfirmedAsync(user).ConfigureAwait(false))
|
||||
if (user is null || !await _userManager.IsEmailConfirmedAsync(user, ct).ConfigureAwait(false))
|
||||
{
|
||||
_logger.LogInformation("ForgotPassword: No action for Email={Email} (not found or unconfirmed)", request.Email);
|
||||
_logger.LogInformation("Password reset request completed without an eligible account");
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
var token = await _userManager.GeneratePasswordResetTokenAsync(user).ConfigureAwait(false);
|
||||
var token = await _userManager.GeneratePasswordResetTokenAsync(user, ct).ConfigureAwait(false);
|
||||
var encodedToken = Uri.EscapeDataString(token);
|
||||
|
||||
var resetLink = $"heimdall://reset-password?email={Uri.EscapeDataString(request.Email)}&token={encodedToken}";
|
||||
@@ -54,7 +53,7 @@ public class ForgotPasswordHandler : IRequestHandler<ForgotPasswordCommand, Serv
|
||||
await _emailService.SendEmailAsync(request.Email,
|
||||
ServerText.Get("Auth.ForgotPassword.Subject", language), body, ct).ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation("ForgotPassword: Reset link sent to Email={Email}", request.Email);
|
||||
_logger.LogInformation("Password reset message sent");
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,13 @@ using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Login;
|
||||
|
||||
public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IAuthSignInService _signInService;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
@@ -22,7 +21,7 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
|
||||
private readonly ILogger<LoginHandler> _logger;
|
||||
|
||||
public LoginHandler(
|
||||
UserManager<AppUser> userManager,
|
||||
IIdentityAccountService userManager,
|
||||
IAuthSignInService signInService,
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
@@ -43,30 +42,30 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> Handle(LoginCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Login attempt: Email={Email}", request.Email);
|
||||
_logger.LogInformation("Login attempt received");
|
||||
|
||||
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByEmailAsync(request.Email, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("Login: User not found Email={Email}", request.Email);
|
||||
await _userRepository.AddAuditLogAsync(null, "LoginFailed", "User", request.Email, null, "User not found", ct).ConfigureAwait(false);
|
||||
_logger.LogWarning("Login rejected: account unavailable");
|
||||
await _userRepository.AddAuditLogAsync(null, "LoginFailed", "User", null, null, "Authentication failed", ct).ConfigureAwait(false);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
}
|
||||
|
||||
if (await _userManager.IsLockedOutAsync(user))
|
||||
if (await _userManager.IsLockedOutAsync(user, ct))
|
||||
{
|
||||
_logger.LogWarning("Login: Account locked Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
|
||||
_logger.LogWarning("Login rejected: account unavailable");
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
}
|
||||
|
||||
var result = await _signInService.PasswordSignInAsync(user, request.Password, true).ConfigureAwait(false);
|
||||
var twoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
|
||||
var twoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user, ct);
|
||||
if (result.ResultType == SignInResultType.LockedOut)
|
||||
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
if (result.ResultType != SignInResultType.Success
|
||||
&& !(result.ResultType == SignInResultType.RequiresTwoFactor && twoFactorEnabled))
|
||||
{
|
||||
_logger.LogWarning("Login: Password mismatch Email={Email}", request.Email);
|
||||
_logger.LogWarning("Login rejected: credentials invalid");
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
}
|
||||
|
||||
@@ -74,8 +73,8 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
|
||||
var emailConfirmRequired = await _authData.GetSettingValueAsync("email.confirmation.required", ct).ConfigureAwait(false);
|
||||
if (string.Equals(emailConfirmRequired, "true", StringComparison.OrdinalIgnoreCase) && !user.EmailConfirmed)
|
||||
{
|
||||
_logger.LogWarning("Login: Email not confirmed Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Failure("Email not confirmed. Check your inbox for the confirmation link.", 403);
|
||||
_logger.LogWarning("Login rejected: account does not meet current sign-in policy");
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
}
|
||||
|
||||
if (twoFactorEnabled)
|
||||
@@ -83,10 +82,10 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
|
||||
var challengeId = await LoginChallengeService.CreateAsync(_db, user, ct);
|
||||
return ServiceResult<AuthResponse>.Success(new AuthResponse(
|
||||
string.Empty, string.Empty, DateTime.UtcNow, true,
|
||||
await AuthHelper.MapUserInfoAsync(user, _userManager), challengeId));
|
||||
await AuthHelper.MapUserInfoAsync(user, _userManager, _rolePermissionService, ct), challengeId));
|
||||
}
|
||||
|
||||
_logger.LogInformation("Login: Success Email={Email}", request.Email);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
|
||||
_logger.LogInformation("Login succeeded");
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
@@ -15,14 +14,14 @@ namespace Heimdall.Application.Auth.Commands.RefreshToken;
|
||||
public class RefreshTokenHandler : IRequestHandler<RefreshTokenCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly IAuthDataService _authData;
|
||||
private readonly ILogger<RefreshTokenHandler> _logger;
|
||||
|
||||
public RefreshTokenHandler(
|
||||
IJwtService jwtService,
|
||||
UserManager<AppUser> userManager,
|
||||
IIdentityAccountService userManager,
|
||||
IRolePermissionService rolePermissionService,
|
||||
IAuthDataService authData,
|
||||
ILogger<RefreshTokenHandler> logger)
|
||||
@@ -61,7 +60,9 @@ public class RefreshTokenHandler : IRequestHandler<RefreshTokenCommand, ServiceR
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid token");
|
||||
}
|
||||
|
||||
var user = await _userManager.FindByIdAsync(userId).ConfigureAwait(false);
|
||||
if (!Guid.TryParse(userId, out var parsedUserId))
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid token");
|
||||
var user = await _userManager.FindByIdAsync(parsedUserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("RefreshToken: User not found UserId={UserId}", userId);
|
||||
@@ -86,6 +87,6 @@ public class RefreshTokenHandler : IRequestHandler<RefreshTokenCommand, ServiceR
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Refresh token already consumed");
|
||||
}
|
||||
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, started).ConfigureAwait(false);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, started, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.RegisterAdmin;
|
||||
|
||||
public record RegisterAdminCommand(string Email, string Password, string DisplayName) : IRequest<ServiceResult<AuthResponse>>;
|
||||
@@ -1,86 +0,0 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Heimdall.Application.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.RegisterAdmin;
|
||||
|
||||
public class RegisterAdminHandler : IRequestHandler<RegisterAdminCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly IAuthDataService _authData;
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly IPasswordBreachChecker _breachChecker;
|
||||
private readonly ILogger<RegisterAdminHandler> _logger;
|
||||
|
||||
public RegisterAdminHandler(
|
||||
IAuthDataService authData,
|
||||
UserManager<AppUser> userManager,
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
IPasswordBreachChecker breachChecker,
|
||||
ILogger<RegisterAdminHandler> logger)
|
||||
{
|
||||
_authData = authData;
|
||||
_userManager = userManager;
|
||||
_jwtService = jwtService;
|
||||
_rolePermissionService = rolePermissionService;
|
||||
_breachChecker = breachChecker;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> Handle(RegisterAdminCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("RegisterAdmin: Email={Email}, DisplayName={DisplayName}", request.Email, request.DisplayName);
|
||||
|
||||
// Vérifier le feature flag auth.admin-registration.enabled
|
||||
var flag = await _authData.GetSettingValueAsync("auth.admin-registration.enabled", ct).ConfigureAwait(false);
|
||||
if (!string.Equals(flag, "true", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_logger.LogWarning("RegisterAdmin: Disabled by feature flag Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Failure("Admin registration is disabled", 403);
|
||||
}
|
||||
|
||||
var existing = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
|
||||
if (existing is not null)
|
||||
{
|
||||
_logger.LogWarning("RegisterAdmin: Already exists Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Conflict("Email already registered");
|
||||
}
|
||||
|
||||
// HaveIBeenPwned check (spec §4.3)
|
||||
if (await _breachChecker.IsPasswordBreachedAsync(request.Password, ct).ConfigureAwait(false))
|
||||
{
|
||||
_logger.LogWarning("RegisterAdmin: password has been breached (HIBP) for Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Failure(
|
||||
"This password has appeared in a data breach. Please choose a different password.");
|
||||
}
|
||||
|
||||
var user = new AppUser
|
||||
{
|
||||
UserName = request.Email,
|
||||
Email = request.Email,
|
||||
DisplayName = request.DisplayName
|
||||
};
|
||||
|
||||
var createResult = await _userManager.CreateAsync(user, request.Password).ConfigureAwait(false);
|
||||
if (!createResult.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", createResult.Errors.Select(e => e.Description));
|
||||
_logger.LogWarning("RegisterAdmin: Creation failed: {Errors}", errors);
|
||||
return ServiceResult<AuthResponse>.Failure(errors);
|
||||
}
|
||||
|
||||
// Assign Admin role
|
||||
await _userManager.AddToRoleAsync(user, "Admin").ConfigureAwait(false);
|
||||
user.EmailConfirmed = true;
|
||||
await _userManager.UpdateAsync(user).ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation("RegisterAdmin: Admin user created Email={Email}", request.Email);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.RegisterAdmin;
|
||||
|
||||
public class RegisterAdminValidator : AbstractValidator<RegisterAdminCommand>
|
||||
{
|
||||
public RegisterAdminValidator()
|
||||
{
|
||||
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(256);
|
||||
RuleFor(x => x.DisplayName).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.Password).NotEmpty().MinimumLength(12)
|
||||
.WithMessage("Password must be at least 12 characters");
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.ResetPassword;
|
||||
|
||||
public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly ILogger<ResetPasswordHandler> _logger;
|
||||
|
||||
public ResetPasswordHandler(UserManager<AppUser> userManager, ILogger<ResetPasswordHandler> logger)
|
||||
public ResetPasswordHandler(IIdentityAccountService userManager, ILogger<ResetPasswordHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_logger = logger;
|
||||
@@ -19,25 +19,31 @@ public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, Servic
|
||||
|
||||
public async Task<ServiceResult> Handle(ResetPasswordCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("ResetPassword: Email={Email}", request.Email);
|
||||
_logger.LogInformation("Password reset completion requested");
|
||||
|
||||
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByEmailAsync(request.Email, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("ResetPassword: User not found Email={Email}", request.Email);
|
||||
return ServiceResult.NotFound("User not found");
|
||||
_logger.LogWarning("Password reset completion rejected");
|
||||
return ServiceResult.Failure("Invalid or expired reset request", 400);
|
||||
}
|
||||
|
||||
var decodedToken = Uri.UnescapeDataString(request.Token);
|
||||
var result = await _userManager.ResetPasswordAsync(user, decodedToken, request.NewPassword).ConfigureAwait(false);
|
||||
var result = await _userManager.ResetPasswordAsync(user, decodedToken, request.NewPassword, ct).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
|
||||
_logger.LogWarning("ResetPassword: Failed Email={Email}: {Errors}", request.Email, errors);
|
||||
return ServiceResult.Failure(errors);
|
||||
_logger.LogWarning("Identity rejected password reset with codes {Codes}", string.Join(',', result.ErrorCodes));
|
||||
return ServiceResult.Failure("Invalid or expired reset request", 400);
|
||||
}
|
||||
|
||||
_logger.LogInformation("ResetPassword: Success Email={Email}", request.Email);
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
|
||||
if (!stamp)
|
||||
{
|
||||
_logger.LogError("Identity could not revoke sessions after password reset");
|
||||
return ServiceResult.Failure("Password reset failed", 500);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Password reset completed successfully");
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
@@ -12,14 +11,14 @@ namespace Heimdall.Application.Auth.Commands.Verify2fa;
|
||||
|
||||
public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly ILogger<Verify2faHandler> _logger;
|
||||
|
||||
public Verify2faHandler(
|
||||
UserManager<AppUser> userManager,
|
||||
IIdentityAccountService userManager,
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
IApplicationDbContext db,
|
||||
@@ -38,43 +37,62 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
|
||||
if (challenge is null)
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid or expired challenge");
|
||||
|
||||
var user = await _userManager.FindByIdAsync(challenge.UserId.ToString());
|
||||
var user = await _userManager.FindByIdAsync(challenge.UserId, ct);
|
||||
var emailSetting = await _db.AppSettings.AsNoTracking()
|
||||
.Where(x => x.Key == "email.confirmation.required").Select(x => x.Value).SingleOrDefaultAsync(ct);
|
||||
var emailRequired = string.Equals(emailSetting, "true", StringComparison.OrdinalIgnoreCase);
|
||||
if (user is null || user.SecurityStamp != challenge.SecurityStamp
|
||||
|| !await _userManager.GetTwoFactorEnabledAsync(user)
|
||||
|| await _userManager.IsLockedOutAsync(user)
|
||||
|| !await _userManager.GetTwoFactorEnabledAsync(user, ct)
|
||||
|| await _userManager.IsLockedOutAsync(user, ct)
|
||||
|| (emailRequired && !user.EmailConfirmed))
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Account unavailable");
|
||||
|
||||
var isValid = await _userManager.VerifyTwoFactorTokenAsync(
|
||||
user, TokenOptions.DefaultAuthenticatorProvider, request.Code);
|
||||
var isValid = await _userManager.VerifyAuthenticatorTokenAsync(user, request.Code, ct).ConfigureAwait(false);
|
||||
|
||||
if (!isValid)
|
||||
{
|
||||
// TOTP invalide → tenter un code de récupération (usage unique)
|
||||
var redeemed = await TryRedeemRecoveryCodeAsync(user, request.Code.Trim(), ct).ConfigureAwait(false);
|
||||
var recoveryCode = request.Code.Trim();
|
||||
var redeemed = await TryRedeemRecoveryCodeAsync(user, recoveryCode, ct).ConfigureAwait(false);
|
||||
if (!redeemed)
|
||||
{
|
||||
// A parallel verifier may have atomically redeemed this exact code while
|
||||
// this request waited on the database row lock. Do not race an access-failure
|
||||
// update against the winner's security-stamp rotation.
|
||||
var alreadyRedeemed = !string.IsNullOrWhiteSpace(recoveryCode)
|
||||
&& await _db.UserRecoveryCodes.AnyAsync(r => r.UserId == user.Id
|
||||
&& r.CodeHash == RecoveryCodeService.Hash(recoveryCode) && r.UsedAt != null, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (alreadyRedeemed)
|
||||
{
|
||||
await LoginChallengeService.ReleaseAttemptAsync(_db, challenge, ct).ConfigureAwait(false);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
|
||||
}
|
||||
|
||||
_logger.LogWarning("Verify2fa: Invalid code UserId={UserId}", challenge.UserId);
|
||||
await _userManager.AccessFailedAsync(user);
|
||||
if (await _userManager.IsLockedOutAsync(user))
|
||||
await _userManager.UpdateSecurityStampAsync(user);
|
||||
await _userManager.AccessFailedAsync(user, ct);
|
||||
if (await _userManager.IsLockedOutAsync(user, ct))
|
||||
await _userManager.UpdateSecurityStampAsync(user, ct);
|
||||
await LoginChallengeService.ReleaseAttemptAsync(_db, challenge, ct);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
|
||||
}
|
||||
var stampUpdate = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
|
||||
if (!stampUpdate)
|
||||
{
|
||||
_logger.LogError("Unable to rotate security stamp after recovery code use for user {UserId}", user.Id);
|
||||
return ServiceResult<AuthResponse>.Failure("Unable to complete sign-in");
|
||||
}
|
||||
_logger.LogInformation("Verify2fa: Recovery code redeemed UserId={UserId}", challenge.UserId);
|
||||
}
|
||||
|
||||
if (await LoginChallengeService.ConsumeAsync(_db, challenge, ct) != 1)
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Challenge already used");
|
||||
await _userManager.ResetAccessFailedCountAsync(user);
|
||||
await _userManager.ResetAccessFailedCountAsync(user, ct);
|
||||
_logger.LogInformation("Verify2fa: Success UserId={UserId}", challenge.UserId);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<bool> TryRedeemRecoveryCodeAsync(AppUser user, string code, CancellationToken ct)
|
||||
private async Task<bool> TryRedeemRecoveryCodeAsync(IdentityAccount user, string code, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(code))
|
||||
return false;
|
||||
|
||||
@@ -3,6 +3,7 @@ using Heimdall.Application.Auth.Commands.Login;
|
||||
using Heimdall.Application.Auth.Commands.Register;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Auth.Mapping;
|
||||
|
||||
@@ -10,7 +11,7 @@ public class AuthMappingProfile : Profile
|
||||
{
|
||||
public AuthMappingProfile()
|
||||
{
|
||||
CreateMap<AppUser, UserInfo>()
|
||||
CreateMap<IdentityAccount, UserInfo>()
|
||||
.ForMember(d => d.Email, o => o.MapFrom(s => s.Email ?? string.Empty))
|
||||
.ForMember(d => d.Roles, o => o.Ignore());
|
||||
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
using System.Security.Claims;
|
||||
using System.Globalization;
|
||||
using Heimdall.Application.Services;
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Heimdall.Application.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.Auth.Services;
|
||||
@@ -13,40 +11,35 @@ public static class AccountSessionPolicy
|
||||
public const string StampClaim = "security_stamp";
|
||||
public const string StartedClaim = "session_started";
|
||||
|
||||
public static async Task<bool> IsValidAsync(ClaimsPrincipal principal, UserManager<AppUser> users, IAuthDataService data, CancellationToken ct)
|
||||
public static async Task<bool> IsValidAsync(ClaimsPrincipal principal, IIdentityAccountService users, IAuthDataService data, CancellationToken ct)
|
||||
{
|
||||
if (!DateTime.TryParse(principal.FindFirstValue(StartedClaim), CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.RoundtripKind, out var started) || started > DateTime.UtcNow || started.AddDays(7) <= DateTime.UtcNow)
|
||||
return false;
|
||||
var id = principal.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
var user = id is null ? null : await users.FindByIdAsync(id);
|
||||
if (!TryReadStarted(principal, out _)) return false;
|
||||
if (!Guid.TryParse(principal.FindFirstValue(ClaimTypes.NameIdentifier), out var userId)) return false;
|
||||
var user = await users.FindByIdAsync(userId, ct).ConfigureAwait(false);
|
||||
if (user is null || string.IsNullOrEmpty(user.SecurityStamp)
|
||||
|| principal.FindFirstValue(StampClaim) != user.SecurityStamp
|
||||
|| await users.IsLockedOutAsync(user)) return false;
|
||||
var required = await data.GetSettingValueAsync("email.confirmation.required", ct);
|
||||
if (string.Equals(required, "true", StringComparison.OrdinalIgnoreCase) && !user.EmailConfirmed) return false;
|
||||
return true;
|
||||
|| await users.IsLockedOutAsync(user, ct).ConfigureAwait(false)) return false;
|
||||
var required = await data.GetSettingValueAsync("email.confirmation.required", ct).ConfigureAwait(false);
|
||||
return !string.Equals(required, "true", StringComparison.OrdinalIgnoreCase) || user.EmailConfirmed;
|
||||
}
|
||||
|
||||
/// <summary>Validates a live connection against persisted values without using Identity's tracked user cache.</summary>
|
||||
public static async Task<bool> IsValidLiveAsync(ClaimsPrincipal principal, IApplicationDbContext db, CancellationToken ct)
|
||||
/// <summary>Checks session state from a fresh persisted projection, bypassing Identity's tracked user cache.</summary>
|
||||
public static async Task<bool> IsValidLiveAsync(ClaimsPrincipal principal, IIdentityAccountService users, IApplicationDbContext db, CancellationToken ct)
|
||||
{
|
||||
if (!DateTime.TryParse(principal.FindFirstValue(StartedClaim), CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.RoundtripKind, out var started) || started > DateTime.UtcNow || started.AddDays(7) <= DateTime.UtcNow)
|
||||
return false;
|
||||
var id = principal.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (!Guid.TryParse(id, out var userId)) return false;
|
||||
|
||||
var user = await db.Users.AsNoTracking().Where(u => u.Id == userId)
|
||||
.Select(u => new { u.SecurityStamp, u.LockoutEnabled, u.LockoutEnd, u.EmailConfirmed })
|
||||
.SingleOrDefaultAsync(ct);
|
||||
if (!TryReadStarted(principal, out _)) return false;
|
||||
if (!Guid.TryParse(principal.FindFirstValue(ClaimTypes.NameIdentifier), out var userId)) return false;
|
||||
var user = await users.GetSessionRecordAsync(userId, ct).ConfigureAwait(false);
|
||||
if (user is null || string.IsNullOrEmpty(user.SecurityStamp)
|
||||
|| principal.FindFirstValue(StampClaim) != user.SecurityStamp
|
||||
|| (user.LockoutEnabled && user.LockoutEnd > DateTimeOffset.UtcNow)) return false;
|
||||
|
||||
var confirmationRequired = await db.AppSettings.AsNoTracking()
|
||||
.Where(s => s.Key == "email.confirmation.required")
|
||||
.Select(s => s.Value).SingleOrDefaultAsync(ct);
|
||||
return !string.Equals(confirmationRequired, "true", StringComparison.OrdinalIgnoreCase) || user.EmailConfirmed;
|
||||
var required = await db.AppSettings.AsNoTracking().Where(setting => setting.Key == "email.confirmation.required")
|
||||
.Select(setting => setting.Value).SingleOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
return !string.Equals(required, "true", StringComparison.OrdinalIgnoreCase) || user.EmailConfirmed;
|
||||
}
|
||||
|
||||
private static bool TryReadStarted(ClaimsPrincipal principal, out DateTime started)
|
||||
=> DateTime.TryParse(principal.FindFirstValue(StartedClaim), CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.RoundtripKind, out started)
|
||||
&& started <= DateTime.UtcNow && started.AddDays(7) > DateTime.UtcNow;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Heimdall.Application.Auth.Services;
|
||||
|
||||
internal static class ClaimsPrincipalExtensions
|
||||
{
|
||||
internal static string? FindFirstValue(this ClaimsPrincipal principal, string claimType)
|
||||
=> principal.FindFirst(claimType)?.Value;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using System.Text;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Auth.Services;
|
||||
|
||||
@@ -10,7 +11,7 @@ public static class LoginChallengeService
|
||||
{
|
||||
public static string Hash(string token) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
|
||||
|
||||
public static async Task<string> CreateAsync(IApplicationDbContext db, AppUser user, CancellationToken ct)
|
||||
public static async Task<string> CreateAsync(IApplicationDbContext db, IdentityAccount user, CancellationToken ct)
|
||||
{
|
||||
var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
|
||||
db.GetSet<LoginChallenge>().Add(new LoginChallenge
|
||||
|
||||
@@ -12,7 +12,6 @@ public interface IApplicationDbContext
|
||||
DbSet<AnalysisJob> AnalysisJobs { get; }
|
||||
DbSet<ApiKey> ApiKeys { get; }
|
||||
DbSet<AppSetting> AppSettings { get; }
|
||||
DbSet<AppUser> Users { get; }
|
||||
DbSet<AuditLog> AuditLogs { get; }
|
||||
DbSet<Camera> Cameras { get; }
|
||||
DbSet<CameraAssignment> CameraAssignments { get; }
|
||||
@@ -46,10 +45,6 @@ public interface IApplicationDbContext
|
||||
DbSet<Vehicle> Vehicles { get; }
|
||||
DbSet<GroupCameraAccess> GroupCameraAccesses { get; }
|
||||
|
||||
// Identity tables (for synchronous admin checks in IQueryable filters)
|
||||
DbSet<AppRole> Roles { get; }
|
||||
DbSet<Microsoft.AspNetCore.Identity.IdentityUserRole<Guid>> UserRoles { get; }
|
||||
|
||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
|
||||
Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default);
|
||||
|
||||
|
||||
@@ -10,4 +10,10 @@ public interface IUserRepository
|
||||
Task AddAuditLogAsync(Guid? userId, string action, string resourceType, string? resourceId, string? oldValue, string? newValue, CancellationToken ct);
|
||||
Task SetUserSitesAsync(Guid userId, IList<Guid> siteIds, CancellationToken ct);
|
||||
Task RemoveUserDataAsync(Guid userId, CancellationToken ct);
|
||||
Task<bool> ExistsAsync(Guid userId, CancellationToken ct);
|
||||
Task<int> CountUsersAsync(CancellationToken ct);
|
||||
Task<IReadOnlyDictionary<Guid, string>> GetLanguagesAsync(IReadOnlyCollection<Guid> userIds, CancellationToken ct);
|
||||
Task<IReadOnlyDictionary<Guid, string?>> GetEmailsAsync(IReadOnlyCollection<Guid> userIds, CancellationToken ct);
|
||||
Task<IReadOnlyList<GroupMemberResponse>> GetGroupMembersAsync(Guid groupId, CancellationToken ct);
|
||||
Task<bool> IsAdminAsync(Guid userId, CancellationToken ct);
|
||||
}
|
||||
@@ -20,7 +20,8 @@ public record UserInfo(
|
||||
Guid Id,
|
||||
string Email,
|
||||
string DisplayName,
|
||||
IList<string> Roles);
|
||||
IList<string> Roles,
|
||||
IList<string>? Permissions = null);
|
||||
|
||||
public record ApiKeyResponse(
|
||||
Guid Id,
|
||||
@@ -44,9 +45,15 @@ public record LogoutRequest(string RefreshToken);
|
||||
|
||||
public record Enable2faResponse(
|
||||
string SharedKey,
|
||||
string QrCodeUri,
|
||||
IReadOnlyList<string>? RecoveryCodes = null,
|
||||
int RecoveryCodesRemaining = 0);
|
||||
string QrCodeUri);
|
||||
|
||||
public record Complete2faSetupRequest(string Code);
|
||||
|
||||
public record Complete2faSetupResponse(IReadOnlyList<string> RecoveryCodes, int RecoveryCodesRemaining);
|
||||
|
||||
public record Disable2faRequest(string CurrentPassword);
|
||||
|
||||
public record Enable2faRequest(string CurrentPassword);
|
||||
|
||||
public record ConfirmEmailRequest(string UserId, string Token);
|
||||
public record ForgotPasswordRequest(string Email);
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.Localization;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Enums;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.Events.Notifications;
|
||||
|
||||
@@ -12,26 +11,18 @@ public class EventCreatedNotificationHandler : INotificationHandler<EventCreated
|
||||
private readonly IEventBroadcastService _broadcast;
|
||||
private readonly ICameraAccessService _cameraAccess;
|
||||
private readonly INotificationService _notifications;
|
||||
private readonly IApplicationDbContext? _context;
|
||||
|
||||
public EventCreatedNotificationHandler(
|
||||
IEventBroadcastService broadcast,
|
||||
ICameraAccessService cameraAccess,
|
||||
INotificationService notifications)
|
||||
: this(broadcast, cameraAccess, notifications, null)
|
||||
{
|
||||
}
|
||||
private readonly IUserRepository? _users;
|
||||
|
||||
public EventCreatedNotificationHandler(
|
||||
IEventBroadcastService broadcast,
|
||||
ICameraAccessService cameraAccess,
|
||||
INotificationService notifications,
|
||||
IApplicationDbContext? context)
|
||||
IUserRepository? users = null)
|
||||
{
|
||||
_broadcast = broadcast;
|
||||
_cameraAccess = cameraAccess;
|
||||
_notifications = notifications;
|
||||
_context = context;
|
||||
_users = users;
|
||||
}
|
||||
|
||||
public async Task Handle(EventCreatedNotification notification, CancellationToken ct)
|
||||
@@ -43,13 +34,9 @@ public class EventCreatedNotificationHandler : INotificationHandler<EventCreated
|
||||
var recipients = await _cameraAccess.GetUserIdsWithCameraAccessAsync(cameraEvent.CameraId, ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var languages = _context is null || recipients.Count == 0
|
||||
var languages = _users is null || recipients.Count == 0
|
||||
? new Dictionary<Guid, string>()
|
||||
: await _context.Users.AsNoTracking()
|
||||
.Where(user => recipients.Contains(user.Id))
|
||||
.Select(user => new { user.Id, user.Language })
|
||||
.ToDictionaryAsync(user => user.Id, user => user.Language, ct)
|
||||
.ConfigureAwait(false);
|
||||
: new Dictionary<Guid, string>(await _users.GetLanguagesAsync(recipients, ct).ConfigureAwait(false));
|
||||
|
||||
var titleKey = cameraEvent.Type switch
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@ using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Text.Json;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Groups.Commands.AddUserToGroup;
|
||||
|
||||
@@ -11,8 +12,9 @@ public record AddUserToGroupCommand(Guid GroupId, Guid UserId, Guid? ActorId = n
|
||||
public class AddUserToGroupCommandHandler : IRequestHandler<AddUserToGroupCommand, ServiceResult>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly IIdentityAccountService _identity;
|
||||
|
||||
public AddUserToGroupCommandHandler(IApplicationDbContext db) => _db = db;
|
||||
public AddUserToGroupCommandHandler(IApplicationDbContext db, IIdentityAccountService identity) => (_db, _identity) = (db, identity);
|
||||
|
||||
public async Task<ServiceResult> Handle(AddUserToGroupCommand request, CancellationToken ct)
|
||||
{
|
||||
@@ -20,7 +22,7 @@ public class AddUserToGroupCommandHandler : IRequestHandler<AddUserToGroupComman
|
||||
if (group is null)
|
||||
return ServiceResult.NotFound("Group not found");
|
||||
|
||||
var user = await _db.Users.FindAsync([request.UserId], ct).ConfigureAwait(false);
|
||||
var user = await _identity.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
|
||||
@@ -11,8 +11,5 @@ public class GroupMappingProfile : Profile
|
||||
CreateMap<Group, GroupResponse>()
|
||||
.ForMember(d => d.UserCount, o => o.MapFrom(s => s.UserGroups.Count));
|
||||
|
||||
CreateMap<UserGroup, GroupMemberResponse>()
|
||||
.ForMember(d => d.Email, o => o.MapFrom(s => s.User.Email ?? string.Empty))
|
||||
.ForMember(d => d.DisplayName, o => o.MapFrom(s => s.User.DisplayName));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
@@ -11,8 +12,9 @@ public class GetGroupMembersQueryHandler
|
||||
: IRequestHandler<GetGroupMembersQuery, ServiceResult<IReadOnlyList<GroupMemberResponse>>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly IUserRepository _users;
|
||||
|
||||
public GetGroupMembersQueryHandler(IApplicationDbContext db) => _db = db;
|
||||
public GetGroupMembersQueryHandler(IApplicationDbContext db, IUserRepository users) => (_db, _users) = (db, users);
|
||||
|
||||
public async Task<ServiceResult<IReadOnlyList<GroupMemberResponse>>> Handle(
|
||||
GetGroupMembersQuery request, CancellationToken ct)
|
||||
@@ -21,14 +23,7 @@ public class GetGroupMembersQueryHandler
|
||||
if (!groupExists)
|
||||
return ServiceResult<IReadOnlyList<GroupMemberResponse>>.NotFound("Group not found");
|
||||
|
||||
var members = await _db.UserGroups.AsNoTracking()
|
||||
.Where(ug => ug.GroupId == request.GroupId)
|
||||
.Join(_db.Users.AsNoTracking(),
|
||||
ug => ug.UserId,
|
||||
u => u.Id,
|
||||
(ug, u) => new GroupMemberResponse(u.Id, u.Email ?? string.Empty, u.DisplayName))
|
||||
.OrderBy(m => m.DisplayName)
|
||||
.ToListAsync(ct);
|
||||
var members = await _users.GetGroupMembersAsync(request.GroupId, ct).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<IReadOnlyList<GroupMemberResponse>>.Success(members);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Heimdall.Domain\Heimdall.Domain.csproj" />
|
||||
@@ -9,7 +9,6 @@
|
||||
<PackageReference Include="FluentValidation" Version="11.11.0" />
|
||||
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.11.0" />
|
||||
<PackageReference Include="MediatR" Version="12.5.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.13" />
|
||||
<!-- Use the same patched native SQLite bundle for server, agent and tests. -->
|
||||
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.13" />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
@@ -14,6 +15,6 @@ public record SignInServiceResult(SignInResultType ResultType);
|
||||
|
||||
public interface IAuthSignInService
|
||||
{
|
||||
Task<SignInServiceResult> PasswordSignInAsync(AppUser user, string password, bool lockoutOnFailure);
|
||||
Task<SignInServiceResult> PasswordSignInAsync(IdentityAccount user, string password, bool lockoutOnFailure);
|
||||
Task SignOutAsync();
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Heimdall.Application.Common;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
/// <summary>Application-facing account data. ASP.NET Core Identity types stay in Infrastructure.</summary>
|
||||
public sealed class IdentityAccount
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string? UserName { get; set; }
|
||||
public string? Email { get; set; }
|
||||
public string DisplayName { get; set; } = string.Empty;
|
||||
public string? Theme { get; set; } = "Auto";
|
||||
public string Language { get; set; } = "fr";
|
||||
public DateTime CreatedAt { get; init; }
|
||||
public bool MustChangePassword { get; set; }
|
||||
public bool EmailConfirmed { get; set; }
|
||||
public bool LockoutEnabled { get; set; }
|
||||
public DateTimeOffset? LockoutEnd { get; set; }
|
||||
public int AccessFailedCount { get; set; }
|
||||
public bool TwoFactorEnabled { get; set; }
|
||||
public string? SecurityStamp { get; set; }
|
||||
}
|
||||
|
||||
public sealed record IdentityOperationResult(bool Succeeded, IReadOnlyList<string> ErrorCodes)
|
||||
{
|
||||
public static IdentityOperationResult Success { get; } = new(true, []);
|
||||
}
|
||||
|
||||
public sealed record UserSessionRecord(string? SecurityStamp, bool LockoutEnabled, DateTimeOffset? LockoutEnd, bool EmailConfirmed);
|
||||
|
||||
|
||||
public interface IIdentityAccountService
|
||||
{
|
||||
Task<IdentityAccount?> FindByIdAsync(Guid userId, CancellationToken ct = default);
|
||||
Task<IdentityAccount?> FindByEmailAsync(string email, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> CreateAsync(IdentityAccount account, string password, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> DeleteAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> UpdateAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<IList<string>> GetRolesAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<bool> IsInRoleAsync(Guid userId, string role, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> AddToRoleAsync(IdentityAccount account, string role, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> AddToRolesAsync(IdentityAccount account, IEnumerable<string> roles, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> RemoveFromRolesAsync(IdentityAccount account, IEnumerable<string> roles, CancellationToken ct = default);
|
||||
Task<bool> CheckPasswordAsync(IdentityAccount account, string password, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> ChangePasswordAsync(IdentityAccount account, string currentPassword, string newPassword, CancellationToken ct = default);
|
||||
Task<string> GeneratePasswordResetTokenAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> ResetPasswordAsync(IdentityAccount account, string token, string password, CancellationToken ct = default);
|
||||
Task<string> GenerateEmailConfirmationTokenAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> ConfirmEmailAsync(IdentityAccount account, string token, CancellationToken ct = default);
|
||||
Task<bool> IsEmailConfirmedAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<bool> IsLockedOutAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> SetLockoutEndDateAsync(IdentityAccount account, DateTimeOffset? lockoutEnd, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> ResetAccessFailedCountAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> AccessFailedAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<bool> GetTwoFactorEnabledAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> SetTwoFactorEnabledAsync(IdentityAccount account, bool enabled, CancellationToken ct = default);
|
||||
Task<IdentityOperationResult> ResetAuthenticatorKeyAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<string?> GetAuthenticatorKeyAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<bool> UpdateSecurityStampAsync(IdentityAccount account, CancellationToken ct = default);
|
||||
Task<bool> VerifyAuthenticatorTokenAsync(IdentityAccount account, string token, CancellationToken ct = default);
|
||||
Task<UserSessionRecord?> GetSessionRecordAsync(Guid userId, CancellationToken ct = default);
|
||||
}
|
||||
@@ -1,14 +1,15 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public interface IJwtService
|
||||
{
|
||||
(string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions);
|
||||
(string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions, DateTime sessionStarted) => GenerateAccessToken(user, roles, permissions);
|
||||
(string token, DateTime expiresAt) GenerateRefreshToken(AppUser user);
|
||||
(string token, DateTime expiresAt) GenerateRefreshToken(AppUser user, DateTime sessionStarted) => GenerateRefreshToken(user);
|
||||
(string token, DateTime expiresAt) GenerateAccessToken(IdentityAccount user, IList<string> roles, IList<string> permissions);
|
||||
(string token, DateTime expiresAt) GenerateAccessToken(IdentityAccount user, IList<string> roles, IList<string> permissions, DateTime sessionStarted) => GenerateAccessToken(user, roles, permissions);
|
||||
(string token, DateTime expiresAt) GenerateRefreshToken(IdentityAccount user);
|
||||
(string token, DateTime expiresAt) GenerateRefreshToken(IdentityAccount user, DateTime sessionStarted) => GenerateRefreshToken(user);
|
||||
ClaimsPrincipal? ValidateRefreshToken(string refreshToken);
|
||||
string? GetUserIdFromExpiredToken(string token);
|
||||
}
|
||||
@@ -1,6 +1,14 @@
|
||||
using Heimdall.Application.Common;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public interface IRolePermissionService
|
||||
{
|
||||
IList<string> GetPermissionsForRoles(IList<string> roles);
|
||||
Task<IList<string>> GetPermissionsForRolesAsync(IList<string> roles, CancellationToken ct);
|
||||
Task<IReadOnlyList<RolePermissionInfo>> GetAllAsync(CancellationToken ct);
|
||||
Task<ServiceResult> SetPermissionsAsync(string role, IReadOnlyCollection<string> permissions,
|
||||
Guid actorId, CancellationToken ct);
|
||||
Task EnsureDefaultsAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed record RolePermissionInfo(string Name, IReadOnlyList<string> Permissions);
|
||||
@@ -1,5 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Domain.Enums;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -11,8 +12,9 @@ public record GetStatsQuery : IRequest<ServiceResult<StatsResponse>>;
|
||||
public class GetStatsQueryHandler : IRequestHandler<GetStatsQuery, ServiceResult<StatsResponse>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly IUserRepository _users;
|
||||
|
||||
public GetStatsQueryHandler(IApplicationDbContext db) => _db = db;
|
||||
public GetStatsQueryHandler(IApplicationDbContext db, IUserRepository users) => (_db, _users) = (db, users);
|
||||
|
||||
public async Task<ServiceResult<StatsResponse>> Handle(GetStatsQuery request, CancellationToken ct)
|
||||
{
|
||||
@@ -23,7 +25,7 @@ public class GetStatsQueryHandler : IRequestHandler<GetStatsQuery, ServiceResult
|
||||
var onlineAgents = await _db.Agents.CountAsync(a => a.Status == AgentStatus.Online, ct).ConfigureAwait(false);
|
||||
var activeSites = await _db.Sites.CountAsync(s => s.Enabled, ct).ConfigureAwait(false);
|
||||
var camerasOnline = await _db.Cameras.CountAsync(c => c.Status == CameraStatus.Online, ct).ConfigureAwait(false);
|
||||
var totalUsers = await _db.Users.CountAsync(ct).ConfigureAwait(false);
|
||||
var totalUsers = await _users.CountUsersAsync(ct).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<StatsResponse>.Success(new StatsResponse(
|
||||
totalSites,
|
||||
|
||||
@@ -5,4 +5,5 @@ namespace Heimdall.Application.Users.Commands.AssignRoles;
|
||||
|
||||
public record AssignRolesCommand(
|
||||
Guid UserId,
|
||||
IList<string> Roles) : IRequest<ServiceResult>;
|
||||
IList<string> Roles,
|
||||
Guid? ActorId = null) : IRequest<ServiceResult>;
|
||||
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.AssignRoles;
|
||||
|
||||
public class AssignRolesHandler : IRequestHandler<AssignRolesCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public AssignRolesHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
public AssignRolesHandler(IIdentityAccountService userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
@@ -19,11 +19,11 @@ public class AssignRolesHandler : IRequestHandler<AssignRolesCommand, ServiceRes
|
||||
|
||||
public async Task<ServiceResult> Handle(AssignRolesCommand command, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
var currentRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
|
||||
var currentRoles = await _userManager.GetRolesAsync(user, ct).ConfigureAwait(false);
|
||||
|
||||
var wasAdmin = currentRoles.Contains("Admin");
|
||||
var willBeAdmin = command.Roles.Contains("Admin");
|
||||
@@ -35,11 +35,34 @@ public class AssignRolesHandler : IRequestHandler<AssignRolesCommand, ServiceRes
|
||||
"Promote another user to Admin first.", 400);
|
||||
}
|
||||
|
||||
await _userManager.RemoveFromRolesAsync(user, currentRoles).ConfigureAwait(false);
|
||||
await _userManager.AddToRolesAsync(user, command.Roles).ConfigureAwait(false);
|
||||
await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
var rolesToAdd = command.Roles.Except(currentRoles, StringComparer.OrdinalIgnoreCase).ToArray();
|
||||
var rolesToRemove = currentRoles.Except(command.Roles, StringComparer.OrdinalIgnoreCase).ToArray();
|
||||
if (rolesToAdd.Length > 0)
|
||||
{
|
||||
var added = await _userManager.AddToRolesAsync(user, rolesToAdd, ct).ConfigureAwait(false);
|
||||
if (!added.Succeeded) return ServiceResult.Failure("Unable to update user roles");
|
||||
}
|
||||
if (rolesToRemove.Length > 0)
|
||||
{
|
||||
var removed = await _userManager.RemoveFromRolesAsync(user, rolesToRemove, ct).ConfigureAwait(false);
|
||||
if (!removed.Succeeded)
|
||||
{
|
||||
if (rolesToAdd.Length > 0)
|
||||
await _userManager.RemoveFromRolesAsync(user, rolesToAdd, ct).ConfigureAwait(false);
|
||||
return ServiceResult.Failure("Unable to update user roles");
|
||||
}
|
||||
}
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
|
||||
if (!stamp)
|
||||
{
|
||||
if (rolesToRemove.Length > 0)
|
||||
await _userManager.AddToRolesAsync(user, rolesToRemove, ct).ConfigureAwait(false);
|
||||
if (rolesToAdd.Length > 0)
|
||||
await _userManager.RemoveFromRolesAsync(user, rolesToAdd, ct).ConfigureAwait(false);
|
||||
return ServiceResult.Failure("Unable to revoke existing sessions");
|
||||
}
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserRolesUpdated", "User",
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "UserRolesUpdated", "User",
|
||||
command.UserId.ToString(),
|
||||
string.Join(",", currentRoles),
|
||||
string.Join(",", command.Roles),
|
||||
|
||||
@@ -5,4 +5,5 @@ namespace Heimdall.Application.Users.Commands.AssignSites;
|
||||
|
||||
public record AssignSitesCommand(
|
||||
Guid UserId,
|
||||
IList<Guid> SiteIds) : IRequest<ServiceResult>;
|
||||
IList<Guid> SiteIds,
|
||||
Guid? ActorId = null) : IRequest<ServiceResult>;
|
||||
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.AssignSites;
|
||||
|
||||
public class AssignSitesHandler : IRequestHandler<AssignSitesCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public AssignSitesHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
public AssignSitesHandler(IIdentityAccountService userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
@@ -19,11 +19,13 @@ public class AssignSitesHandler : IRequestHandler<AssignSitesCommand, ServiceRes
|
||||
|
||||
public async Task<ServiceResult> Handle(AssignSitesCommand command, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
await _repository.SetUserSitesAsync(command.UserId, command.SiteIds, ct).ConfigureAwait(false);
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "UserSitesUpdated", "User", command.UserId.ToString(),
|
||||
null, string.Join(',', command.SiteIds), ct).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.ConfirmEmail;
|
||||
|
||||
public class ConfirmEmailCommandHandler : IRequestHandler<ConfirmEmailCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public ConfirmEmailCommandHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
public ConfirmEmailCommandHandler(IIdentityAccountService userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
@@ -19,15 +19,15 @@ public class ConfirmEmailCommandHandler : IRequestHandler<ConfirmEmailCommand, S
|
||||
|
||||
public async Task<ServiceResult> Handle(ConfirmEmailCommand request, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(request.UserId.ToString()).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByIdAsync(request.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
return ServiceResult.Failure("Utilisateur introuvable", 404);
|
||||
|
||||
if (user.EmailConfirmed)
|
||||
return ServiceResult.Failure("L'email est déjà confirmé", 400);
|
||||
|
||||
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
|
||||
var result = await _userManager.ConfirmEmailAsync(user, token).ConfigureAwait(false);
|
||||
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user, ct);
|
||||
var result = await _userManager.ConfirmEmailAsync(user, token, ct).ConfigureAwait(false);
|
||||
|
||||
if (!result.Succeeded)
|
||||
return ServiceResult.Failure("Erreur lors de la confirmation de l'email", 400);
|
||||
|
||||
@@ -8,4 +8,5 @@ public record CreateUserCommand(
|
||||
string Email,
|
||||
string Password,
|
||||
string DisplayName,
|
||||
IList<string>? Roles) : IRequest<ServiceResult<UserResponse>>;
|
||||
IList<string>? Roles,
|
||||
Guid? ActorId = null) : IRequest<ServiceResult<UserResponse>>;
|
||||
@@ -3,16 +3,16 @@ using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.CreateUser;
|
||||
|
||||
public class CreateUserHandler : IRequestHandler<CreateUserCommand, ServiceResult<UserResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public CreateUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
public CreateUserHandler(IIdentityAccountService userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
@@ -20,26 +20,31 @@ public class CreateUserHandler : IRequestHandler<CreateUserCommand, ServiceResul
|
||||
|
||||
public async Task<ServiceResult<UserResponse>> Handle(CreateUserCommand command, CancellationToken ct)
|
||||
{
|
||||
var existing = await _userManager.FindByEmailAsync(command.Email).ConfigureAwait(false);
|
||||
var existing = await _userManager.FindByEmailAsync(command.Email, ct).ConfigureAwait(false);
|
||||
if (existing is not null)
|
||||
return ServiceResult<UserResponse>.Conflict("Email already registered");
|
||||
|
||||
var user = new AppUser
|
||||
var user = new IdentityAccount
|
||||
{
|
||||
UserName = command.Email,
|
||||
Email = command.Email,
|
||||
DisplayName = command.DisplayName
|
||||
};
|
||||
|
||||
var result = await _userManager.CreateAsync(user, command.Password).ConfigureAwait(false);
|
||||
var result = await _userManager.CreateAsync(user, command.Password, ct).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
return ServiceResult<UserResponse>.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
string.Join(", ", result.ErrorCodes));
|
||||
|
||||
var roles = command.Roles is { Count: > 0 } ? command.Roles : new List<string> { "Viewer" };
|
||||
await _userManager.AddToRolesAsync(user, roles).ConfigureAwait(false);
|
||||
var assignment = await _userManager.AddToRolesAsync(user, roles, ct).ConfigureAwait(false);
|
||||
if (!assignment.Succeeded)
|
||||
{
|
||||
await _userManager.DeleteAsync(user, ct).ConfigureAwait(false);
|
||||
return ServiceResult<UserResponse>.Failure("Unable to assign requested account roles");
|
||||
}
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserCreated", "User", user.Id.ToString(),
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "UserCreated", "User", user.Id.ToString(),
|
||||
null, null, ct);
|
||||
|
||||
var response = await _repository.GetByIdAsync(user.Id, ct).ConfigureAwait(false);
|
||||
|
||||
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.DeleteUser;
|
||||
|
||||
public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public DeleteUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
public DeleteUserHandler(IIdentityAccountService userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
@@ -22,11 +22,11 @@ public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, ServiceResul
|
||||
if (command.UserId == command.CurrentUserId)
|
||||
return ServiceResult.Failure("You cannot delete your own account.", 400);
|
||||
|
||||
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
var roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
|
||||
var roles = await _userManager.GetRolesAsync(user, ct).ConfigureAwait(false);
|
||||
if (roles.Contains("Admin"))
|
||||
{
|
||||
var adminCount = await _repository.CountAdminUsersAsync(ct).ConfigureAwait(false);
|
||||
@@ -37,10 +37,10 @@ public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, ServiceResul
|
||||
|
||||
await _repository.RemoveUserDataAsync(command.UserId, ct).ConfigureAwait(false);
|
||||
|
||||
var result = await _userManager.DeleteAsync(user).ConfigureAwait(false);
|
||||
var result = await _userManager.DeleteAsync(user, ct).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
return ServiceResult.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
string.Join(", ", result.ErrorCodes));
|
||||
|
||||
await _repository.AddAuditLogAsync(command.CurrentUserId, "UserDeleted", "User",
|
||||
command.UserId.ToString(), null, null, ct);
|
||||
|
||||
@@ -3,4 +3,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.LockUser;
|
||||
|
||||
public record LockUserCommand(Guid UserId) : IRequest<ServiceResult>;
|
||||
public record LockUserCommand(Guid UserId, Guid? ActorId = null) : IRequest<ServiceResult>;
|
||||
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.LockUser;
|
||||
|
||||
public class LockUserHandler : IRequestHandler<LockUserCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public LockUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
public LockUserHandler(IIdentityAccountService userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
@@ -19,14 +19,21 @@ public class LockUserHandler : IRequestHandler<LockUserCommand, ServiceResult>
|
||||
|
||||
public async Task<ServiceResult> Handle(LockUserCommand command, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue).ConfigureAwait(false);
|
||||
await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
var roles = await _userManager.GetRolesAsync(user, ct).ConfigureAwait(false);
|
||||
if (roles.Contains("Admin", StringComparer.OrdinalIgnoreCase)
|
||||
&& await _repository.CountAdminUsersAsync(ct).ConfigureAwait(false) <= 1)
|
||||
return ServiceResult.Failure("Cannot lock the last administrator account.", 400);
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserLocked", "User",
|
||||
var lockout = await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue, ct).ConfigureAwait(false);
|
||||
if (!lockout.Succeeded) return ServiceResult.Failure("Unable to lock account");
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
|
||||
if (!stamp) return ServiceResult.Failure("Unable to revoke existing sessions");
|
||||
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "UserLocked", "User",
|
||||
command.UserId.ToString(), null, null, ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
|
||||
@@ -4,4 +4,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.ResetPassword;
|
||||
|
||||
public record ResetPasswordCommand(Guid UserId) : IRequest<ServiceResult<ResetPasswordResponse>>;
|
||||
public record ResetPasswordCommand(Guid UserId, Guid? ActorId = null) : IRequest<ServiceResult<ResetPasswordResponse>>;
|
||||
@@ -4,16 +4,16 @@ using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.ResetPassword;
|
||||
|
||||
public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, ServiceResult<ResetPasswordResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public ResetPasswordHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
public ResetPasswordHandler(IIdentityAccountService userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
@@ -21,22 +21,24 @@ public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, Servic
|
||||
|
||||
public async Task<ServiceResult<ResetPasswordResponse>> Handle(ResetPasswordCommand command, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
return ServiceResult<ResetPasswordResponse>.NotFound("User not found");
|
||||
|
||||
var temporaryPassword = GenerateTemporaryPassword();
|
||||
var token = await _userManager.GeneratePasswordResetTokenAsync(user).ConfigureAwait(false);
|
||||
var result = await _userManager.ResetPasswordAsync(user, token, temporaryPassword).ConfigureAwait(false);
|
||||
var token = await _userManager.GeneratePasswordResetTokenAsync(user, ct).ConfigureAwait(false);
|
||||
var result = await _userManager.ResetPasswordAsync(user, token, temporaryPassword, ct).ConfigureAwait(false);
|
||||
|
||||
if (!result.Succeeded)
|
||||
return ServiceResult<ResetPasswordResponse>.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
|
||||
|
||||
user.MustChangePassword = true;
|
||||
await _userManager.UpdateAsync(user).ConfigureAwait(false);
|
||||
var updated = await _userManager.UpdateAsync(user, ct).ConfigureAwait(false);
|
||||
if (!updated.Succeeded) return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
|
||||
if (!stamp) return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserPasswordReset", "User",
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "UserPasswordReset", "User",
|
||||
command.UserId.ToString(), null, null, ct);
|
||||
|
||||
return ServiceResult<ResetPasswordResponse>.Success(
|
||||
|
||||
@@ -3,4 +3,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.UnlockUser;
|
||||
|
||||
public record UnlockUserCommand(Guid UserId) : IRequest<ServiceResult>;
|
||||
public record UnlockUserCommand(Guid UserId, Guid? ActorId = null) : IRequest<ServiceResult>;
|
||||
@@ -2,16 +2,16 @@ using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.UnlockUser;
|
||||
|
||||
public class UnlockUserHandler : IRequestHandler<UnlockUserCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public UnlockUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
public UnlockUserHandler(IIdentityAccountService userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
@@ -19,14 +19,18 @@ public class UnlockUserHandler : IRequestHandler<UnlockUserCommand, ServiceResul
|
||||
|
||||
public async Task<ServiceResult> Handle(UnlockUserCommand command, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByIdAsync(command.UserId, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
await _userManager.SetLockoutEndDateAsync(user, null).ConfigureAwait(false);
|
||||
await _userManager.ResetAccessFailedCountAsync(user).ConfigureAwait(false);
|
||||
var unlock = await _userManager.SetLockoutEndDateAsync(user, null, ct).ConfigureAwait(false);
|
||||
if (!unlock.Succeeded) return ServiceResult.Failure("Unable to unlock account");
|
||||
var reset = await _userManager.ResetAccessFailedCountAsync(user, ct).ConfigureAwait(false);
|
||||
if (!reset.Succeeded) return ServiceResult.Failure("Unable to reset failed sign-in count");
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
|
||||
if (!stamp) return ServiceResult.Failure("Unable to revoke existing sessions");
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserUnlocked", "User",
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "UserUnlocked", "User",
|
||||
command.UserId.ToString(), null, null, ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
|
||||
@@ -3,17 +3,17 @@ using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.UpdateUser;
|
||||
|
||||
public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ServiceResult<UserResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IIdentityAccountService _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public UpdateUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
public UpdateUserHandler(IIdentityAccountService userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
@@ -21,7 +21,7 @@ public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ServiceResul
|
||||
|
||||
public async Task<ServiceResult<UserResponse>> Handle(UpdateUserCommand command, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(command.Id.ToString()).ConfigureAwait(false);
|
||||
var user = await _userManager.FindByIdAsync(command.Id, ct).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
return ServiceResult<UserResponse>.NotFound("User not found");
|
||||
|
||||
@@ -40,7 +40,7 @@ public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ServiceResul
|
||||
|
||||
if (!string.Equals(oldEmail, newEmail, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var existingUser = await _userManager.FindByEmailAsync(newEmail).ConfigureAwait(false);
|
||||
var existingUser = await _userManager.FindByEmailAsync(newEmail, ct).ConfigureAwait(false);
|
||||
if (existingUser is not null && existingUser.Id != user.Id)
|
||||
return ServiceResult<UserResponse>.Failure("Cette adresse email est déjà utilisée", 409);
|
||||
|
||||
@@ -55,10 +55,17 @@ public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ServiceResul
|
||||
user.Theme = command.Theme ?? user.Theme;
|
||||
user.Language = language ?? user.Language;
|
||||
|
||||
var result = await _userManager.UpdateAsync(user).ConfigureAwait(false);
|
||||
var result = await _userManager.UpdateAsync(user, ct).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
return ServiceResult<UserResponse>.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
string.Join(", ", result.ErrorCodes));
|
||||
|
||||
if (emailChanged)
|
||||
{
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user, ct).ConfigureAwait(false);
|
||||
if (!stamp)
|
||||
return ServiceResult<UserResponse>.Failure("Email updated but existing sessions could not be revoked", 500);
|
||||
}
|
||||
|
||||
if (emailChanged)
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@ using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Users.Commands.CreateUser;
|
||||
using Heimdall.Application.Users.Commands.UpdateUser;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Application.Users.Mapping;
|
||||
|
||||
@@ -10,7 +11,7 @@ public class UserMappingProfile : Profile
|
||||
{
|
||||
public UserMappingProfile()
|
||||
{
|
||||
CreateMap<AppUser, UserResponse>()
|
||||
CreateMap<IdentityAccount, UserResponse>()
|
||||
.ForMember(d => d.Email, o => o.MapFrom(s => s.Email ?? string.Empty))
|
||||
.ForMember(d => d.Roles, o => o.Ignore())
|
||||
.ForMember(d => d.SiteIds, o => o.Ignore())
|
||||
|
||||
@@ -39,16 +39,6 @@
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.13, )",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "c6984ahCnqc3zqYgl5KqrBoY+LMKqJW6nZcFdBYNyp3PAA67prA/IgjQ/ySV0t3lEL2LEz3bcx91fbUYr8bRPA==",
|
||||
"dependencies": {
|
||||
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
|
||||
"Microsoft.Extensions.Identity.Stores": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Data.Sqlite": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.13, )",
|
||||
@@ -102,19 +92,6 @@
|
||||
"resolved": "2.0.1",
|
||||
"contentHash": "FYv95bNT4UwcNA+G/J1oX5OpRiSUxteXaUt2BJbRSdRNiIUNbggJF69wy6mnk2wYToaanpdXZdCwVylt96MpwQ=="
|
||||
},
|
||||
"Microsoft.AspNetCore.Cryptography.Internal": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "INZVBMOPbQC5xj1oTpwhELtokdH9LcY7oCsTVDEavziMpsoGJJPejax5WdFNfPeTMGq9eT6fL8GcVHeobvqORA=="
|
||||
},
|
||||
"Microsoft.AspNetCore.Cryptography.KeyDerivation": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "mt935Uji4EdglTPrgJrqHdXkWM2EI6d7V8fEfvlC+KevB16MtHUHGiaKycawlOJgbOMw1D9etbHIfLL2nnWV4Q==",
|
||||
"dependencies": {
|
||||
"Microsoft.AspNetCore.Cryptography.Internal": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Data.Sqlite.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
@@ -178,15 +155,6 @@
|
||||
"Microsoft.Extensions.Primitives": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "inhujYI/nikhmLxYI6ZEcaCgZ28ipJsKMPPxxr2XWf3vM0Q2P+E9R3hDHABZOLBxzD3gjpgcbSH/+hd2+gvI2A==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Primitives": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
@@ -195,15 +163,6 @@
|
||||
"Microsoft.Extensions.Primitives": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.Binder": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "yJJl/b0+W+GEWbu+7viw6C3h2BoNkB69Vlz7s/4e+hm4mYbJqfhdcDSi9sCXJw47blsBaiQd3UDPgDtop92+ug==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.13",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
@@ -222,46 +181,6 @@
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "6TyllZsToy3S/Ziu67GddljRTttuVJ8bbrbVUrsdHqH5678Oax5MpaEubxLoPoWLvgUBYo4KfcAig0mkBtktXQ=="
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "J9ODOrffj1mK3Et69elNsLGRguesPxvThTdVpFmQX7fLNPhIOgqHQfLdGnTBEwNAV3yf8yiyVlpDZNw2qN87Nw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.13",
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "oZzqZze8ed1fLS20HtIrkPxQXGRG/koq09srIw2ptnDHm9RHfwB++d35hosB/cXc55TH7Pshv85O0txongjCIg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Options": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Identity.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "76aNRvI7HU9sYjevIlpFuT/VyspRoiREwOZI+RFXM/HRJ3v6nC7gxSZoX881FEBkF+0udKHuFxtsWbRLytqsSA==",
|
||||
"dependencies": {
|
||||
"Microsoft.AspNetCore.Cryptography.KeyDerivation": "10.0.13",
|
||||
"Microsoft.Extensions.Diagnostics": "10.0.13",
|
||||
"Microsoft.Extensions.Logging": "10.0.13",
|
||||
"Microsoft.Extensions.Options": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Identity.Stores": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "qNZr9maHa2Kg7mRh+hLEJ59ts2OfYMiJJ5GVjx8BDrmhPxx/V345CTdIrUcZ5FZwwHepITsZY0e9qss7NB2U5A==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Caching.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Identity.Core": "10.0.13",
|
||||
"Microsoft.Extensions.Logging": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
@@ -289,18 +208,6 @@
|
||||
"Microsoft.Extensions.Primitives": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "xVO5HhATc09WXuS/RaDmx8ZeWS0mTpT1L0tkEDMSBHtAnNpNsDr0ge0wIO2jinCWWqpq5dL1tRTzpYNVlvyqLw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.13",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Options": "10.0.13",
|
||||
"Microsoft.Extensions.Primitives": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Primitives": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
@@ -365,8 +272,7 @@
|
||||
"heimdall.domain": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Heimdall.Domain.Primitives": "[1.0.0, )",
|
||||
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "[10.0.13, )"
|
||||
"Heimdall.Domain.Primitives": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"heimdall.domain.primitives": {
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
public class AppRole : IdentityRole<Guid>
|
||||
{
|
||||
public AppRole() { }
|
||||
|
||||
public AppRole(string name) : base(name) { }
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
public class AppUser : IdentityUser<Guid>
|
||||
{
|
||||
public string DisplayName { get; set; } = string.Empty;
|
||||
public string? Theme { get; set; } = "Auto";
|
||||
public string Language { get; set; } = "fr";
|
||||
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
public bool MustChangePassword { get; set; }
|
||||
|
||||
// Navigation
|
||||
private readonly List<UserSite> _userSites = [];
|
||||
public IReadOnlyCollection<UserSite> UserSites => _userSites.AsReadOnly();
|
||||
|
||||
private readonly List<UserGroup> _userGroups = [];
|
||||
public IReadOnlyCollection<UserGroup> UserGroups => _userGroups.AsReadOnly();
|
||||
}
|
||||
@@ -16,9 +16,6 @@ public class AuditLog
|
||||
public string? IpAddress { get; private set; }
|
||||
public DateTime Timestamp { get; private set; } = DateTime.UtcNow;
|
||||
|
||||
// Navigation
|
||||
public AppUser? User { get; private set; }
|
||||
|
||||
private AuditLog() { } // EF Core
|
||||
|
||||
public AuditLog(
|
||||
|
||||
@@ -10,7 +10,6 @@ public class UserCamera
|
||||
public Guid UserId { get; private set; }
|
||||
public Guid CameraId { get; private set; }
|
||||
|
||||
public AppUser User { get; private set; } = null!;
|
||||
public Camera Camera { get; private set; } = null!;
|
||||
|
||||
private UserCamera() { } // EF Core
|
||||
|
||||
@@ -19,7 +19,6 @@ public class UserCameraAccess : Entity<Guid>, IAuditableEntity
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
|
||||
// Navigation
|
||||
public AppUser User { get; private set; } = null!;
|
||||
public Site Site { get; private set; } = null!;
|
||||
public Camera? Camera { get; private set; }
|
||||
|
||||
|
||||
@@ -8,8 +8,6 @@ public class UserGroup
|
||||
public Guid UserId { get; private set; }
|
||||
public Guid GroupId { get; private set; }
|
||||
|
||||
// Navigation
|
||||
public AppUser User { get; private set; } = null!;
|
||||
public Group Group { get; private set; } = null!;
|
||||
|
||||
private UserGroup() { } // EF Core
|
||||
|
||||
@@ -9,7 +9,6 @@ public class UserSite
|
||||
public Guid UserId { get; private set; }
|
||||
public Guid SiteId { get; private set; }
|
||||
|
||||
public AppUser User { get; private set; } = null!;
|
||||
public Site Site { get; private set; } = null!;
|
||||
|
||||
private UserSite() { } // EF Core
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Heimdall.Domain.Primitives\Heimdall.Domain.Primitives.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.13" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
@@ -2,204 +2,6 @@
|
||||
"version": 1,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.13, )",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "c6984ahCnqc3zqYgl5KqrBoY+LMKqJW6nZcFdBYNyp3PAA67prA/IgjQ/ySV0t3lEL2LEz3bcx91fbUYr8bRPA==",
|
||||
"dependencies": {
|
||||
"Microsoft.EntityFrameworkCore.Relational": "10.0.13",
|
||||
"Microsoft.Extensions.Identity.Stores": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.AspNetCore.Cryptography.Internal": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "INZVBMOPbQC5xj1oTpwhELtokdH9LcY7oCsTVDEavziMpsoGJJPejax5WdFNfPeTMGq9eT6fL8GcVHeobvqORA=="
|
||||
},
|
||||
"Microsoft.AspNetCore.Cryptography.KeyDerivation": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "mt935Uji4EdglTPrgJrqHdXkWM2EI6d7V8fEfvlC+KevB16MtHUHGiaKycawlOJgbOMw1D9etbHIfLL2nnWV4Q==",
|
||||
"dependencies": {
|
||||
"Microsoft.AspNetCore.Cryptography.Internal": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.EntityFrameworkCore": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "u/z4nTQUJ5nJEXAQekgQEQZkh0delp4gL+ESHn7Z6k037c8HC5mSNu1/YdBgxGm7DtLjhOxktNl+aQMzw6wN7A==",
|
||||
"dependencies": {
|
||||
"Microsoft.EntityFrameworkCore.Abstractions": "10.0.13",
|
||||
"Microsoft.EntityFrameworkCore.Analyzers": "10.0.13",
|
||||
"Microsoft.Extensions.Caching.Memory": "10.0.13",
|
||||
"Microsoft.Extensions.Logging": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.EntityFrameworkCore.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "ARw+tZ3eiTosnK5nJPUGEzeUQcjyqCqs3qKA3lPtIRH5yJo3qIgxm7AvkZVIT9iWkS2083UsWe3Rj1MysW3p5A=="
|
||||
},
|
||||
"Microsoft.EntityFrameworkCore.Analyzers": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "zBx6VeEz/hkhlm0BJ2V+9xebUuDDIszcKvurJceQHuZPEXuXubrL6Lneo9VZiliRyJbQlB2oNKLkJXd3gHteQA=="
|
||||
},
|
||||
"Microsoft.EntityFrameworkCore.Relational": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "QU/sbTtDR5wVAJRVecC1GwM7mwH8bvKOZNm+lulzMr5rhjdb8DDEFIqqdhF08JIo51DPv5uQdZ1nXoZsD5pTag==",
|
||||
"dependencies": {
|
||||
"Microsoft.EntityFrameworkCore": "10.0.13",
|
||||
"Microsoft.Extensions.Caching.Memory": "10.0.13",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Logging": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Caching.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "UOJqcdNMoFcV/5RUcOlVKq9pPmbrcmbpLx5iYz9QtrmMcWRQzlL5Q/NZRfbPPLNyIEc1HWjjs5Z7nIwqewU1sg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Primitives": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Caching.Memory": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "q+At65RACuCtGwUDVI08TmmrC73YFouimMkJAtlhsGhFcU/dVpqYEKpNBOF9TUxkJ6aefEOShqe7StLK7q3NqA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Caching.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Options": "10.0.13",
|
||||
"Microsoft.Extensions.Primitives": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "inhujYI/nikhmLxYI6ZEcaCgZ28ipJsKMPPxxr2XWf3vM0Q2P+E9R3hDHABZOLBxzD3gjpgcbSH/+hd2+gvI2A==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Primitives": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "DY4C2qzTt2lOIY3VoscBH/TCwTolI5DKOfgJLuI+k1QUvRNT5vTMS58AOerNiihdVRStO0wEpLeRWA8jytzHBQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Primitives": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.Binder": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "yJJl/b0+W+GEWbu+7viw6C3h2BoNkB69Vlz7s/4e+hm4mYbJqfhdcDSi9sCXJw47blsBaiQd3UDPgDtop92+ug==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.13",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "4tnWU9vrU/A8NwYe9Z6wvieZ0EBb/uM82LAT+edNhdepOBWREZ7M7mzb941EIDPJaeOFdbVrDd5+7s9e89U6bQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "G2GrGWNAPZBsii2F6AU8n+JT2tC1/I0Ml/e9ZyNCgPjf3hZqronP7o0X91aAynCmVeae8KkSIUNXXeXCNRmdVQ=="
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "J9ODOrffj1mK3Et69elNsLGRguesPxvThTdVpFmQX7fLNPhIOgqHQfLdGnTBEwNAV3yf8yiyVlpDZNw2qN87Nw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.13",
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "oZzqZze8ed1fLS20HtIrkPxQXGRG/koq09srIw2ptnDHm9RHfwB++d35hosB/cXc55TH7Pshv85O0txongjCIg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Options": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Identity.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "76aNRvI7HU9sYjevIlpFuT/VyspRoiREwOZI+RFXM/HRJ3v6nC7gxSZoX881FEBkF+0udKHuFxtsWbRLytqsSA==",
|
||||
"dependencies": {
|
||||
"Microsoft.AspNetCore.Cryptography.KeyDerivation": "10.0.13",
|
||||
"Microsoft.Extensions.Diagnostics": "10.0.13",
|
||||
"Microsoft.Extensions.Logging": "10.0.13",
|
||||
"Microsoft.Extensions.Options": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Identity.Stores": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "qNZr9maHa2Kg7mRh+hLEJ59ts2OfYMiJJ5GVjx8BDrmhPxx/V345CTdIrUcZ5FZwwHepITsZY0e9qss7NB2U5A==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Caching.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Identity.Core": "10.0.13",
|
||||
"Microsoft.Extensions.Logging": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "fqbiPy4nUp4H2XHKAVQXKN2y3T2h4cFIx1DAAgE6iY9OHkN/OA1cKFi+geJKRWGuX6pS5SFbsjIPWHJqrxE0eg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection": "10.0.13",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Options": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "aSZEhEig4fvNiw2zs8Z6NyDlniKtq6YjcF3DyHuqTEHcZ2VKA/6itMPZ+dW+yWABWExlDcQwwdbqX1Rcb7W8WQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Options": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "tmMJgdrE4uhf1JcNs9CV9moAHW+hmDuvgMiPpnQxarKaUxqI2eN33sYK5S4l9Uw+rG9PJvlm4qPxMhvolTDTaQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Primitives": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "xVO5HhATc09WXuS/RaDmx8ZeWS0mTpT1L0tkEDMSBHtAnNpNsDr0ge0wIO2jinCWWqpq5dL1tRTzpYNVlvyqLw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.13",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.13",
|
||||
"Microsoft.Extensions.Options": "10.0.13",
|
||||
"Microsoft.Extensions.Primitives": "10.0.13"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Primitives": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.13",
|
||||
"contentHash": "ZjTwxzhiw2TMEzIbUDkMF0dfDB2I4NQgIfKD0ELu9/5Mk+SRGdKZcD0/lvBrRCAPo6KN2r0BW86MRancoyJkoA=="
|
||||
},
|
||||
"heimdall.domain.primitives": {
|
||||
"type": "Project"
|
||||
}
|
||||
|
||||
@@ -7,9 +7,10 @@ using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
namespace Heimdall.Infrastructure.Data;
|
||||
|
||||
public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicationDbContext
|
||||
public class AppDbContext : IdentityDbContext<IdentityAppUser, IdentityAppRole, Guid>, IApplicationDbContext, IIdentityPersistenceContext
|
||||
{
|
||||
private readonly AuditInterceptor _auditInterceptor;
|
||||
private readonly IServiceProvider? _serviceProvider;
|
||||
@@ -69,14 +70,6 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
|
||||
// 2FA recovery codes (stored hashed)
|
||||
public DbSet<UserRecoveryCode> UserRecoveryCodes => Set<UserRecoveryCode>();
|
||||
|
||||
// Identity tables (for synchronous admin checks in IQueryable filters)
|
||||
public new DbSet<AppRole> Roles => Set<AppRole>();
|
||||
|
||||
// Suppress CS0114 — base IdentityDbContext.UserRoles is virtual but we need
|
||||
// the specific DbSet<IdentityUserRole<Guid>> type exposed through IApplicationDbContext.
|
||||
public new DbSet<Microsoft.AspNetCore.Identity.IdentityUserRole<Guid>> UserRoles
|
||||
=> Set<Microsoft.AspNetCore.Identity.IdentityUserRole<Guid>>();
|
||||
|
||||
// Domain métier (spec 2.1)
|
||||
public DbSet<Vehicle> Vehicles => Set<Vehicle>();
|
||||
public DbSet<Recording> Recordings => Set<Recording>();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
@@ -34,7 +35,7 @@ public class AuditLogConfiguration : IEntityTypeConfiguration<AuditLog>
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
// Relationships
|
||||
builder.HasOne(al => al.User)
|
||||
builder.HasOne<IdentityAppUser>()
|
||||
.WithMany()
|
||||
.HasForeignKey(al => al.UserId)
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
@@ -52,8 +53,8 @@ public class UserGroupConfiguration : IEntityTypeConfiguration<UserGroup>
|
||||
|
||||
builder.HasKey(ug => new { ug.UserId, ug.GroupId });
|
||||
|
||||
builder.HasOne(ug => ug.User)
|
||||
.WithMany(u => u.UserGroups)
|
||||
builder.HasOne<IdentityAppUser>()
|
||||
.WithMany()
|
||||
.HasForeignKey(ug => ug.UserId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
|
||||
@@ -3,11 +3,12 @@ using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
namespace Heimdall.Infrastructure.Data.Configurations;
|
||||
|
||||
public class AppUserConfiguration : IEntityTypeConfiguration<AppUser>
|
||||
public class IdentityAppUserConfiguration : IEntityTypeConfiguration<IdentityAppUser>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<AppUser> builder)
|
||||
public void Configure(EntityTypeBuilder<IdentityAppUser> builder)
|
||||
{
|
||||
builder.ToTable("users");
|
||||
|
||||
@@ -33,9 +34,9 @@ public class AppUserConfiguration : IEntityTypeConfiguration<AppUser>
|
||||
}
|
||||
}
|
||||
|
||||
public class AppRoleConfiguration : IEntityTypeConfiguration<AppRole>
|
||||
public class IdentityAppRoleConfiguration : IEntityTypeConfiguration<IdentityAppRole>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<AppRole> builder)
|
||||
public void Configure(EntityTypeBuilder<IdentityAppRole> builder)
|
||||
{
|
||||
builder.ToTable("roles");
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ using Heimdall.Domain.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
namespace Heimdall.Infrastructure.Data.Configurations;
|
||||
|
||||
public class LoginChallengeConfiguration : IEntityTypeConfiguration<LoginChallenge>
|
||||
@@ -13,6 +14,6 @@ public class LoginChallengeConfiguration : IEntityTypeConfiguration<LoginChallen
|
||||
builder.Property(x => x.Id).HasMaxLength(64);
|
||||
builder.Property(x => x.SecurityStamp).HasMaxLength(256);
|
||||
builder.HasIndex(x => x.ExpiresAt);
|
||||
builder.HasOne<AppUser>().WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade);
|
||||
builder.HasOne<IdentityAppUser>().WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
@@ -12,7 +13,7 @@ public class UserCameraAccessConfiguration : IEntityTypeConfiguration<UserCamera
|
||||
|
||||
builder.HasKey(eca => new { eca.UserId, eca.SiteId, eca.CameraId });
|
||||
|
||||
builder.HasOne(eca => eca.User)
|
||||
builder.HasOne<IdentityAppUser>()
|
||||
.WithMany()
|
||||
.HasForeignKey(eca => eca.UserId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
@@ -12,7 +13,7 @@ public class UserCameraConfiguration : IEntityTypeConfiguration<UserCamera>
|
||||
|
||||
builder.HasKey(uc => new { uc.UserId, uc.CameraId });
|
||||
|
||||
builder.HasOne(uc => uc.User)
|
||||
builder.HasOne<IdentityAppUser>()
|
||||
.WithMany()
|
||||
.HasForeignKey(uc => uc.UserId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
@@ -12,8 +13,8 @@ public class UserSiteConfiguration : IEntityTypeConfiguration<UserSite>
|
||||
|
||||
builder.HasKey(us => new { us.UserId, us.SiteId });
|
||||
|
||||
builder.HasOne(us => us.User)
|
||||
.WithMany(u => u.UserSites)
|
||||
builder.HasOne<IdentityAppUser>()
|
||||
.WithMany()
|
||||
.HasForeignKey(us => us.UserId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
namespace Heimdall.Infrastructure;
|
||||
|
||||
public static class DependencyInjection
|
||||
@@ -43,6 +44,7 @@ public static class DependencyInjection
|
||||
ServiceLifetime.Scoped); // must be Scoped: AddDbContext registers DbContextOptions as Scoped, and a Singleton factory would fail DI validation (singleton → scoped)
|
||||
|
||||
services.AddScoped<IApplicationDbContext>(sp => sp.GetRequiredService<AppDbContext>());
|
||||
services.AddScoped<IIdentityPersistenceContext>(sp => sp.GetRequiredService<AppDbContext>());
|
||||
|
||||
// Stockage (spec Phase 8) — provider résolu depuis les settings DB
|
||||
// (storage.provider = Local | S3), factory scoped (lit la config à
|
||||
@@ -60,8 +62,11 @@ public static class DependencyInjection
|
||||
.AddCheck<Infrastructure.HealthChecks.AiHealthCheck>("codeproject-ai", tags: ["live"]);
|
||||
|
||||
// Identity
|
||||
services.AddIdentity<AppUser, AppRole>(options =>
|
||||
services.AddIdentity<IdentityAppUser, IdentityAppRole>(options =>
|
||||
{
|
||||
options.User.RequireUniqueEmail = true;
|
||||
options.SignIn.RequireConfirmedEmail = false; // Heimdall enforces the configurable policy at its auth boundary.
|
||||
options.Lockout.AllowedForNewUsers = true;
|
||||
options.Password.RequiredLength = 12;
|
||||
options.Password.RequireDigit = true;
|
||||
options.Password.RequireLowercase = true;
|
||||
@@ -146,6 +151,7 @@ public static class DependencyInjection
|
||||
|
||||
// Data access
|
||||
services.AddScoped<IUserRepository, UserRepository>();
|
||||
services.AddScoped<IIdentityAccountService, IdentityAccountService>();
|
||||
|
||||
// Camera discovery services (used by CQRS handlers)
|
||||
services.AddHttpClient("Discovery", client =>
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Infrastructure.Identity;
|
||||
|
||||
/// <summary>Infrastructure-only query surface for Identity entities used in composed authorization queries.</summary>
|
||||
public interface IIdentityPersistenceContext
|
||||
{
|
||||
DbSet<IdentityAppUser> Users { get; }
|
||||
DbSet<IdentityAppRole> Roles { get; }
|
||||
DbSet<IdentityUserRole<Guid>> UserRoles { get; }
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Infrastructure.Identity;
|
||||
|
||||
/// <summary>Adapts ASP.NET Core Identity to the application account port.</summary>
|
||||
public sealed class IdentityAccountService(UserManager<IdentityAppUser> users, AppDbContext db) : IIdentityAccountService
|
||||
{
|
||||
public async Task<IdentityAccount?> FindByIdAsync(Guid userId, CancellationToken ct = default)
|
||||
=> Map(await users.FindByIdAsync(userId.ToString()).ConfigureAwait(false));
|
||||
|
||||
public async Task<IdentityAccount?> FindByEmailAsync(string email, CancellationToken ct = default)
|
||||
=> Map(await users.FindByEmailAsync(email).ConfigureAwait(false));
|
||||
|
||||
public async Task<IdentityOperationResult> CreateAsync(IdentityAccount account, string password, CancellationToken ct = default)
|
||||
{
|
||||
var user = new IdentityAppUser { Id = account.Id == Guid.Empty ? Guid.NewGuid() : account.Id };
|
||||
Copy(account, user);
|
||||
var result = await users.CreateAsync(user, password).ConfigureAwait(false);
|
||||
account.Id = user.Id;
|
||||
account.SecurityStamp = user.SecurityStamp;
|
||||
return Map(result);
|
||||
}
|
||||
|
||||
public async Task<IdentityOperationResult> DeleteAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
{
|
||||
var user = await FindEntityAsync(account.Id).ConfigureAwait(false);
|
||||
return user is null ? Failure("UserNotFound") : Map(await users.DeleteAsync(user).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
public async Task<IdentityOperationResult> UpdateAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
{
|
||||
var user = await FindEntityAsync(account.Id).ConfigureAwait(false);
|
||||
if (user is null) return Failure("UserNotFound");
|
||||
Copy(account, user);
|
||||
return Map(await users.UpdateAsync(user).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
public async Task<IList<string>> GetRolesAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
{
|
||||
var user = await FindEntityAsync(account.Id).ConfigureAwait(false);
|
||||
return user is null ? [] : await users.GetRolesAsync(user).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<bool> IsInRoleAsync(Guid userId, string role, CancellationToken ct = default)
|
||||
{
|
||||
var user = await FindEntityAsync(userId).ConfigureAwait(false);
|
||||
return user is not null && await users.IsInRoleAsync(user, role).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<IdentityOperationResult> AddToRoleAsync(IdentityAccount account, string role, CancellationToken ct = default)
|
||||
=> await WithUser(account, u => users.AddToRoleAsync(u, role)).ConfigureAwait(false);
|
||||
|
||||
public async Task<IdentityOperationResult> AddToRolesAsync(IdentityAccount account, IEnumerable<string> roles, CancellationToken ct = default)
|
||||
=> await WithUser(account, u => users.AddToRolesAsync(u, roles)).ConfigureAwait(false);
|
||||
|
||||
public async Task<IdentityOperationResult> RemoveFromRolesAsync(IdentityAccount account, IEnumerable<string> roles, CancellationToken ct = default)
|
||||
=> await WithUser(account, u => users.RemoveFromRolesAsync(u, roles)).ConfigureAwait(false);
|
||||
|
||||
public async Task<bool> CheckPasswordAsync(IdentityAccount account, string password, CancellationToken ct = default)
|
||||
=> await WithUserValue(account, u => users.CheckPasswordAsync(u, password)).ConfigureAwait(false);
|
||||
|
||||
public async Task<IdentityOperationResult> ChangePasswordAsync(IdentityAccount account, string currentPassword, string newPassword, CancellationToken ct = default)
|
||||
=> await WithUser(account, u => users.ChangePasswordAsync(u, currentPassword, newPassword)).ConfigureAwait(false);
|
||||
|
||||
public async Task<string> GeneratePasswordResetTokenAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
=> await WithUserValue(account, users.GeneratePasswordResetTokenAsync).ConfigureAwait(false) ?? string.Empty;
|
||||
|
||||
public async Task<IdentityOperationResult> ResetPasswordAsync(IdentityAccount account, string token, string password, CancellationToken ct = default)
|
||||
=> await WithUser(account, u => users.ResetPasswordAsync(u, token, password)).ConfigureAwait(false);
|
||||
|
||||
public async Task<string> GenerateEmailConfirmationTokenAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
=> await WithUserValue(account, users.GenerateEmailConfirmationTokenAsync).ConfigureAwait(false) ?? string.Empty;
|
||||
|
||||
public async Task<IdentityOperationResult> ConfirmEmailAsync(IdentityAccount account, string token, CancellationToken ct = default)
|
||||
=> await WithUser(account, u => users.ConfirmEmailAsync(u, token)).ConfigureAwait(false);
|
||||
|
||||
public async Task<bool> IsEmailConfirmedAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
=> await WithUserValue(account, users.IsEmailConfirmedAsync).ConfigureAwait(false);
|
||||
|
||||
public async Task<bool> IsLockedOutAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
=> await WithUserValue(account, users.IsLockedOutAsync).ConfigureAwait(false);
|
||||
|
||||
public async Task<IdentityOperationResult> SetLockoutEndDateAsync(IdentityAccount account, DateTimeOffset? lockoutEnd, CancellationToken ct = default)
|
||||
=> await WithUser(account, u => users.SetLockoutEndDateAsync(u, lockoutEnd)).ConfigureAwait(false);
|
||||
|
||||
public async Task<IdentityOperationResult> ResetAccessFailedCountAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
=> await WithUser(account, users.ResetAccessFailedCountAsync).ConfigureAwait(false);
|
||||
|
||||
public async Task<IdentityOperationResult> AccessFailedAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
=> await WithUser(account, users.AccessFailedAsync).ConfigureAwait(false);
|
||||
|
||||
public async Task<bool> GetTwoFactorEnabledAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
=> await WithUserValue(account, users.GetTwoFactorEnabledAsync).ConfigureAwait(false);
|
||||
|
||||
public async Task<IdentityOperationResult> SetTwoFactorEnabledAsync(IdentityAccount account, bool enabled, CancellationToken ct = default)
|
||||
=> await WithUser(account, u => users.SetTwoFactorEnabledAsync(u, enabled)).ConfigureAwait(false);
|
||||
|
||||
public async Task<IdentityOperationResult> ResetAuthenticatorKeyAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
=> await WithUser(account, users.ResetAuthenticatorKeyAsync).ConfigureAwait(false);
|
||||
|
||||
public async Task<string?> GetAuthenticatorKeyAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
=> await WithUserValue(account, users.GetAuthenticatorKeyAsync).ConfigureAwait(false);
|
||||
|
||||
public async Task<bool> VerifyAuthenticatorTokenAsync(IdentityAccount account, string token, CancellationToken ct = default)
|
||||
=> await WithUserValue(account, u => users.VerifyTwoFactorTokenAsync(u, "Authenticator", token)).ConfigureAwait(false);
|
||||
|
||||
public async Task<bool> UpdateSecurityStampAsync(IdentityAccount account, CancellationToken ct = default)
|
||||
=> (await WithUser(account, users.UpdateSecurityStampAsync).ConfigureAwait(false)).Succeeded;
|
||||
|
||||
public async Task<UserSessionRecord?> GetSessionRecordAsync(Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
var row = await db.Users.AsNoTracking().Where(user => user.Id == userId)
|
||||
.Select(user => new { user.SecurityStamp, user.LockoutEnabled, user.LockoutEnd, user.EmailConfirmed })
|
||||
.SingleOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
return row is null ? null : new UserSessionRecord(row.SecurityStamp, row.LockoutEnabled, row.LockoutEnd, row.EmailConfirmed);
|
||||
}
|
||||
|
||||
private async Task<IdentityAppUser?> FindEntityAsync(Guid id) => await users.FindByIdAsync(id.ToString()).ConfigureAwait(false);
|
||||
|
||||
private async Task<IdentityOperationResult> WithUser(IdentityAccount account, Func<IdentityAppUser, Task<IdentityResult>> action)
|
||||
{
|
||||
var user = await FindEntityAsync(account.Id).ConfigureAwait(false);
|
||||
return user is null ? Failure("UserNotFound") : Map(await action(user).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
private async Task<T> WithUserValue<T>(IdentityAccount account, Func<IdentityAppUser, Task<T>> action)
|
||||
{
|
||||
var user = await FindEntityAsync(account.Id).ConfigureAwait(false);
|
||||
return user is null ? default! : await action(user).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static IdentityAccount? Map(IdentityAppUser? user) => user is null ? null : new IdentityAccount
|
||||
{
|
||||
Id = user.Id, UserName = user.UserName, Email = user.Email, DisplayName = user.DisplayName,
|
||||
Theme = user.Theme, Language = user.Language, CreatedAt = user.CreatedAt,
|
||||
MustChangePassword = user.MustChangePassword, EmailConfirmed = user.EmailConfirmed,
|
||||
LockoutEnabled = user.LockoutEnabled, LockoutEnd = user.LockoutEnd,
|
||||
AccessFailedCount = user.AccessFailedCount, TwoFactorEnabled = user.TwoFactorEnabled,
|
||||
SecurityStamp = user.SecurityStamp
|
||||
};
|
||||
|
||||
private static void Copy(IdentityAccount source, IdentityAppUser target)
|
||||
{
|
||||
target.UserName = source.UserName ?? source.Email;
|
||||
target.Email = source.Email;
|
||||
target.DisplayName = source.DisplayName;
|
||||
target.Theme = source.Theme;
|
||||
target.Language = source.Language;
|
||||
target.MustChangePassword = source.MustChangePassword;
|
||||
target.EmailConfirmed = source.EmailConfirmed;
|
||||
target.LockoutEnabled = source.LockoutEnabled;
|
||||
target.LockoutEnd = source.LockoutEnd;
|
||||
target.AccessFailedCount = source.AccessFailedCount;
|
||||
target.TwoFactorEnabled = source.TwoFactorEnabled;
|
||||
}
|
||||
|
||||
private static IdentityOperationResult Map(IdentityResult result) => new(result.Succeeded, result.Errors.Select(e => e.Code).ToArray());
|
||||
private static IdentityOperationResult Failure(string code) => new(false, [code]);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Infrastructure.Identity;
|
||||
|
||||
/// <summary>ASP.NET Core Identity persistence model. Kept out of Domain and Application.</summary>
|
||||
public sealed class IdentityAppUser : IdentityUser<Guid>
|
||||
{
|
||||
public string DisplayName { get; set; } = string.Empty;
|
||||
public string? Theme { get; set; } = "Auto";
|
||||
public string Language { get; set; } = "fr";
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
public bool MustChangePassword { get; set; }
|
||||
}
|
||||
|
||||
public sealed class IdentityAppRole : IdentityRole<Guid>
|
||||
{
|
||||
public IdentityAppRole() { }
|
||||
public IdentityAppRole(string name) : base(name) { }
|
||||
}
|
||||
+2887
File diff suppressed because it is too large.
Load diff
+22
@@ -0,0 +1,22 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Heimdall.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class MoveIdentityPersistenceToInfrastructure : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// <auto-generated />
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -17,7 +17,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.8")
|
||||
.HasAnnotation("ProductVersion", "10.0.13")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
@@ -117,6 +117,9 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(255)");
|
||||
|
||||
b.Property<DateTime?>("InventoryObservedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("IsDeleted")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
@@ -187,9 +190,6 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("TemperatureJson")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime?>("InventoryObservedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int?>("ThreadsPerCore")
|
||||
.HasColumnType("integer");
|
||||
|
||||
@@ -290,13 +290,16 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<double?>("GpuUtilizationPercent")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<DateTime?>("InventoryObservedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int?>("LogicalCores")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<long?>("MemTotalBytes")
|
||||
b.Property<long?>("MemAvailableBytes")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<long?>("MemAvailableBytes")
|
||||
b.Property<long?>("MemTotalBytes")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<long?>("MemoryUsageBytes")
|
||||
@@ -308,16 +311,13 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<string>("TemperatureJson")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime?>("InventoryObservedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CapturedAtUtc");
|
||||
|
||||
b.HasIndex("AgentId", "CapturedAtUtc")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("CapturedAtUtc");
|
||||
|
||||
b.HasIndex("SiteId", "CapturedAtUtc");
|
||||
|
||||
b.ToTable("agent_metric_samples", (string)null);
|
||||
@@ -511,33 +511,6 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.ToTable("api_keys", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AppRole", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("NormalizedName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("RoleNameIndex");
|
||||
|
||||
b.ToTable("roles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -596,101 +569,6 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.ToTable("app_settings", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("AccessFailedCount")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<bool>("EmailConfirmed")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Language")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(10)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasDefaultValue("fr");
|
||||
|
||||
b.Property<bool>("LockoutEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTimeOffset?>("LockoutEnd")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("MustChangePassword")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false);
|
||||
|
||||
b.Property<string>("NormalizedEmail")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("NormalizedUserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("PhoneNumberConfirmed")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Theme")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(20)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)")
|
||||
.HasDefaultValue("Auto");
|
||||
|
||||
b.Property<bool>("TwoFactorEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("UserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedEmail")
|
||||
.HasDatabaseName("EmailIndex");
|
||||
|
||||
b.HasIndex("NormalizedUserName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("UserNameIndex");
|
||||
|
||||
b.ToTable("users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -972,9 +850,6 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b =>
|
||||
{
|
||||
b.Property<string>("ExecutionProfileJson")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("CameraId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
@@ -999,6 +874,9 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<bool>("DetectVehicle")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("ExecutionProfileJson")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("FaceRecognition")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
@@ -1065,20 +943,17 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<int?>("HomeKitCategory")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("HomeKitDeviceId")
|
||||
.HasMaxLength(50)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(50)");
|
||||
|
||||
b.Property<int?>("HomeKitCategory")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool?>("HomeKitIsPaired")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int?>("HomeKitPort")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("HomeKitModel")
|
||||
.HasMaxLength(200)
|
||||
.IsUnicode(false)
|
||||
@@ -1089,6 +964,9 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<int?>("HomeKitPort")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("Hostname")
|
||||
.HasMaxLength(255)
|
||||
.IsUnicode(false)
|
||||
@@ -1223,19 +1101,17 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<Guid?>("RecordingId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("SnapshotThumbUrl")
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<string>("SnapshotObjectKey")
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<string>("SnapshotThumbObjectKey")
|
||||
b.Property<string>("SnapshotStorageBucket")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("SnapshotStorageEndpoint")
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<string>("SnapshotStorageProvider")
|
||||
@@ -1247,13 +1123,15 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<string>("SnapshotStorageEndpoint")
|
||||
b.Property<string>("SnapshotThumbObjectKey")
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<string>("SnapshotStorageBucket")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
b.Property<string>("SnapshotThumbUrl")
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<string>("SnapshotUrl")
|
||||
.HasMaxLength(2000)
|
||||
@@ -1289,8 +1167,6 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
b.HasIndex("ParentEventId");
|
||||
|
||||
b.HasIndex("PersonId", "OccurredAt");
|
||||
|
||||
b.HasIndex("RecordingId");
|
||||
|
||||
b.HasIndex("TrackId");
|
||||
@@ -1302,6 +1178,8 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
b.HasIndex("CameraId", "Type");
|
||||
|
||||
b.HasIndex("PersonId", "OccurredAt");
|
||||
|
||||
b.ToTable("camera_events", (string)null);
|
||||
});
|
||||
|
||||
@@ -1513,9 +1391,6 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<bool>("Verifying")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int>("Attempts")
|
||||
.HasColumnType("integer");
|
||||
|
||||
@@ -1533,6 +1408,9 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<bool>("Verifying")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ExpiresAt");
|
||||
@@ -1545,6 +1423,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.ManualSnapshotRequest", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("AgentId")
|
||||
@@ -1573,10 +1452,10 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CameraId", "CreatedAt");
|
||||
|
||||
b.HasIndex("ExpiresAt");
|
||||
|
||||
b.HasIndex("CameraId", "CreatedAt");
|
||||
|
||||
b.ToTable("manual_snapshot_requests", (string)null);
|
||||
});
|
||||
|
||||
@@ -1708,13 +1587,13 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Status", "NextAttemptAt", "LeaseExpiresAt")
|
||||
.HasDatabaseName("ix_notification_deliveries_dispatch");
|
||||
|
||||
b.HasIndex("NotificationId", "Channel")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ux_notification_deliveries_notification_channel");
|
||||
|
||||
b.HasIndex("Status", "NextAttemptAt", "LeaseExpiresAt")
|
||||
.HasDatabaseName("ix_notification_deliveries_dispatch");
|
||||
|
||||
b.ToTable("notification_deliveries", (string)null);
|
||||
});
|
||||
|
||||
@@ -1846,21 +1725,17 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<bool>("StorageLocationCaptured")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false);
|
||||
|
||||
b.Property<string>("StoragePath")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<string>("StorageRoot")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<bool>("StorageLocationCaptured")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false);
|
||||
|
||||
b.Property<Guid?>("StoragePolicyId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
@@ -1870,6 +1745,10 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<string>("StorageRoot")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<DateTime>("Timestamp")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
@@ -2031,42 +1910,6 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.ToTable("site_credentials", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.StoragePolicy", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<int>("RetentionDays")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("StorageProvider")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("storage_policies", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.StorageDestination", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -2110,6 +1953,42 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.ToTable("storage_destinations", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.StoragePolicy", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<int>("RetentionDays")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("StorageProvider")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("storage_policies", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
@@ -2328,6 +2207,128 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.ToTable("vehicles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Infrastructure.Identity.IdentityAppRole", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("NormalizedName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("RoleNameIndex");
|
||||
|
||||
b.ToTable("roles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Infrastructure.Identity.IdentityAppUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("AccessFailedCount")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("ConcurrencyStamp")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<bool>("EmailConfirmed")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Language")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(10)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasDefaultValue("fr");
|
||||
|
||||
b.Property<bool>("LockoutEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTimeOffset?>("LockoutEnd")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("MustChangePassword")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false);
|
||||
|
||||
b.Property<string>("NormalizedEmail")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("NormalizedUserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PhoneNumber")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("PhoneNumberConfirmed")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("SecurityStamp")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Theme")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasMaxLength(20)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(20)")
|
||||
.HasDefaultValue("Auto");
|
||||
|
||||
b.Property<bool>("TwoFactorEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("UserName")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("NormalizedEmail")
|
||||
.HasDatabaseName("EmailIndex");
|
||||
|
||||
b.HasIndex("NormalizedUserName")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("UserNameIndex");
|
||||
|
||||
b.ToTable("users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
@@ -2431,15 +2432,6 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.ToTable("user_tokens", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.Notification", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("NotificationId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.Site", "Site")
|
||||
@@ -2512,12 +2504,10 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
|
||||
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b =>
|
||||
@@ -2668,13 +2658,22 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
|
||||
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.Notification", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("NotificationId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.Camera", "Camera")
|
||||
@@ -2712,15 +2711,13 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
|
||||
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Camera");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b =>
|
||||
@@ -2736,7 +2733,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
|
||||
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
@@ -2745,8 +2742,6 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Navigation("Camera");
|
||||
|
||||
b.Navigation("Site");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b =>
|
||||
@@ -2757,15 +2752,13 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
|
||||
.WithMany("UserGroups")
|
||||
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Group");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b =>
|
||||
@@ -2776,15 +2769,13 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", "User")
|
||||
.WithMany("UserSites")
|
||||
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Site");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b =>
|
||||
@@ -2799,7 +2790,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppRole", null)
|
||||
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppRole", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
@@ -2808,7 +2799,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
|
||||
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
@@ -2817,7 +2808,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
|
||||
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
@@ -2826,13 +2817,13 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppRole", null)
|
||||
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppRole", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
|
||||
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
@@ -2841,7 +2832,7 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.AppUser", null)
|
||||
b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
@@ -2853,13 +2844,6 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Navigation("Cameras");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b =>
|
||||
{
|
||||
b.Navigation("UserGroups");
|
||||
|
||||
b.Navigation("UserSites");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b =>
|
||||
{
|
||||
b.Navigation("Credentials");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
@@ -11,9 +12,9 @@ namespace Heimdall.Infrastructure.Persistence;
|
||||
public class UserRepository : IUserRepository
|
||||
{
|
||||
private readonly AppDbContext _db;
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly UserManager<IdentityAppUser> _userManager;
|
||||
|
||||
public UserRepository(AppDbContext db, UserManager<AppUser> userManager)
|
||||
public UserRepository(AppDbContext db, UserManager<IdentityAppUser> userManager)
|
||||
{
|
||||
_db = db;
|
||||
_userManager = userManager;
|
||||
@@ -90,8 +91,13 @@ public class UserRepository : IUserRepository
|
||||
var adminRole = await _db.Roles.FirstOrDefaultAsync(r => r.Name == AppRoles.Admin, ct).ConfigureAwait(false);
|
||||
if (adminRole is null) return 0;
|
||||
|
||||
return await _db.Set<IdentityUserRole<Guid>>()
|
||||
.CountAsync(ur => ur.RoleId == adminRole.Id, ct);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
return await (from membership in _db.Set<IdentityUserRole<Guid>>()
|
||||
join user in _db.Users on membership.UserId equals user.Id
|
||||
where membership.RoleId == adminRole.Id
|
||||
&& (!user.LockoutEnabled || user.LockoutEnd == null || user.LockoutEnd <= now)
|
||||
select membership.UserId)
|
||||
.CountAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task AddAuditLogAsync(Guid? userId, string action, string resourceType,
|
||||
@@ -126,7 +132,37 @@ public class UserRepository : IUserRepository
|
||||
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static UserResponse MapToResponse(AppUser user, List<string> roles, List<Guid> siteIds)
|
||||
public Task<bool> ExistsAsync(Guid userId, CancellationToken ct)
|
||||
=> _db.Users.AsNoTracking().AnyAsync(user => user.Id == userId, ct);
|
||||
|
||||
public Task<int> CountUsersAsync(CancellationToken ct)
|
||||
=> _db.Users.AsNoTracking().CountAsync(ct);
|
||||
|
||||
public async Task<IReadOnlyDictionary<Guid, string>> GetLanguagesAsync(IReadOnlyCollection<Guid> userIds, CancellationToken ct)
|
||||
=> await _db.Users.AsNoTracking().Where(user => userIds.Contains(user.Id))
|
||||
.ToDictionaryAsync(user => user.Id, user => user.Language, ct).ConfigureAwait(false);
|
||||
|
||||
public async Task<IReadOnlyDictionary<Guid, string?>> GetEmailsAsync(IReadOnlyCollection<Guid> userIds, CancellationToken ct)
|
||||
=> await _db.Users.AsNoTracking().Where(user => userIds.Contains(user.Id))
|
||||
.ToDictionaryAsync(user => user.Id, user => user.Email, ct).ConfigureAwait(false);
|
||||
|
||||
public async Task<IReadOnlyList<GroupMemberResponse>> GetGroupMembersAsync(Guid groupId, CancellationToken ct)
|
||||
=> await (from membership in _db.UserGroups.AsNoTracking()
|
||||
join user in _db.Users.AsNoTracking() on membership.UserId equals user.Id
|
||||
where membership.GroupId == groupId
|
||||
orderby user.DisplayName
|
||||
select new GroupMemberResponse(user.Id, user.Email ?? string.Empty, user.DisplayName))
|
||||
.ToListAsync(ct).ConfigureAwait(false);
|
||||
|
||||
public async Task<bool> IsAdminAsync(Guid userId, CancellationToken ct)
|
||||
{
|
||||
var roleId = await _db.Roles.AsNoTracking().Where(role => role.Name == AppRoles.Admin)
|
||||
.Select(role => (Guid?)role.Id).SingleOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
return roleId.HasValue && await _db.UserRoles.AsNoTracking()
|
||||
.AnyAsync(userRole => userRole.UserId == userId && userRole.RoleId == roleId.Value, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static UserResponse MapToResponse(IdentityAppUser user, List<string> roles, List<Guid> siteIds)
|
||||
{
|
||||
return new UserResponse(
|
||||
user.Id,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
namespace Heimdall.Infrastructure.Security;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
namespace Heimdall.Infrastructure.Security;
|
||||
|
||||
public class AuthSignInService : IAuthSignInService
|
||||
{
|
||||
private readonly SignInManager<AppUser> _signInManager;
|
||||
private readonly SignInManager<IdentityAppUser> _signInManager;
|
||||
|
||||
public AuthSignInService(SignInManager<AppUser> signInManager)
|
||||
public AuthSignInService(SignInManager<IdentityAppUser> signInManager)
|
||||
{
|
||||
_signInManager = signInManager;
|
||||
}
|
||||
|
||||
public async Task<SignInServiceResult> PasswordSignInAsync(AppUser user, string password, bool lockoutOnFailure)
|
||||
public async Task<SignInServiceResult> PasswordSignInAsync(IdentityAccount account, string password, bool lockoutOnFailure)
|
||||
{
|
||||
var user = await _signInManager.UserManager.FindByIdAsync(account.Id.ToString()).ConfigureAwait(false);
|
||||
if (user is null) return new SignInServiceResult(SignInResultType.Failed);
|
||||
var result = await _signInManager.CheckPasswordSignInAsync(user, password, lockoutOnFailure).ConfigureAwait(false);
|
||||
if (result.IsLockedOut)
|
||||
await _signInManager.UserManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
|
||||
@@ -4,11 +4,11 @@ using System.Globalization;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
namespace Heimdall.Infrastructure.Security;
|
||||
|
||||
public class JwtService : IJwtService
|
||||
@@ -22,10 +22,10 @@ public class JwtService : IJwtService
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions)
|
||||
public (string token, DateTime expiresAt) GenerateAccessToken(IdentityAccount user, IList<string> roles, IList<string> permissions)
|
||||
=> GenerateAccessToken(user, roles, permissions, DateTime.UtcNow);
|
||||
|
||||
public (string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions, DateTime sessionStarted)
|
||||
public (string token, DateTime expiresAt) GenerateAccessToken(IdentityAccount user, IList<string> roles, IList<string> permissions, DateTime sessionStarted)
|
||||
{
|
||||
var key = new SymmetricSecurityKey(
|
||||
Encoding.UTF8.GetBytes(GetJwtKey()));
|
||||
@@ -61,10 +61,10 @@ public class JwtService : IJwtService
|
||||
return (new JwtSecurityTokenHandler().WriteToken(token), expiresAt);
|
||||
}
|
||||
|
||||
public (string token, DateTime expiresAt) GenerateRefreshToken(AppUser user)
|
||||
public (string token, DateTime expiresAt) GenerateRefreshToken(IdentityAccount user)
|
||||
=> GenerateRefreshToken(user, DateTime.UtcNow);
|
||||
|
||||
public (string token, DateTime expiresAt) GenerateRefreshToken(AppUser user, DateTime sessionStarted)
|
||||
public (string token, DateTime expiresAt) GenerateRefreshToken(IdentityAccount user, DateTime sessionStarted)
|
||||
{
|
||||
var refreshKeyValue = GetJwtRefreshKey();
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(refreshKeyValue));
|
||||
|
||||
@@ -1,20 +1,167 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
namespace Heimdall.Infrastructure.Security;
|
||||
|
||||
public class RolePermissionService : IRolePermissionService
|
||||
public sealed class RolePermissionService : IRolePermissionService
|
||||
{
|
||||
public IList<string> GetPermissionsForRoles(IList<string> roles)
|
||||
private const string PermissionClaim = "permission";
|
||||
private const string ConfiguredClaim = "heimdall:permissions-configured";
|
||||
private readonly RoleManager<IdentityAppRole> _roles;
|
||||
private readonly UserManager<IdentityAppUser> _users;
|
||||
private readonly IUserRepository _userRepository;
|
||||
|
||||
public RolePermissionService(RoleManager<IdentityAppRole> roles, UserManager<IdentityAppUser> users, IUserRepository userRepository)
|
||||
{
|
||||
var permissions = new List<string>();
|
||||
foreach (var role in roles)
|
||||
_roles = roles;
|
||||
_users = users;
|
||||
_userRepository = userRepository;
|
||||
}
|
||||
|
||||
public async Task<IList<string>> GetPermissionsForRolesAsync(IList<string> roleNames, CancellationToken ct)
|
||||
{
|
||||
if (AppPermissions.RolePermissions.TryGetValue(role, out var rolePerms))
|
||||
var permissions = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var name in roleNames)
|
||||
{
|
||||
permissions.AddRange(rolePerms);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var role = await _roles.FindByNameAsync(name).ConfigureAwait(false);
|
||||
if (role is null) continue;
|
||||
var claims = await _roles.GetClaimsAsync(role).ConfigureAwait(false);
|
||||
foreach (var claim in claims.Where(c => c.Type == PermissionClaim))
|
||||
if (claim.Value.Length > 0) permissions.Add(claim.Value);
|
||||
}
|
||||
return permissions.Order(StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<RolePermissionInfo>> GetAllAsync(CancellationToken ct)
|
||||
{
|
||||
var result = new List<RolePermissionInfo>(AppRoles.All.Length);
|
||||
foreach (var name in AppRoles.All)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var role = await _roles.FindByNameAsync(name).ConfigureAwait(false);
|
||||
if (role is null) continue;
|
||||
var claims = await _roles.GetClaimsAsync(role).ConfigureAwait(false);
|
||||
result.Add(new RolePermissionInfo(name, claims.Where(c => c.Type == PermissionClaim)
|
||||
.Select(c => c.Value).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> SetPermissionsAsync(string roleName, IReadOnlyCollection<string> permissions,
|
||||
Guid actorId, CancellationToken ct)
|
||||
{
|
||||
if (!AppRoles.All.Contains(roleName, StringComparer.Ordinal))
|
||||
return ServiceResult.NotFound("Role not found");
|
||||
if (roleName == AppRoles.Admin)
|
||||
return ServiceResult.Failure("The Admin role permissions are fixed to preserve full administrative recovery.", 400);
|
||||
|
||||
var allowed = AppPermissions.RolePermissions.Values.SelectMany(p => p).ToHashSet(StringComparer.Ordinal);
|
||||
var requested = permissions.ToHashSet(StringComparer.Ordinal);
|
||||
if (requested.Count != permissions.Count || requested.Any(p => !allowed.Contains(p)))
|
||||
return ServiceResult.Failure("The permission list contains duplicate or unknown permissions.", 400);
|
||||
|
||||
var role = await _roles.FindByNameAsync(roleName).ConfigureAwait(false);
|
||||
if (role is null) return ServiceResult.NotFound("Role not found");
|
||||
var current = await _roles.GetClaimsAsync(role).ConfigureAwait(false);
|
||||
var currentPermissions = current.Where(c => c.Type == PermissionClaim).Select(c => c.Value)
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
var additions = requested.Except(currentPermissions, StringComparer.Ordinal).ToArray();
|
||||
var removals = current.Where(c => c.Type == PermissionClaim && !requested.Contains(c.Value)).ToArray();
|
||||
if (additions.Length == 0 && removals.Length == 0) return ServiceResult.Success();
|
||||
|
||||
if (additions.Length > 0)
|
||||
{
|
||||
if (!await AddClaimsAsync(role, additions.Select(p => new Claim(PermissionClaim, p))).ConfigureAwait(false))
|
||||
return ServiceResult.Failure("Unable to update role permissions", 500);
|
||||
}
|
||||
if (removals.Length > 0)
|
||||
{
|
||||
if (!await RemoveClaimsAsync(role, removals).ConfigureAwait(false))
|
||||
{
|
||||
if (additions.Length > 0)
|
||||
await RemoveClaimsAsync(role, additions.Select(p => new Claim(PermissionClaim, p))).ConfigureAwait(false);
|
||||
return ServiceResult.Failure("Unable to update role permissions", 500);
|
||||
}
|
||||
}
|
||||
return permissions.Distinct().ToList();
|
||||
|
||||
var members = await _users.GetUsersInRoleAsync(roleName).ConfigureAwait(false);
|
||||
foreach (var user in members)
|
||||
{
|
||||
var stamp = await _users.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
if (!stamp.Succeeded)
|
||||
{
|
||||
// Earlier stamp rotations only revoke sessions early; restoring role claims
|
||||
// guarantees subsequent logins still receive the previous permission set.
|
||||
if (removals.Length > 0) await AddClaimsAsync(role, removals).ConfigureAwait(false);
|
||||
if (additions.Length > 0)
|
||||
await RemoveClaimsAsync(role, additions.Select(p => new Claim(PermissionClaim, p))).ConfigureAwait(false);
|
||||
return ServiceResult.Failure("Unable to revoke sessions after changing role permissions", 500);
|
||||
}
|
||||
}
|
||||
|
||||
await _userRepository.AddAuditLogAsync(actorId, "RolePermissionsUpdated", "Role", roleName,
|
||||
string.Join(',', currentPermissions.Order(StringComparer.Ordinal)),
|
||||
string.Join(',', requested.Order(StringComparer.Ordinal)), ct).ConfigureAwait(false);
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
public async Task EnsureDefaultsAsync(CancellationToken ct)
|
||||
{
|
||||
foreach (var roleName in AppRoles.All)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var role = await _roles.FindByNameAsync(roleName).ConfigureAwait(false);
|
||||
if (role is null) continue;
|
||||
var claims = await _roles.GetClaimsAsync(role).ConfigureAwait(false);
|
||||
if (claims.Any(c => c.Type == ConfiguredClaim)) continue;
|
||||
var defaults = AppPermissions.RolePermissions[roleName]
|
||||
.Select(permission => new Claim(PermissionClaim, permission))
|
||||
.Where(permission => !claims.Contains(permission)).ToList();
|
||||
defaults.Add(new Claim(ConfiguredClaim, "true"));
|
||||
if (!await AddClaimsAsync(role, defaults).ConfigureAwait(false))
|
||||
throw new InvalidOperationException($"Could not initialize permissions for role {roleName}.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> AddClaimsAsync(IdentityAppRole role, IEnumerable<Claim> claims)
|
||||
{
|
||||
var added = new List<Claim>();
|
||||
foreach (var claim in claims)
|
||||
{
|
||||
var result = await _roles.AddClaimAsync(role, claim).ConfigureAwait(false);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
added.Add(claim);
|
||||
continue;
|
||||
}
|
||||
foreach (var rollback in added)
|
||||
await _roles.RemoveClaimAsync(role, rollback).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<bool> RemoveClaimsAsync(IdentityAppRole role, IEnumerable<Claim> claims)
|
||||
{
|
||||
var removed = new List<Claim>();
|
||||
foreach (var claim in claims)
|
||||
{
|
||||
var result = await _roles.RemoveClaimAsync(role, claim).ConfigureAwait(false);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
removed.Add(claim);
|
||||
continue;
|
||||
}
|
||||
foreach (var rollback in removed)
|
||||
await _roles.AddClaimAsync(role, rollback).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,12 @@ using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Heimdall.Infrastructure.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
/// <summary>Union of explicit camera grants, legacy grants, sites and live group membership.</summary>
|
||||
public class CameraAccessService(IApplicationDbContext context) : ICameraAccessService
|
||||
public class CameraAccessService(IApplicationDbContext context, IIdentityPersistenceContext identity) : ICameraAccessService
|
||||
{
|
||||
public async Task<bool> HasCameraAccessAsync(Guid userId, Guid cameraId, CancellationToken ct = default)
|
||||
=> await ApplyCameraFilter(context.Cameras, userId).AnyAsync(c => c.Id == cameraId, ct);
|
||||
@@ -24,10 +24,10 @@ public class CameraAccessService(IApplicationDbContext context) : ICameraAccessS
|
||||
.ConfigureAwait(false);
|
||||
if (!siteId.HasValue) return [];
|
||||
|
||||
return await context.Users.AsNoTracking()
|
||||
return await identity.Users.AsNoTracking()
|
||||
.Where(user =>
|
||||
context.UserRoles.Any(ur => ur.UserId == user.Id &&
|
||||
context.Roles.Any(role => role.Id == ur.RoleId && role.Name == AppRoles.Admin)) ||
|
||||
identity.UserRoles.Any(ur => ur.UserId == user.Id &&
|
||||
identity.Roles.Any(role => role.Id == ur.RoleId && role.Name == AppRoles.Admin)) ||
|
||||
context.UserCameraAccesses.Any(grant => grant.UserId == user.Id && grant.SiteId == siteId.Value &&
|
||||
(grant.CameraId == null || grant.CameraId == cameraId)) ||
|
||||
context.UserCameras.Any(grant => grant.UserId == user.Id && grant.CameraId == cameraId) ||
|
||||
@@ -68,6 +68,6 @@ public class CameraAccessService(IApplicationDbContext context) : ICameraAccessS
|
||||
context.UserGroups.Any(m => m.UserId == userId && m.GroupId == a.GroupId)));
|
||||
}
|
||||
|
||||
private bool IsAdmin(Guid userId) => userId != Guid.Empty && context.UserRoles.Any(ur =>
|
||||
ur.UserId == userId && context.Roles.Any(r => r.Id == ur.RoleId && r.Name == AppRoles.Admin));
|
||||
private bool IsAdmin(Guid userId) => userId != Guid.Empty && identity.UserRoles.Any(ur =>
|
||||
ur.UserId == userId && identity.Roles.Any(r => r.Id == ur.RoleId && r.Name == AppRoles.Admin));
|
||||
}
|
||||
@@ -27,6 +27,9 @@ else if (_error)
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Class="mb-4">
|
||||
@Text["AdminClaims_EditableInfo"]
|
||||
</MudAlert>
|
||||
@foreach (var category in _groupedPermissions)
|
||||
{
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4" @key="category.Key">
|
||||
@@ -40,7 +43,20 @@ else
|
||||
<MudTh>@Text["AdminClaims_Description"]</MudTh>
|
||||
@foreach (var role in _roles)
|
||||
{
|
||||
<MudTh Class="text-center" @key="role.Name">@role.Name</MudTh>
|
||||
<MudTh Class="text-center" @key="role.Name">
|
||||
@role.Name
|
||||
@if (role.Name == "Admin")
|
||||
{
|
||||
<MudText Typo="Typo.caption">@Text["AdminClaims_AdminImmutable"]</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Size="Size.Small" Variant="Variant.Text" Disabled="@(_savingRole == role.Name)"
|
||||
OnClick="@(() => SavePermissions(role.Name))">
|
||||
@(_savingRole == role.Name ? Text["Saving"] : Text["Save"])
|
||||
</MudButton>
|
||||
}
|
||||
</MudTh>
|
||||
}
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
@@ -52,11 +68,11 @@ else
|
||||
</MudTd>
|
||||
@foreach (var role in _roles)
|
||||
{
|
||||
var hasPermission = role.Permissions.Contains(context.Name);
|
||||
var hasPermission = _selectedPermissions.GetValueOrDefault(role.Name)?.Contains(context.Name) == true;
|
||||
<MudTd DataLabel="@role.Name" Class="text-center" @key="role.Name">
|
||||
<MudIcon Icon="@(hasPermission ? Icons.Material.Filled.Check : Icons.Material.Filled.Remove)"
|
||||
Color="@(hasPermission ? Color.Success : Color.Default)"
|
||||
Size="Size.Small" />
|
||||
<MudCheckBox T="bool" Value="@hasPermission" Disabled="@(role.Name == "Admin" || _savingRole == role.Name)"
|
||||
ValueChanged="@((bool enabled) => SetPermission(role.Name, context.Name, enabled))"
|
||||
Color="Color.Primary" />
|
||||
</MudTd>
|
||||
}
|
||||
</RowTemplate>
|
||||
@@ -70,9 +86,11 @@ else
|
||||
@code {
|
||||
private List<PermissionItem>? _permissions;
|
||||
private List<RoleItem> _roles = [];
|
||||
private readonly Dictionary<string, HashSet<string>> _selectedPermissions = new(StringComparer.Ordinal);
|
||||
private Dictionary<string, List<PermissionItem>> _groupedPermissions = new();
|
||||
private bool _loading = true;
|
||||
private bool _error;
|
||||
private string? _savingRole;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
@@ -95,6 +113,9 @@ else
|
||||
|
||||
_permissions = await permissionsTask;
|
||||
_roles = await rolesTask;
|
||||
_selectedPermissions.Clear();
|
||||
foreach (var role in _roles)
|
||||
_selectedPermissions[role.Name] = role.Permissions.ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
_groupedPermissions = _permissions
|
||||
.GroupBy(p => string.IsNullOrEmpty(p.Category) ? "General" : p.Category)
|
||||
@@ -107,6 +128,31 @@ else
|
||||
}
|
||||
finally { _loading = false; }
|
||||
}
|
||||
|
||||
private void SetPermission(string role, string permission, bool enabled)
|
||||
{
|
||||
if (!_selectedPermissions.TryGetValue(role, out var selected)) return;
|
||||
if (enabled) selected.Add(permission);
|
||||
else selected.Remove(permission);
|
||||
}
|
||||
|
||||
private async Task SavePermissions(string role)
|
||||
{
|
||||
if (!_selectedPermissions.TryGetValue(role, out var selected)) return;
|
||||
_savingRole = role;
|
||||
try
|
||||
{
|
||||
if (!await Api.UpdateRolePermissionsAsync(role, selected.Order(StringComparer.Ordinal).ToArray()))
|
||||
{
|
||||
Snackbar.Add(Text["AdminClaims_SaveFailed"], Severity.Error);
|
||||
return;
|
||||
}
|
||||
Snackbar.Add(Text["AdminClaims_Saved"], Severity.Success);
|
||||
await LoadData();
|
||||
}
|
||||
catch { Snackbar.Add(Text["AdminClaims_SaveFailed"], Severity.Error); }
|
||||
finally { _savingRole = null; }
|
||||
}
|
||||
private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged);
|
||||
public void Dispose() => Language.LanguageChanged -= OnLanguageChanged;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
@layout MainLayout
|
||||
@implements IDisposable
|
||||
@using Enable2faResponse = Heimdall.Application.DTOs.Enable2faResponse
|
||||
@using Complete2faSetupResponse = Heimdall.Application.DTOs.Complete2faSetupResponse
|
||||
@inject HeimdallApiClient Api
|
||||
@inject AuthState Auth
|
||||
@inject UiLanguageService Language
|
||||
@@ -105,6 +106,12 @@ else if (_profile is not null)
|
||||
@if (_toggling2fa) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
@Text["DisableTwoFactor"]
|
||||
</MudButton>
|
||||
@if (_confirmDisable2fa)
|
||||
{
|
||||
<MudTextField @bind-Value="_disable2faPassword" Label='@Text["CurrentPassword"]' InputType="InputType.Password" Variant="Variant.Outlined" Class="mt-2" />
|
||||
<MudButton Color="Color.Error" Variant="Variant.Filled" Class="mt-2" Disabled="@_toggling2fa" OnClick="ConfirmDisable2fa">@Text["ConfirmDisableTwoFactor"]</MudButton>
|
||||
<MudButton Variant="Variant.Text" Class="mt-2" OnClick="CancelDisable2fa">@Text["Cancel"]</MudButton>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -113,6 +120,12 @@ else if (_profile is not null)
|
||||
@if (_toggling2fa) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
@Text["EnableTwoFactor"]
|
||||
</MudButton>
|
||||
@if (_confirmEnable2fa)
|
||||
{
|
||||
<MudTextField @bind-Value="_enable2faPassword" Label='@Text["CurrentPassword"]' InputType="InputType.Password" Variant="Variant.Outlined" Class="mt-2" />
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" Class="mt-2" Disabled="@_toggling2fa" OnClick="StartEnable2fa">@Text["ConfirmTwoFactor"]</MudButton>
|
||||
<MudButton Variant="Variant.Text" Class="mt-2" OnClick="CancelEnable2fa">@Text["Cancel"]</MudButton>
|
||||
}
|
||||
}
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
@@ -285,7 +298,7 @@ else if (_profile is not null)
|
||||
}
|
||||
</MudAlert>
|
||||
|
||||
@if (_2faSetup.RecoveryCodes is { Count: > 0 })
|
||||
@if (_completed2faSetup is { RecoveryCodes.Count: > 0 })
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning" Variant="Variant.Outlined" Class="mb-2">
|
||||
<MudText Typo="Typo.body2" Class="mb-1">
|
||||
@@ -295,7 +308,7 @@ else if (_profile is not null)
|
||||
</MudAlert>
|
||||
<MudPaper Elevation="0" Class="pa-3 mb-4" Style="border: 1px dashed #f0ad4e; border-radius: 8px;">
|
||||
<div class="d-flex flex-wrap">
|
||||
@foreach (var rc in _2faSetup.RecoveryCodes)
|
||||
@foreach (var rc in _completed2faSetup.RecoveryCodes)
|
||||
{
|
||||
<MudText Typo="Typo.subtitle1" Class="d-inline mr-4 mb-2" Style="font-family: monospace;">
|
||||
@rc
|
||||
@@ -303,12 +316,17 @@ else if (_profile is not null)
|
||||
}
|
||||
</div>
|
||||
</MudPaper>
|
||||
<MudCheckBox T="bool" @bind-Value="_recoveryCodesConfirmed" Label="@Text["RecoveryCodesSaved"]" Class="mb-2" />
|
||||
<MudCheckBox T="bool" @bind-Value="_recoveryCodesConfirmed" Label='@Text["RecoveryCodesSaved"]' Class="mb-2" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTextField @bind-Value="_authenticatorCode" Label='@Text["AuthenticatorCode"]' Variant="Variant.Outlined" />
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" Class="mt-2" Disabled="@_toggling2fa" OnClick="ConfirmEnable2fa">@Text["ConfirmTwoFactor"]</MudButton>
|
||||
}
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _show2faDialog = false)">@Text["Close"]</MudButton>
|
||||
<MudButton Variant="Variant.Text" OnClick="Close2faDialog" Disabled="@(_completed2faSetup is not null && !_recoveryCodesConfirmed)">@Text["Close"]</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
|
||||
@@ -333,8 +351,14 @@ else if (_profile is not null)
|
||||
|
||||
// Section 2FA
|
||||
private bool _toggling2fa;
|
||||
private bool _confirmDisable2fa;
|
||||
private string _disable2faPassword = "";
|
||||
private bool _confirmEnable2fa;
|
||||
private string _enable2faPassword = "";
|
||||
private bool _show2faDialog;
|
||||
private Enable2faResponse? _2faSetup;
|
||||
private Complete2faSetupResponse? _completed2faSetup;
|
||||
private string _authenticatorCode = "";
|
||||
private string? _2faError;
|
||||
private bool _recoveryCodesConfirmed;
|
||||
|
||||
@@ -404,21 +428,55 @@ else if (_profile is not null)
|
||||
|
||||
// ─── Section 3: Changer le mot de passe ───────────────────────
|
||||
|
||||
private async Task Enable2fa()
|
||||
private Task Enable2fa()
|
||||
{
|
||||
_confirmEnable2fa = true;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void CancelEnable2fa()
|
||||
{
|
||||
_confirmEnable2fa = false;
|
||||
_enable2faPassword = "";
|
||||
}
|
||||
|
||||
private async Task StartEnable2fa()
|
||||
{
|
||||
_toggling2fa = true;
|
||||
_2faError = null;
|
||||
_2faSetup = null;
|
||||
_completed2faSetup = null;
|
||||
_authenticatorCode = "";
|
||||
_recoveryCodesConfirmed = false;
|
||||
var currentPassword = _enable2faPassword;
|
||||
_confirmEnable2fa = false;
|
||||
try
|
||||
{
|
||||
var setup = await Api.Enable2faAsync();
|
||||
var setup = await Api.Enable2faAsync(currentPassword);
|
||||
if (setup is null)
|
||||
{
|
||||
_2faError = Text["OperationFailed"];
|
||||
_show2faDialog = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// ResetAuthenticatorKeyAsync rotates the security stamp. Reissue both
|
||||
// the Blazor token state and middleware cookie before confirming setup.
|
||||
var renewedSession = await Api.LoginAsync(_profile!.Email, currentPassword);
|
||||
if (renewedSession is null || string.IsNullOrEmpty(renewedSession.AccessToken))
|
||||
{
|
||||
_2faError = Text["OperationFailed"];
|
||||
_show2faDialog = true;
|
||||
return;
|
||||
}
|
||||
await AuthProvider.NotifyLoginAsync(renewedSession);
|
||||
if (!await AuthHelper.SignInAsync(JS, AuthHelper.CreateSignInPayload(renewedSession.AccessToken)))
|
||||
{
|
||||
_2faError = Text["OperationFailed"];
|
||||
_show2faDialog = true;
|
||||
return;
|
||||
}
|
||||
|
||||
_2faSetup = setup;
|
||||
_show2faDialog = true;
|
||||
}
|
||||
@@ -429,17 +487,59 @@ else if (_profile is not null)
|
||||
}
|
||||
finally
|
||||
{
|
||||
_enable2faPassword = "";
|
||||
_toggling2fa = false;
|
||||
await LoadProfile();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task Disable2fa()
|
||||
private void Close2faDialog()
|
||||
{
|
||||
_show2faDialog = false;
|
||||
_2faSetup = null;
|
||||
_completed2faSetup = null;
|
||||
_authenticatorCode = "";
|
||||
_recoveryCodesConfirmed = false;
|
||||
}
|
||||
|
||||
private async Task ConfirmEnable2fa()
|
||||
{
|
||||
_toggling2fa = true;
|
||||
try
|
||||
{
|
||||
var ok = await Api.Disable2faAsync();
|
||||
var completed = await Api.ConfirmEnable2faAsync(_authenticatorCode);
|
||||
if (completed is null)
|
||||
{
|
||||
_2faError = "Code invalide ou activation impossible";
|
||||
return;
|
||||
}
|
||||
_completed2faSetup = completed;
|
||||
_2faError = null;
|
||||
}
|
||||
catch { _2faError = Text["OperationFailed"]; }
|
||||
finally { _toggling2fa = false; await LoadProfile(); }
|
||||
}
|
||||
|
||||
private Task Disable2fa()
|
||||
{
|
||||
_confirmDisable2fa = true;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void CancelDisable2fa()
|
||||
{
|
||||
_confirmDisable2fa = false;
|
||||
_disable2faPassword = "";
|
||||
}
|
||||
|
||||
private async Task ConfirmDisable2fa()
|
||||
{
|
||||
_toggling2fa = true;
|
||||
var disabled = false;
|
||||
try
|
||||
{
|
||||
var ok = await Api.Disable2faAsync(_disable2faPassword);
|
||||
disabled = ok;
|
||||
if (ok)
|
||||
{
|
||||
Snackbar.Add(Text["TwoFactorDisabled"], Severity.Success);
|
||||
@@ -456,6 +556,7 @@ else if (_profile is not null)
|
||||
finally
|
||||
{
|
||||
_toggling2fa = false;
|
||||
if (disabled) CancelDisable2fa();
|
||||
await LoadProfile();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,12 +4,12 @@ using Heimdall.Application.Auth.Commands.Login;
|
||||
using Heimdall.Application.Auth.Commands.Verify2fa;
|
||||
using Heimdall.Application.Auth.Commands.RefreshToken;
|
||||
using Heimdall.Application.Auth.Commands.ChangePassword;
|
||||
using Heimdall.Application.Auth.Commands.RegisterAdmin;
|
||||
using Heimdall.Application.Auth.Commands.ConfirmEmail;
|
||||
using Heimdall.Application.Auth.Commands.ForgotPassword;
|
||||
using Heimdall.Application.Auth.Commands.ResetPassword;
|
||||
using Heimdall.Application.Auth.Commands.Enable2fa;
|
||||
using Heimdall.Application.Auth.Commands.Disable2fa;
|
||||
using Heimdall.Application.Auth.Commands.Complete2faSetup;
|
||||
using Heimdall.Application.Auth.Commands.Logout;
|
||||
using Heimdall.Application.Auth.Queries;
|
||||
using Heimdall.Application.Common;
|
||||
@@ -57,7 +57,7 @@ public class AuthController : ControllerBase
|
||||
if (result.IsSuccess)
|
||||
return Ok(result.Data);
|
||||
|
||||
_logger.LogWarning("First administrator setup failed for {Email}: {Error}", request.Email, result.Error);
|
||||
_logger.LogWarning("First administrator setup failed with status {StatusCode}", result.StatusCode);
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
@@ -68,17 +68,17 @@ public class AuthController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Login attempt for {Email}", request.Email);
|
||||
_logger.LogInformation("Login attempt received");
|
||||
var command = new LoginCommand(request.Email, request.Password);
|
||||
var result = await _mediator.Send(command, ct);
|
||||
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
_logger.LogInformation("Login successful for {Email}", request.Email);
|
||||
_logger.LogInformation("Login succeeded");
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
_logger.LogWarning("Login failed for {Email}: {Error}", request.Email, result.Error);
|
||||
_logger.LogWarning("Login failed with status {StatusCode}", result.StatusCode);
|
||||
return StatusCode(result.StatusCode ?? 401, new { error = result.Error });
|
||||
}
|
||||
|
||||
@@ -154,34 +154,12 @@ public class AuthController : ControllerBase
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Register an admin user. Requires Admin role + feature flag auth.admin-registration.enabled.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = "AdminUsers")]
|
||||
[HttpPost("register-admin")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> RegisterAdmin([FromBody] RegisterRequest request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("RegisterAdmin attempt for {Email}", request.Email);
|
||||
var command = new RegisterAdminCommand(request.Email, request.Password, request.DisplayName);
|
||||
var result = await _mediator.Send(command, ct);
|
||||
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
_logger.LogInformation("Admin user registered successfully: {Email}", request.Email);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
_logger.LogWarning("Admin registration failed for {Email}: {Error}", request.Email, result.Error);
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Enable 2FA for the current user. Returns the shared key and QR code URI for setup.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies")]
|
||||
[HttpPost("2fa/enable")]
|
||||
[ProducesResponseType(typeof(Enable2faResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Enable2fa(CancellationToken ct)
|
||||
public async Task<IActionResult> Enable2fa([FromBody] Enable2faRequest request, CancellationToken ct)
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
|
||||
@@ -191,11 +169,11 @@ public class AuthController : ControllerBase
|
||||
}
|
||||
|
||||
_logger.LogInformation("2FA enable attempt for user {UserId}", userId);
|
||||
var result = await _mediator.Send(new Enable2faCommand(userId), ct);
|
||||
var result = await _mediator.Send(new Enable2faCommand(userId, request.CurrentPassword), ct);
|
||||
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
_logger.LogInformation("2FA enabled successfully for user {UserId}", userId);
|
||||
_logger.LogInformation("Authenticator setup initialized; code confirmation is required");
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
@@ -203,12 +181,25 @@ public class AuthController : ControllerBase
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Confirm authenticator setup and return one-time recovery codes.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies")]
|
||||
[EnableRateLimiting("TwoFactor")]
|
||||
[HttpPost("2fa/enable/confirm")]
|
||||
[ProducesResponseType(typeof(Complete2faSetupResponse), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> ConfirmEnable2fa([FromBody] Complete2faSetupRequest request, CancellationToken ct)
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (!Guid.TryParse(userIdClaim, out var userId)) return Unauthorized();
|
||||
var result = await _mediator.Send(new Complete2faSetupCommand(userId, request.Code), ct);
|
||||
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Disable 2FA for the current user.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies")]
|
||||
[HttpPost("2fa/disable")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Disable2fa(CancellationToken ct)
|
||||
public async Task<IActionResult> Disable2fa([FromBody] Disable2faRequest request, CancellationToken ct)
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
|
||||
@@ -218,7 +209,7 @@ public class AuthController : ControllerBase
|
||||
}
|
||||
|
||||
_logger.LogInformation("2FA disable attempt for user {UserId}", userId);
|
||||
var result = await _mediator.Send(new Disable2faCommand(userId), ct);
|
||||
var result = await _mediator.Send(new Disable2faCommand(userId, request.CurrentPassword), ct);
|
||||
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
@@ -260,7 +251,7 @@ public class AuthController : ControllerBase
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> ForgotPassword([FromBody] ForgotPasswordRequest request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("ForgotPassword request for {Email}", request.Email);
|
||||
_logger.LogInformation("Password reset request received");
|
||||
await _mediator.Send(new ForgotPasswordCommand(request.Email), ct);
|
||||
return Ok(new { message = "If the email exists, a reset link has been sent." });
|
||||
}
|
||||
@@ -272,16 +263,16 @@ public class AuthController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordRequest request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("ResetPassword attempt for {Email}", request.Email);
|
||||
_logger.LogInformation("Password reset completion requested");
|
||||
var result = await _mediator.Send(new ResetPasswordCommand(request.Email, request.Token, request.NewPassword), ct);
|
||||
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
_logger.LogInformation("Password reset successfully for {Email}", request.Email);
|
||||
_logger.LogInformation("Password reset completed successfully");
|
||||
return Ok(new { message = "Password reset successfully" });
|
||||
}
|
||||
|
||||
_logger.LogWarning("Password reset failed for {Email}: {Error}", request.Email, result.Error);
|
||||
_logger.LogWarning("Password reset failed with status {StatusCode}", result.StatusCode);
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Heimdall.Application.Services;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
@@ -10,6 +12,7 @@ public record RoleResponse(string Name, IReadOnlyList<string> Permissions);
|
||||
|
||||
/// <summary>Response DTO for a list of roles.</summary>
|
||||
public record RolesListResponse(IReadOnlyList<RoleResponse> Roles);
|
||||
public record UpdateRolePermissionsRequest(IReadOnlyList<string> Permissions);
|
||||
|
||||
[ApiController]
|
||||
[Route("api/roles")]
|
||||
@@ -17,16 +20,18 @@ public record RolesListResponse(IReadOnlyList<RoleResponse> Roles);
|
||||
[EnableRateLimiting("Api")]
|
||||
public class RolesController : ControllerBase
|
||||
{
|
||||
private readonly IRolePermissionService _permissions;
|
||||
|
||||
public RolesController(IRolePermissionService permissions) => _permissions = permissions;
|
||||
|
||||
/// <summary>Returns all roles with their associated permissions.</summary>
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(RolesListResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public IActionResult List()
|
||||
public async Task<IActionResult> List(CancellationToken ct)
|
||||
{
|
||||
var roles = AppPermissions.RolePermissions
|
||||
.Select(kvp => new RoleResponse(kvp.Key, kvp.Value))
|
||||
.ToList();
|
||||
|
||||
var roles = (await _permissions.GetAllAsync(ct).ConfigureAwait(false))
|
||||
.Select(role => new RoleResponse(role.Name, role.Permissions)).ToList();
|
||||
return Ok(new RolesListResponse(roles));
|
||||
}
|
||||
|
||||
@@ -35,11 +40,26 @@ public class RolesController : ControllerBase
|
||||
[ProducesResponseType(typeof(RoleResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public IActionResult GetByName(string name)
|
||||
public async Task<IActionResult> GetByName(string name, CancellationToken ct)
|
||||
{
|
||||
if (!AppPermissions.RolePermissions.TryGetValue(name, out var permissions))
|
||||
var role = (await _permissions.GetAllAsync(ct).ConfigureAwait(false))
|
||||
.FirstOrDefault(r => string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase));
|
||||
if (role is null)
|
||||
return NotFound(new { error = $"Role '{name}' not found" });
|
||||
return Ok(new RoleResponse(role.Name, role.Permissions));
|
||||
}
|
||||
|
||||
return Ok(new RoleResponse(name, permissions));
|
||||
/// <summary>Replace the permission set for a non-Admin role.</summary>
|
||||
[HttpPut("{name}/permissions")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> UpdatePermissions(string name,
|
||||
[FromBody] UpdateRolePermissionsRequest request, CancellationToken ct)
|
||||
{
|
||||
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
|
||||
var result = await _permissions.SetPermissionsAsync(name, request.Permissions, actorId, ct)
|
||||
.ConfigureAwait(false);
|
||||
return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user