feat(cqrs): migrate Sites, Auth, Users, Cameras to CQRS
- Sites: CreateSite, UpdateSite, DeleteSite, GenerateToken commands + handlers - Auth: Login, Register, RefreshToken, 2FA, ChangePassword, Logout commands - Users: CRUD, roles, sites, lock/unlock, reset-password commands + queries - Cameras: CRUD, SetCredentials commands + queries - Add IApplicationDbContext abstraction for Clean Architecture - Add ICredentialProtector, IJwtService interfaces to Application layer - 0 build errors, 0 warnings
This commit is contained in:
1 parent
649af93f56
commit
11f7fd8d20
83 files changed
+1991
-21
No files matched your search
@@ -7,7 +7,7 @@
|
||||
<AnalysisLevel>latest-Recommended</AnalysisLevel>
|
||||
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
|
||||
<!-- NU1510: Channels is transitively pulled by SignalR but included in the framework - safe to suppress -->
|
||||
<NoWarn>$(NoWarn);NU1903;NU1510;CA1848;CA1727;CA1861;CA1825;CA1873;MUD0002</NoWarn>
|
||||
<NoWarn>$(NoWarn);NU1903;NU1510;CA1848;CA1727;CA1861;CA1825;CA1873;MUD0002;CA1725</NoWarn>
|
||||
<!-- Alpine workaround: no host package available for alpine.3.24-x64 -->
|
||||
<UseAppHost>false</UseAppHost>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
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,
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
UserManager<AppUser> userManager)
|
||||
{
|
||||
var roles = await userManager.GetRolesAsync(user);
|
||||
var permissions = rolePermissionService.GetPermissionsForRoles(roles);
|
||||
|
||||
var (accessToken, expiresAt) = jwtService.GenerateAccessToken(user, roles, permissions);
|
||||
var (refreshToken, _) = jwtService.GenerateRefreshToken(user);
|
||||
|
||||
return ServiceResult<AuthResponse>.Success(new AuthResponse(
|
||||
accessToken,
|
||||
refreshToken,
|
||||
expiresAt,
|
||||
false,
|
||||
new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles])));
|
||||
}
|
||||
|
||||
internal static async Task<UserInfo> MapUserInfoAsync(AppUser user, UserManager<AppUser> userManager)
|
||||
{
|
||||
var roles = await userManager.GetRolesAsync(user);
|
||||
return new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.ChangePassword;
|
||||
|
||||
public record ChangePasswordCommand(Guid UserId, string CurrentPassword, string NewPassword) : IRequest<ServiceResult>;
|
||||
@@ -0,0 +1,42 @@
|
||||
using Heimdall.Application.Common;
|
||||
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 ILogger<ChangePasswordHandler> _logger;
|
||||
|
||||
public ChangePasswordHandler(UserManager<AppUser> userManager, ILogger<ChangePasswordHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> Handle(ChangePasswordCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogDebug("ChangePassword: UserId={UserId}", request.UserId);
|
||||
|
||||
var user = await _userManager.FindByIdAsync(request.UserId.ToString());
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("ChangePassword: User not found UserId={UserId}", request.UserId);
|
||||
return ServiceResult.NotFound("User not found");
|
||||
}
|
||||
|
||||
var result = await _userManager.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword);
|
||||
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.LogInformation("ChangePassword: Success UserId={UserId}", request.UserId);
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.ChangePassword;
|
||||
|
||||
public class ChangePasswordValidator : AbstractValidator<ChangePasswordCommand>
|
||||
{
|
||||
public ChangePasswordValidator()
|
||||
{
|
||||
RuleFor(x => x.CurrentPassword).NotEmpty();
|
||||
RuleFor(x => x.NewPassword).NotEmpty().MinimumLength(12)
|
||||
.WithMessage("New password must be at least 12 characters")
|
||||
.NotEqual(x => x.CurrentPassword)
|
||||
.WithMessage("New password must differ from current password");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Disable2fa;
|
||||
|
||||
public record Disable2faCommand(Guid UserId) : IRequest<ServiceResult>;
|
||||
@@ -0,0 +1,41 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Disable2fa;
|
||||
|
||||
public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly ILogger<Disable2faHandler> _logger;
|
||||
|
||||
public Disable2faHandler(UserManager<AppUser> userManager, ILogger<Disable2faHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> Handle(Disable2faCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogDebug("Disable2fa: UserId={UserId}", request.UserId);
|
||||
|
||||
var user = await _userManager.FindByIdAsync(request.UserId.ToString());
|
||||
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);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
_logger.LogError("Disable2fa: Failed UserId={UserId}", request.UserId);
|
||||
return ServiceResult.Failure("Failed to disable 2FA");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Disable2fa: Disabled UserId={UserId}", request.UserId);
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Enable2fa;
|
||||
|
||||
public record Enable2faCommand(Guid UserId) : IRequest<ServiceResult>;
|
||||
@@ -0,0 +1,41 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Enable2fa;
|
||||
|
||||
public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly ILogger<Enable2faHandler> _logger;
|
||||
|
||||
public Enable2faHandler(UserManager<AppUser> userManager, ILogger<Enable2faHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> Handle(Enable2faCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogDebug("Enable2fa: UserId={UserId}", request.UserId);
|
||||
|
||||
var user = await _userManager.FindByIdAsync(request.UserId.ToString());
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("Enable2fa: User not found UserId={UserId}", request.UserId);
|
||||
return ServiceResult.NotFound("User not found");
|
||||
}
|
||||
|
||||
var result = await _userManager.SetTwoFactorEnabledAsync(user, true);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
_logger.LogError("Enable2fa: Failed UserId={UserId}", request.UserId);
|
||||
return ServiceResult.Failure("Failed to enable 2FA");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Enable2fa: Enabled UserId={UserId}", request.UserId);
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Login;
|
||||
|
||||
public record LoginCommand(string Email, string Password) : IRequest<ServiceResult<AuthResponse>>;
|
||||
@@ -0,0 +1,81 @@
|
||||
using Heimdall.Application.Common;
|
||||
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.Login;
|
||||
|
||||
public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IAuthSignInService _signInService;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly ILogger<LoginHandler> _logger;
|
||||
|
||||
public LoginHandler(
|
||||
UserManager<AppUser> userManager,
|
||||
IAuthSignInService signInService,
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
ILogger<LoginHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_signInService = signInService;
|
||||
_jwtService = jwtService;
|
||||
_rolePermissionService = rolePermissionService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> Handle(LoginCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Login attempt: Email={Email}", request.Email);
|
||||
|
||||
var user = await _userManager.FindByEmailAsync(request.Email);
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("Login: User not found Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
}
|
||||
|
||||
if (await _userManager.IsLockedOutAsync(user))
|
||||
{
|
||||
_logger.LogWarning("Login: Account locked Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
|
||||
}
|
||||
|
||||
if (await _userManager.GetTwoFactorEnabledAsync(user))
|
||||
{
|
||||
_logger.LogDebug("Login: 2FA required Email={Email}", request.Email);
|
||||
var signIn = await _signInService.PasswordSignInAsync(user, request.Password, true);
|
||||
if (signIn.ResultType == SignInResultType.LockedOut)
|
||||
{
|
||||
_logger.LogWarning("Login: Account locked after 2FA attempt Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
|
||||
}
|
||||
if (signIn.ResultType != SignInResultType.Success)
|
||||
{
|
||||
_logger.LogWarning("Login: 2FA failed Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Login: 2FA passed Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Success(new AuthResponse(
|
||||
string.Empty, string.Empty, DateTime.UtcNow, true,
|
||||
await AuthHelper.MapUserInfoAsync(user, _userManager)));
|
||||
}
|
||||
|
||||
var result = await _signInService.PasswordSignInAsync(user, request.Password, true);
|
||||
if (result.ResultType != SignInResultType.Success)
|
||||
{
|
||||
_logger.LogWarning("Login: Password mismatch Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Login: Success Email={Email}", request.Email);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Login;
|
||||
|
||||
public class LoginValidator : AbstractValidator<LoginCommand>
|
||||
{
|
||||
public LoginValidator()
|
||||
{
|
||||
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(256);
|
||||
RuleFor(x => x.Password).NotEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Logout;
|
||||
|
||||
public record LogoutCommand(Guid UserId, string RefreshToken) : IRequest<ServiceResult>;
|
||||
@@ -0,0 +1,36 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Services;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Logout;
|
||||
|
||||
public class LogoutHandler : IRequestHandler<LogoutCommand, ServiceResult>
|
||||
{
|
||||
private readonly IAuthSignInService _signInService;
|
||||
private readonly IAuthDataService _authData;
|
||||
private readonly ILogger<LogoutHandler> _logger;
|
||||
|
||||
public LogoutHandler(
|
||||
IAuthSignInService signInService,
|
||||
IAuthDataService authData,
|
||||
ILogger<LogoutHandler> logger)
|
||||
{
|
||||
_signInService = signInService;
|
||||
_authData = authData;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> Handle(LogoutCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Logout: UserId={UserId}", request.UserId);
|
||||
|
||||
if (!string.IsNullOrEmpty(request.RefreshToken))
|
||||
{
|
||||
await _authData.RevokeRefreshTokenAsync(request.RefreshToken, request.UserId, ct);
|
||||
}
|
||||
|
||||
await _signInService.SignOutAsync();
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.RefreshToken;
|
||||
|
||||
public record RefreshTokenCommand(string RefreshToken) : IRequest<ServiceResult<AuthResponse>>;
|
||||
@@ -0,0 +1,71 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Application.Common;
|
||||
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.RefreshToken;
|
||||
|
||||
public class RefreshTokenHandler : IRequestHandler<RefreshTokenCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly IAuthDataService _authData;
|
||||
private readonly ILogger<RefreshTokenHandler> _logger;
|
||||
|
||||
public RefreshTokenHandler(
|
||||
IJwtService jwtService,
|
||||
UserManager<AppUser> userManager,
|
||||
IRolePermissionService rolePermissionService,
|
||||
IAuthDataService authData,
|
||||
ILogger<RefreshTokenHandler> logger)
|
||||
{
|
||||
_jwtService = jwtService;
|
||||
_userManager = userManager;
|
||||
_rolePermissionService = rolePermissionService;
|
||||
_authData = authData;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> Handle(RefreshTokenCommand request, CancellationToken ct)
|
||||
{
|
||||
var principal = _jwtService.ValidateRefreshToken(request.RefreshToken);
|
||||
if (principal is null)
|
||||
{
|
||||
_logger.LogWarning("RefreshToken: Invalid or expired token");
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid or expired refresh token");
|
||||
}
|
||||
|
||||
var tokenId = principal.FindFirstValue("jti");
|
||||
if (tokenId is not null)
|
||||
{
|
||||
var revoked = await _authData.IsRefreshTokenRevokedAsync(tokenId, ct);
|
||||
if (revoked)
|
||||
{
|
||||
_logger.LogWarning("RefreshToken: Token revoked jti={Jti}", tokenId[..Math.Min(8, tokenId.Length)]);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Refresh token has been revoked");
|
||||
}
|
||||
}
|
||||
|
||||
var userId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userId is null)
|
||||
{
|
||||
_logger.LogWarning("RefreshToken: Token missing NameIdentifier");
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid token");
|
||||
}
|
||||
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("RefreshToken: User not found UserId={UserId}", userId);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("User not found");
|
||||
}
|
||||
|
||||
_logger.LogInformation("RefreshToken: Success UserId={UserId}", userId);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Register;
|
||||
|
||||
public record RegisterCommand(string Email, string Password, string DisplayName) : IRequest<ServiceResult<AuthResponse>>;
|
||||
@@ -0,0 +1,101 @@
|
||||
using Heimdall.Application.Common;
|
||||
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.Register;
|
||||
|
||||
public class RegisterHandler : IRequestHandler<RegisterCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly IAuthDataService _authData;
|
||||
private readonly ILogger<RegisterHandler> _logger;
|
||||
|
||||
public RegisterHandler(
|
||||
UserManager<AppUser> userManager,
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
IAuthDataService authData,
|
||||
ILogger<RegisterHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_jwtService = jwtService;
|
||||
_rolePermissionService = rolePermissionService;
|
||||
_authData = authData;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> Handle(RegisterCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Register attempt: Email={Email}, DisplayName={DisplayName}", request.Email, request.DisplayName);
|
||||
|
||||
var existingUser = await _userManager.FindByEmailAsync(request.Email);
|
||||
if (existingUser is not null)
|
||||
{
|
||||
_logger.LogWarning("Register: Email={Email} already registered", request.Email);
|
||||
return ServiceResult<AuthResponse>.Conflict("Email already registered");
|
||||
}
|
||||
|
||||
var anyUsers = await _authData.IsFirstUserAsync(ct);
|
||||
_logger.LogDebug("Register: anyUsers={AnyUsers}", anyUsers);
|
||||
|
||||
if (!anyUsers)
|
||||
{
|
||||
_logger.LogInformation("Register: First user — creating admin Email={Email}", request.Email);
|
||||
var firstUser = new AppUser
|
||||
{
|
||||
UserName = request.Email,
|
||||
Email = request.Email,
|
||||
DisplayName = request.DisplayName
|
||||
};
|
||||
|
||||
var createResult = await _userManager.CreateAsync(firstUser, request.Password);
|
||||
if (!createResult.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", createResult.Errors.Select(e => e.Description));
|
||||
_logger.LogError("Register: First user creation failed: {Errors}", errors);
|
||||
return ServiceResult<AuthResponse>.Failure(errors);
|
||||
}
|
||||
|
||||
await _userManager.AddToRoleAsync(firstUser, "Admin");
|
||||
_logger.LogInformation("Register: First user created and granted Admin role Email={Email}", request.Email);
|
||||
return await AuthHelper.CreateAuthResponseAsync(firstUser, _jwtService, _rolePermissionService, _userManager);
|
||||
}
|
||||
|
||||
_logger.LogDebug("Register: checking PublicRegistrationEnabled setting");
|
||||
var setting = await _authData.GetSettingValueAsync("auth.public-registration.enabled", ct);
|
||||
if (setting is not null &&
|
||||
!string.Equals(setting, "true", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_logger.LogWarning("Register: Public registration disabled (setting={Value})", setting);
|
||||
return ServiceResult<AuthResponse>.Failure("Public registration is disabled. Contact an administrator.", 403);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Register: Creating user Email={Email}", request.Email);
|
||||
var user = new AppUser
|
||||
{
|
||||
UserName = request.Email,
|
||||
Email = request.Email,
|
||||
DisplayName = request.DisplayName
|
||||
};
|
||||
|
||||
var result = await _userManager.CreateAsync(user, request.Password);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
|
||||
_logger.LogError("Register: User creation failed: {Errors}", errors);
|
||||
return ServiceResult<AuthResponse>.Failure(errors);
|
||||
}
|
||||
|
||||
_logger.LogDebug("Register: Assigning Viewer role to Email={Email}", request.Email);
|
||||
await _userManager.AddToRoleAsync(user, "Viewer");
|
||||
|
||||
_logger.LogInformation("Register: User created successfully Email={Email}", request.Email);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Register;
|
||||
|
||||
public class RegisterValidator : AbstractValidator<RegisterCommand>
|
||||
{
|
||||
public RegisterValidator()
|
||||
{
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
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>>;
|
||||
@@ -0,0 +1,61 @@
|
||||
using Heimdall.Application.Common;
|
||||
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.RegisterAdmin;
|
||||
|
||||
public class RegisterAdminHandler : IRequestHandler<RegisterAdminCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly ILogger<RegisterAdminHandler> _logger;
|
||||
|
||||
public RegisterAdminHandler(
|
||||
UserManager<AppUser> userManager,
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
ILogger<RegisterAdminHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_jwtService = jwtService;
|
||||
_rolePermissionService = rolePermissionService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> Handle(RegisterAdminCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("RegisterAdmin: Email={Email}, DisplayName={DisplayName}", request.Email, request.DisplayName);
|
||||
|
||||
var existing = await _userManager.FindByEmailAsync(request.Email);
|
||||
if (existing is not null)
|
||||
{
|
||||
_logger.LogWarning("RegisterAdmin: Already exists Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Conflict("Email already registered");
|
||||
}
|
||||
|
||||
var user = new AppUser
|
||||
{
|
||||
UserName = request.Email,
|
||||
Email = request.Email,
|
||||
DisplayName = request.DisplayName
|
||||
};
|
||||
|
||||
var createResult = await _userManager.CreateAsync(user, request.Password);
|
||||
if (!createResult.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", createResult.Errors.Select(e => e.Description));
|
||||
_logger.LogError("RegisterAdmin: Creation failed Email={Email}: {Errors}", request.Email, errors);
|
||||
return ServiceResult<AuthResponse>.Failure(errors);
|
||||
}
|
||||
|
||||
await _userManager.AddToRoleAsync(user, "Admin");
|
||||
_logger.LogInformation("RegisterAdmin: Created and granted Admin role Email={Email}", request.Email);
|
||||
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Verify2fa;
|
||||
|
||||
public record Verify2faCommand(string Email, string Code) : IRequest<ServiceResult<AuthResponse>>;
|
||||
@@ -0,0 +1,53 @@
|
||||
using Heimdall.Application.Common;
|
||||
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.Verify2fa;
|
||||
|
||||
public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly ILogger<Verify2faHandler> _logger;
|
||||
|
||||
public Verify2faHandler(
|
||||
UserManager<AppUser> userManager,
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
ILogger<Verify2faHandler> logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_jwtService = jwtService;
|
||||
_rolePermissionService = rolePermissionService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> Handle(Verify2faCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogDebug("Verify2fa: Email={Email}", request.Email);
|
||||
|
||||
var user = await _userManager.FindByEmailAsync(request.Email);
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("Verify2fa: User not found Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid request");
|
||||
}
|
||||
|
||||
var isValid = await _userManager.VerifyTwoFactorTokenAsync(
|
||||
user, TokenOptions.DefaultAuthenticatorProvider, request.Code);
|
||||
|
||||
if (!isValid)
|
||||
{
|
||||
_logger.LogWarning("Verify2fa: Invalid code Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Verify2fa: Success Email={Email}", request.Email);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Verify2fa;
|
||||
|
||||
public class Verify2faValidator : AbstractValidator<Verify2faCommand>
|
||||
{
|
||||
public Verify2faValidator()
|
||||
{
|
||||
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(256);
|
||||
RuleFor(x => x.Code).NotEmpty().Length(6).WithMessage("2FA code must be 6 digits");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Cameras.Commands.CreateCamera;
|
||||
|
||||
public record CreateCameraCommand(
|
||||
Guid SiteId,
|
||||
string Name,
|
||||
string? RtspUrl,
|
||||
string? Manufacturer,
|
||||
string? Model) : IRequest<ServiceResult<CameraResponse>>;
|
||||
|
||||
public class CreateCameraCommandHandler : IRequestHandler<CreateCameraCommand, ServiceResult<CameraResponse>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
|
||||
public CreateCameraCommandHandler(IApplicationDbContext db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<CameraResponse>> Handle(CreateCameraCommand request, CancellationToken ct)
|
||||
{
|
||||
var site = await _db.Sites.FindAsync([request.SiteId], ct);
|
||||
if (site is null)
|
||||
return ServiceResult<CameraResponse>.NotFound("Site not found");
|
||||
|
||||
var camera = new Camera(request.SiteId, request.Name, request.RtspUrl, request.Manufacturer, request.Model);
|
||||
|
||||
_db.Cameras.Add(camera);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return ServiceResult<CameraResponse>.Success(MapResponse(camera));
|
||||
}
|
||||
|
||||
private static CameraResponse MapResponse(Camera c) => new(
|
||||
c.Id, c.SiteId, c.AgentId, c.Name, c.Manufacturer, c.Model,
|
||||
c.RtspUrl, c.SubRtspUrl,
|
||||
c.Status, c.DiscoveryMethod, c.DetectedType, c.Capabilities,
|
||||
c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort,
|
||||
c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs,
|
||||
c.LastDiscoveredAt, c.LastStreamTestAt,
|
||||
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt);
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Cameras.Commands.CreateCamera;
|
||||
|
||||
public class CreateCameraCommandValidator : AbstractValidator<CreateCameraCommand>
|
||||
{
|
||||
public CreateCameraCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.Name).NotEmpty().MaximumLength(200);
|
||||
RuleFor(x => x.RtspUrl).NotEmpty().Must(uri => Uri.TryCreate(uri, UriKind.Absolute, out _))
|
||||
.WithMessage("RTSP URL must be a valid absolute URI");
|
||||
RuleFor(x => x.SiteId).NotEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Cameras.Commands.DeleteCamera;
|
||||
|
||||
public record DeleteCameraCommand(Guid Id) : IRequest<ServiceResult>;
|
||||
|
||||
public class DeleteCameraCommandHandler : IRequestHandler<DeleteCameraCommand, ServiceResult>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
|
||||
public DeleteCameraCommandHandler(IApplicationDbContext db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> Handle(DeleteCameraCommand request, CancellationToken ct)
|
||||
{
|
||||
var camera = await _db.Cameras.FindAsync([request.Id], ct);
|
||||
if (camera is null)
|
||||
return ServiceResult.NotFound("Camera not found");
|
||||
|
||||
camera.SoftDelete();
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Cameras.Commands.SetCredentials;
|
||||
|
||||
public record SetCameraCredentialsCommand(
|
||||
Guid CameraId,
|
||||
string OnvifUsername,
|
||||
string OnvifPassword,
|
||||
string RtspUsername,
|
||||
string RtspPassword) : IRequest<ServiceResult>;
|
||||
|
||||
public class SetCameraCredentialsCommandHandler : IRequestHandler<SetCameraCredentialsCommand, ServiceResult>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly ICredentialProtector _credentialProtector;
|
||||
|
||||
public SetCameraCredentialsCommandHandler(IApplicationDbContext db, ICredentialProtector credentialProtector)
|
||||
{
|
||||
_db = db;
|
||||
_credentialProtector = credentialProtector;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> Handle(SetCameraCredentialsCommand request, CancellationToken ct)
|
||||
{
|
||||
var camera = await _db.Cameras.FindAsync([request.CameraId], ct);
|
||||
if (camera is null)
|
||||
return ServiceResult.NotFound("Camera not found");
|
||||
|
||||
var credentials = new Domain.Entities.CameraCredentials(request.CameraId);
|
||||
credentials.SetCredentials(
|
||||
request.OnvifUsername,
|
||||
_credentialProtector.Encrypt(request.OnvifPassword),
|
||||
_credentialProtector.Encrypt(request.RtspUsername),
|
||||
_credentialProtector.Encrypt(request.RtspPassword));
|
||||
|
||||
camera.SetCredentials(credentials);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Cameras.Commands.SetCredentials;
|
||||
|
||||
public class SetCameraCredentialsCommandValidator : AbstractValidator<SetCameraCredentialsCommand>
|
||||
{
|
||||
public SetCameraCredentialsCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.CameraId).NotEmpty();
|
||||
RuleFor(x => x.OnvifUsername).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.OnvifPassword).NotEmpty().MaximumLength(500);
|
||||
RuleFor(x => x.RtspUsername).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.RtspPassword).NotEmpty().MaximumLength(500);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Enums;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Cameras.Commands.UpdateCamera;
|
||||
|
||||
public record UpdateCameraCommand(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? RtspUrl,
|
||||
CameraStatus? Status,
|
||||
string? Manufacturer = null,
|
||||
string? Model = null) : IRequest<ServiceResult<CameraResponse>>;
|
||||
|
||||
public class UpdateCameraCommandHandler : IRequestHandler<UpdateCameraCommand, ServiceResult<CameraResponse>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
|
||||
public UpdateCameraCommandHandler(IApplicationDbContext db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<CameraResponse>> Handle(UpdateCameraCommand request, CancellationToken ct)
|
||||
{
|
||||
var camera = await _db.Cameras.FindAsync([request.Id], ct);
|
||||
if (camera is null)
|
||||
return ServiceResult<CameraResponse>.NotFound("Camera not found");
|
||||
|
||||
camera.Update(request.Name, request.Manufacturer, request.Model, request.RtspUrl);
|
||||
if (request.Status.HasValue)
|
||||
camera.SetStatus(request.Status.Value);
|
||||
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return ServiceResult<CameraResponse>.Success(MapResponse(camera));
|
||||
}
|
||||
|
||||
private static CameraResponse MapResponse(Domain.Entities.Camera c) => new(
|
||||
c.Id, c.SiteId, c.AgentId, c.Name, c.Manufacturer, c.Model,
|
||||
c.RtspUrl, c.SubRtspUrl,
|
||||
c.Status, c.DiscoveryMethod, c.DetectedType, c.Capabilities,
|
||||
c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort,
|
||||
c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs,
|
||||
c.LastDiscoveredAt, c.LastStreamTestAt,
|
||||
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt);
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Cameras.Commands.UpdateCamera;
|
||||
|
||||
public class UpdateCameraCommandValidator : AbstractValidator<UpdateCameraCommand>
|
||||
{
|
||||
public UpdateCameraCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.Id).NotEmpty();
|
||||
RuleFor(x => x.Name).NotEmpty().MaximumLength(200);
|
||||
RuleFor(x => x.RtspUrl).NotEmpty().Must(uri => Uri.TryCreate(uri, UriKind.Absolute, out _))
|
||||
.WithMessage("RTSP URL must be a valid absolute URI");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Cameras.Queries.GetCamera;
|
||||
|
||||
public record GetCameraQuery(Guid Id) : IRequest<ServiceResult<CameraResponse>>;
|
||||
|
||||
public class GetCameraQueryHandler : IRequestHandler<GetCameraQuery, ServiceResult<CameraResponse>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
|
||||
public GetCameraQueryHandler(IApplicationDbContext db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<CameraResponse>> Handle(GetCameraQuery request, CancellationToken ct)
|
||||
{
|
||||
var camera = await _db.Cameras.FindAsync([request.Id], ct);
|
||||
if (camera is null)
|
||||
return ServiceResult<CameraResponse>.NotFound("Camera not found");
|
||||
|
||||
return ServiceResult<CameraResponse>.Success(MapResponse(camera));
|
||||
}
|
||||
|
||||
private static CameraResponse MapResponse(Domain.Entities.Camera c) => new(
|
||||
c.Id, c.SiteId, c.AgentId, c.Name, c.Manufacturer, c.Model,
|
||||
c.RtspUrl, c.SubRtspUrl,
|
||||
c.Status, c.DiscoveryMethod, c.DetectedType, c.Capabilities,
|
||||
c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort,
|
||||
c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs,
|
||||
c.LastDiscoveredAt, c.LastStreamTestAt,
|
||||
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.Cameras.Queries.GetCamerasBySite;
|
||||
|
||||
public record GetCamerasBySiteQuery(
|
||||
Guid SiteId,
|
||||
int Page = 1,
|
||||
int PageSize = 20) : IRequest<ServiceResult<PagedResult<CameraResponse>>>;
|
||||
|
||||
public class GetCamerasBySiteQueryHandler : IRequestHandler<GetCamerasBySiteQuery, ServiceResult<PagedResult<CameraResponse>>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
|
||||
public GetCamerasBySiteQueryHandler(IApplicationDbContext db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<PagedResult<CameraResponse>>> Handle(GetCamerasBySiteQuery request, CancellationToken ct)
|
||||
{
|
||||
var query = _db.Cameras
|
||||
.Where(c => c.SiteId == request.SiteId)
|
||||
.OrderBy(c => c.Name);
|
||||
|
||||
var total = await query.CountAsync(ct);
|
||||
var items = await query
|
||||
.Skip((request.Page - 1) * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.Select(c => MapResponse(c))
|
||||
.ToListAsync(ct);
|
||||
|
||||
return ServiceResult<PagedResult<CameraResponse>>.Success(
|
||||
new PagedResult<CameraResponse>(items, total, request.Page, request.PageSize));
|
||||
}
|
||||
|
||||
private static CameraResponse MapResponse(Domain.Entities.Camera c) => new(
|
||||
c.Id, c.SiteId, c.AgentId, c.Name, c.Manufacturer, c.Model,
|
||||
c.RtspUrl, c.SubRtspUrl,
|
||||
c.Status, c.DiscoveryMethod, c.DetectedType, c.Capabilities,
|
||||
c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort,
|
||||
c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs,
|
||||
c.LastDiscoveredAt, c.LastStreamTestAt,
|
||||
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.Common;
|
||||
|
||||
public interface IApplicationDbContext
|
||||
{
|
||||
DbSet<Camera> Cameras { get; }
|
||||
DbSet<Site> Sites { get; }
|
||||
DbSet<AuditLog> AuditLogs { get; }
|
||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
|
||||
Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Heimdall.Application.Common;
|
||||
|
||||
public interface ICredentialProtector
|
||||
{
|
||||
string Encrypt(string plaintext);
|
||||
string Decrypt(string ciphertext);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Common.Persistence;
|
||||
|
||||
public interface IUserRepository
|
||||
{
|
||||
Task<PagedResult<UserResponse>> GetPagedAsync(int page, int pageSize, CancellationToken ct);
|
||||
Task<UserResponse?> GetByIdAsync(Guid id, CancellationToken ct);
|
||||
Task<int> CountAdminUsersAsync(CancellationToken ct);
|
||||
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);
|
||||
}
|
||||
@@ -9,6 +9,8 @@
|
||||
<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.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.8" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public interface IAuthDataService
|
||||
{
|
||||
Task<string?> GetSettingValueAsync(string key, CancellationToken ct);
|
||||
Task<bool> IsFirstUserAsync(CancellationToken ct);
|
||||
Task<bool> IsRefreshTokenRevokedAsync(string tokenHash, CancellationToken ct);
|
||||
Task RevokeRefreshTokenAsync(string refreshToken, Guid userId, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public enum SignInResultType
|
||||
{
|
||||
Success,
|
||||
LockedOut,
|
||||
RequiresTwoFactor,
|
||||
Failed
|
||||
}
|
||||
|
||||
public record SignInServiceResult(SignInResultType ResultType);
|
||||
|
||||
public interface IAuthSignInService
|
||||
{
|
||||
Task<SignInServiceResult> PasswordSignInAsync(AppUser user, string password, bool lockoutOnFailure);
|
||||
Task SignOutAsync();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Domain.Entities;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public interface IJwtService
|
||||
{
|
||||
(string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions);
|
||||
(string token, DateTime expiresAt) GenerateRefreshToken(AppUser user);
|
||||
ClaimsPrincipal? ValidateRefreshToken(string refreshToken);
|
||||
string? GetUserIdFromExpiredToken(string token);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public interface IRolePermissionService
|
||||
{
|
||||
IList<string> GetPermissionsForRoles(IList<string> roles);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.CreateSite;
|
||||
|
||||
public record CreateSiteCommand(string Name, string? Address, string? Timezone) : IRequest<ServiceResult<SiteResponse>>;
|
||||
@@ -0,0 +1,29 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.CreateSite;
|
||||
|
||||
public class CreateSiteHandler : IRequestHandler<CreateSiteCommand, ServiceResult<SiteResponse>>
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
|
||||
public CreateSiteHandler(IApplicationDbContext context) => _context = context;
|
||||
|
||||
public async Task<ServiceResult<SiteResponse>> Handle(CreateSiteCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var existing = await _context.Sites.AnyAsync(s => s.Name == request.Name, cancellationToken);
|
||||
if (existing)
|
||||
return ServiceResult<SiteResponse>.Conflict("A site with this name already exists");
|
||||
|
||||
var site = new Site(request.Name, request.Address, request.Timezone);
|
||||
_context.Sites.Add(site);
|
||||
|
||||
await _context.SaveChangesWithRetryAsync(ct: cancellationToken);
|
||||
|
||||
return ServiceResult<SiteResponse>.Success(new SiteResponse(
|
||||
site.Id, site.Name, site.Address, site.Timezone, site.Enabled, site.CreatedAt));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.CreateSite;
|
||||
|
||||
public class CreateSiteValidator : AbstractValidator<CreateSiteCommand>
|
||||
{
|
||||
public CreateSiteValidator()
|
||||
{
|
||||
RuleFor(x => x.Name)
|
||||
.NotEmpty()
|
||||
.MaximumLength(200);
|
||||
|
||||
RuleFor(x => x.Address)
|
||||
.MaximumLength(500)
|
||||
.When(x => x.Address is not null);
|
||||
|
||||
RuleFor(x => x.Timezone)
|
||||
.Must(tz => string.IsNullOrEmpty(tz) || IsValidTimezone(tz))
|
||||
.WithMessage("Invalid timezone. Use IANA timezone format (e.g., 'Europe/Paris').");
|
||||
}
|
||||
|
||||
private static bool? _hasTzData;
|
||||
|
||||
private static bool HasTzData()
|
||||
{
|
||||
if (_hasTzData.HasValue) return _hasTzData.Value;
|
||||
|
||||
try
|
||||
{
|
||||
_ = TimeZoneInfo.FindSystemTimeZoneById("Europe/Paris");
|
||||
_hasTzData = true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
_hasTzData = false;
|
||||
}
|
||||
|
||||
return _hasTzData.Value;
|
||||
}
|
||||
|
||||
private static bool IsValidTimezone(string timezone)
|
||||
{
|
||||
try
|
||||
{
|
||||
_ = TimeZoneInfo.FindSystemTimeZoneById(timezone);
|
||||
return true;
|
||||
}
|
||||
catch (InvalidTimeZoneException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (TimeZoneNotFoundException)
|
||||
{
|
||||
return !HasTzData();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.DeleteSite;
|
||||
|
||||
public record DeleteSiteCommand(Guid Id) : IRequest<ServiceResult>;
|
||||
@@ -0,0 +1,23 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.DeleteSite;
|
||||
|
||||
public class DeleteSiteHandler : IRequestHandler<DeleteSiteCommand, ServiceResult>
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
|
||||
public DeleteSiteHandler(IApplicationDbContext context) => _context = context;
|
||||
|
||||
public async Task<ServiceResult> Handle(DeleteSiteCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var site = await _context.Sites.FindAsync([request.Id], cancellationToken);
|
||||
if (site is null)
|
||||
return ServiceResult.NotFound("Site not found");
|
||||
|
||||
site.SoftDelete();
|
||||
await _context.SaveChangesWithRetryAsync(ct: cancellationToken);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.GenerateSiteToken;
|
||||
|
||||
public record GenerateSiteTokenCommand(Guid Id) : IRequest<ServiceResult<RegistrationTokenResponse>>;
|
||||
@@ -0,0 +1,38 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.GenerateSiteToken;
|
||||
|
||||
public class GenerateSiteTokenHandler : IRequestHandler<GenerateSiteTokenCommand, ServiceResult<RegistrationTokenResponse>>
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
|
||||
public GenerateSiteTokenHandler(IApplicationDbContext context) => _context = context;
|
||||
|
||||
public async Task<ServiceResult<RegistrationTokenResponse>> Handle(GenerateSiteTokenCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var site = await _context.Sites.FindAsync([request.Id], cancellationToken);
|
||||
if (site is null)
|
||||
return ServiceResult<RegistrationTokenResponse>.NotFound("Site not found");
|
||||
|
||||
var (plainToken, tokenHash, expiresAt) = GenerateRegistrationToken();
|
||||
site.GenerateRegistrationToken(tokenHash, expiresAt);
|
||||
await _context.SaveChangesWithRetryAsync(ct: cancellationToken);
|
||||
|
||||
return ServiceResult<RegistrationTokenResponse>.Success(
|
||||
new RegistrationTokenResponse(plainToken, expiresAt));
|
||||
}
|
||||
|
||||
private static (string plainToken, string tokenHash, DateTime expiresAt) GenerateRegistrationToken()
|
||||
{
|
||||
var tokenBytes = new byte[32];
|
||||
RandomNumberGenerator.Fill(tokenBytes);
|
||||
var plainToken = Convert.ToHexString(tokenBytes).ToLowerInvariant();
|
||||
var tokenHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(plainToken))).ToLowerInvariant();
|
||||
var expiresAt = DateTime.UtcNow.AddDays(1);
|
||||
return (plainToken, tokenHash, expiresAt);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.UpdateSite;
|
||||
|
||||
public record UpdateSiteCommand(Guid Id, string Name, string? Address, string? Timezone) : IRequest<ServiceResult<SiteResponse>>;
|
||||
@@ -0,0 +1,25 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.UpdateSite;
|
||||
|
||||
public class UpdateSiteHandler : IRequestHandler<UpdateSiteCommand, ServiceResult<SiteResponse>>
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
|
||||
public UpdateSiteHandler(IApplicationDbContext context) => _context = context;
|
||||
|
||||
public async Task<ServiceResult<SiteResponse>> Handle(UpdateSiteCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var site = await _context.Sites.FindAsync([request.Id], cancellationToken);
|
||||
if (site is null)
|
||||
return ServiceResult<SiteResponse>.NotFound("Site not found");
|
||||
|
||||
site.Update(request.Name, request.Address, request.Timezone);
|
||||
await _context.SaveChangesWithRetryAsync(ct: cancellationToken);
|
||||
|
||||
return ServiceResult<SiteResponse>.Success(new SiteResponse(
|
||||
site.Id, site.Name, site.Address, site.Timezone, site.Enabled, site.CreatedAt));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Queries.GetSite;
|
||||
|
||||
public class GetSiteHandler : IRequestHandler<GetSiteQuery, ServiceResult<SiteResponse>>
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
|
||||
public GetSiteHandler(IApplicationDbContext context) => _context = context;
|
||||
|
||||
public async Task<ServiceResult<SiteResponse>> Handle(GetSiteQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var site = await _context.Sites.FindAsync([request.Id], cancellationToken);
|
||||
if (site is null)
|
||||
return ServiceResult<SiteResponse>.NotFound("Site not found");
|
||||
|
||||
return ServiceResult<SiteResponse>.Success(new SiteResponse(
|
||||
site.Id, site.Name, site.Address, site.Timezone, site.Enabled, site.CreatedAt));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Queries.GetSite;
|
||||
|
||||
public record GetSiteQuery(Guid Id) : IRequest<ServiceResult<SiteResponse>>;
|
||||
@@ -0,0 +1,29 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.Sites.Queries.GetSites;
|
||||
|
||||
public class GetSitesHandler : IRequestHandler<GetSitesQuery, ServiceResult<PagedResult<SiteResponse>>>
|
||||
{
|
||||
private readonly IApplicationDbContext _context;
|
||||
|
||||
public GetSitesHandler(IApplicationDbContext context) => _context = context;
|
||||
|
||||
public async Task<ServiceResult<PagedResult<SiteResponse>>> Handle(GetSitesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = _context.Sites.AsNoTracking().OrderBy(s => s.Name);
|
||||
|
||||
var total = await query.CountAsync(cancellationToken);
|
||||
var items = await query
|
||||
.Skip((request.Page - 1) * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.Select(s => new SiteResponse(
|
||||
s.Id, s.Name, s.Address, s.Timezone, s.Enabled, s.CreatedAt))
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return ServiceResult<PagedResult<SiteResponse>>.Success(
|
||||
new PagedResult<SiteResponse>(items, total, request.Page, request.PageSize));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Queries.GetSites;
|
||||
|
||||
public record GetSitesQuery(int Page = 1, int PageSize = 20) : IRequest<ServiceResult<PagedResult<SiteResponse>>>;
|
||||
@@ -0,0 +1,8 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.AssignRoles;
|
||||
|
||||
public record AssignRolesCommand(
|
||||
Guid UserId,
|
||||
IList<string> Roles) : IRequest<ServiceResult>;
|
||||
@@ -0,0 +1,49 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.AssignRoles;
|
||||
|
||||
public class AssignRolesHandler : IRequestHandler<AssignRolesCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public AssignRolesHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> Handle(AssignRolesCommand command, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(command.UserId.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
var currentRoles = await _userManager.GetRolesAsync(user);
|
||||
|
||||
var wasAdmin = currentRoles.Contains("Admin");
|
||||
var willBeAdmin = command.Roles.Contains("Admin");
|
||||
if (wasAdmin && !willBeAdmin)
|
||||
{
|
||||
var adminCount = await _repository.CountAdminUsersAsync(ct);
|
||||
if (adminCount <= 1)
|
||||
return ServiceResult.Failure("Cannot remove the last administrator role. " +
|
||||
"Promote another user to Admin first.", 400);
|
||||
}
|
||||
|
||||
await _userManager.RemoveFromRolesAsync(user, currentRoles);
|
||||
await _userManager.AddToRolesAsync(user, command.Roles);
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserRolesUpdated", "User",
|
||||
command.UserId.ToString(),
|
||||
string.Join(",", currentRoles),
|
||||
string.Join(",", command.Roles),
|
||||
ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.AssignSites;
|
||||
|
||||
public record AssignSitesCommand(
|
||||
Guid UserId,
|
||||
IList<Guid> SiteIds) : IRequest<ServiceResult>;
|
||||
@@ -0,0 +1,30 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.AssignSites;
|
||||
|
||||
public class AssignSitesHandler : IRequestHandler<AssignSitesCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public AssignSitesHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> Handle(AssignSitesCommand command, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(command.UserId.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
await _repository.SetUserSitesAsync(command.UserId, command.SiteIds, ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.CreateUser;
|
||||
|
||||
public record CreateUserCommand(
|
||||
string Email,
|
||||
string Password,
|
||||
string DisplayName,
|
||||
IList<string>? Roles) : IRequest<ServiceResult<UserResponse>>;
|
||||
@@ -0,0 +1,48 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.CreateUser;
|
||||
|
||||
public class CreateUserHandler : IRequestHandler<CreateUserCommand, ServiceResult<UserResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public CreateUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<UserResponse>> Handle(CreateUserCommand command, CancellationToken ct)
|
||||
{
|
||||
var existing = await _userManager.FindByEmailAsync(command.Email);
|
||||
if (existing is not null)
|
||||
return ServiceResult<UserResponse>.Conflict("Email already registered");
|
||||
|
||||
var user = new AppUser
|
||||
{
|
||||
UserName = command.Email,
|
||||
Email = command.Email,
|
||||
DisplayName = command.DisplayName
|
||||
};
|
||||
|
||||
var result = await _userManager.CreateAsync(user, command.Password);
|
||||
if (!result.Succeeded)
|
||||
return ServiceResult<UserResponse>.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
|
||||
var roles = command.Roles is { Count: > 0 } ? command.Roles : new List<string> { "Viewer" };
|
||||
await _userManager.AddToRolesAsync(user, roles);
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserCreated", "User", user.Id.ToString(),
|
||||
null, null, ct);
|
||||
|
||||
var response = await _repository.GetByIdAsync(user.Id, ct);
|
||||
return ServiceResult<UserResponse>.Success(response!);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.DeleteUser;
|
||||
|
||||
public record DeleteUserCommand(Guid UserId, Guid CurrentUserId) : IRequest<ServiceResult>;
|
||||
@@ -0,0 +1,50 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.DeleteUser;
|
||||
|
||||
public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public DeleteUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> Handle(DeleteUserCommand command, CancellationToken ct)
|
||||
{
|
||||
if (command.UserId == command.CurrentUserId)
|
||||
return ServiceResult.Failure("You cannot delete your own account.", 400);
|
||||
|
||||
var user = await _userManager.FindByIdAsync(command.UserId.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
var roles = await _userManager.GetRolesAsync(user);
|
||||
if (roles.Contains("Admin"))
|
||||
{
|
||||
var adminCount = await _repository.CountAdminUsersAsync(ct);
|
||||
if (adminCount <= 1)
|
||||
return ServiceResult.Failure("Cannot delete the last administrator. " +
|
||||
"Promote another user to Admin first.", 400);
|
||||
}
|
||||
|
||||
await _repository.RemoveUserDataAsync(command.UserId, ct);
|
||||
|
||||
var result = await _userManager.DeleteAsync(user);
|
||||
if (!result.Succeeded)
|
||||
return ServiceResult.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
|
||||
await _repository.AddAuditLogAsync(command.CurrentUserId, "UserDeleted", "User",
|
||||
command.UserId.ToString(), null, null, ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.LockUser;
|
||||
|
||||
public record LockUserCommand(Guid UserId) : IRequest<ServiceResult>;
|
||||
@@ -0,0 +1,33 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.LockUser;
|
||||
|
||||
public class LockUserHandler : IRequestHandler<LockUserCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public LockUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> Handle(LockUserCommand command, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(command.UserId.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue);
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserLocked", "User",
|
||||
command.UserId.ToString(), null, null, ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.ResetPassword;
|
||||
|
||||
public record ResetPasswordCommand(Guid UserId) : IRequest<ServiceResult<ResetPasswordResponse>>;
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.Security.Cryptography;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.ResetPassword;
|
||||
|
||||
public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, ServiceResult<ResetPasswordResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public ResetPasswordHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<ResetPasswordResponse>> Handle(ResetPasswordCommand command, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(command.UserId.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult<ResetPasswordResponse>.NotFound("User not found");
|
||||
|
||||
var temporaryPassword = GenerateTemporaryPassword();
|
||||
var token = await _userManager.GeneratePasswordResetTokenAsync(user);
|
||||
var result = await _userManager.ResetPasswordAsync(user, token, temporaryPassword);
|
||||
|
||||
if (!result.Succeeded)
|
||||
return ServiceResult<ResetPasswordResponse>.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
|
||||
user.MustChangePassword = true;
|
||||
await _userManager.UpdateAsync(user);
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserPasswordReset", "User",
|
||||
command.UserId.ToString(), null, null, ct);
|
||||
|
||||
return ServiceResult<ResetPasswordResponse>.Success(
|
||||
new ResetPasswordResponse(temporaryPassword));
|
||||
}
|
||||
|
||||
private static string GenerateTemporaryPassword()
|
||||
{
|
||||
const string lower = "abcdefghijklmnopqrstuvwxyz";
|
||||
const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
const string digits = "0123456789";
|
||||
const string special = "!@#$%";
|
||||
|
||||
var chars = (lower + upper + digits + special).ToCharArray();
|
||||
var password = new char[16];
|
||||
password[0] = digits[RandomNumberGenerator.GetInt32(digits.Length)];
|
||||
password[1] = lower[RandomNumberGenerator.GetInt32(lower.Length)];
|
||||
password[2] = upper[RandomNumberGenerator.GetInt32(upper.Length)];
|
||||
password[3] = special[RandomNumberGenerator.GetInt32(special.Length)];
|
||||
for (int i = 4; i < password.Length; i++)
|
||||
password[i] = chars[RandomNumberGenerator.GetInt32(chars.Length)];
|
||||
|
||||
RandomNumberGenerator.Shuffle(password.AsSpan());
|
||||
return new string(password);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.UnlockUser;
|
||||
|
||||
public record UnlockUserCommand(Guid UserId) : IRequest<ServiceResult>;
|
||||
@@ -0,0 +1,34 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.UnlockUser;
|
||||
|
||||
public class UnlockUserHandler : IRequestHandler<UnlockUserCommand, ServiceResult>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public UnlockUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> Handle(UnlockUserCommand command, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(command.UserId.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
await _userManager.SetLockoutEndDateAsync(user, null);
|
||||
await _userManager.ResetAccessFailedCountAsync(user);
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserUnlocked", "User",
|
||||
command.UserId.ToString(), null, null, ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.UpdateUser;
|
||||
|
||||
public record UpdateUserCommand(
|
||||
Guid Id,
|
||||
string? DisplayName,
|
||||
string? Theme,
|
||||
string? Language) : IRequest<ServiceResult<UserResponse>>;
|
||||
@@ -0,0 +1,39 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.UpdateUser;
|
||||
|
||||
public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ServiceResult<UserResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public UpdateUserHandler(UserManager<AppUser> userManager, IUserRepository repository)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<UserResponse>> Handle(UpdateUserCommand command, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(command.Id.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult<UserResponse>.NotFound("User not found");
|
||||
|
||||
user.DisplayName = command.DisplayName ?? user.DisplayName;
|
||||
user.Theme = command.Theme ?? user.Theme;
|
||||
user.Language = command.Language ?? user.Language;
|
||||
|
||||
var result = await _userManager.UpdateAsync(user);
|
||||
if (!result.Succeeded)
|
||||
return ServiceResult<UserResponse>.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
|
||||
var response = await _repository.GetByIdAsync(user.Id, ct);
|
||||
return ServiceResult<UserResponse>.Success(response!);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Queries.GetMe;
|
||||
|
||||
public class GetMeHandler : IRequestHandler<GetMeQuery, ServiceResult<UserResponse>>
|
||||
{
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public GetMeHandler(IUserRepository repository)
|
||||
{
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<UserResponse>> Handle(GetMeQuery query, CancellationToken ct)
|
||||
{
|
||||
var user = await _repository.GetByIdAsync(query.CurrentUserId, ct);
|
||||
if (user is null)
|
||||
return ServiceResult<UserResponse>.NotFound("User not found");
|
||||
|
||||
return ServiceResult<UserResponse>.Success(user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Queries.GetMe;
|
||||
|
||||
public record GetMeQuery(Guid CurrentUserId) : IRequest<ServiceResult<UserResponse>>;
|
||||
@@ -0,0 +1,25 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Queries.GetUser;
|
||||
|
||||
public class GetUserHandler : IRequestHandler<GetUserQuery, ServiceResult<UserResponse>>
|
||||
{
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public GetUserHandler(IUserRepository repository)
|
||||
{
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<UserResponse>> Handle(GetUserQuery query, CancellationToken ct)
|
||||
{
|
||||
var user = await _repository.GetByIdAsync(query.Id, ct);
|
||||
if (user is null)
|
||||
return ServiceResult<UserResponse>.NotFound("User not found");
|
||||
|
||||
return ServiceResult<UserResponse>.Success(user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Queries.GetUser;
|
||||
|
||||
public record GetUserQuery(Guid Id) : IRequest<ServiceResult<UserResponse>>;
|
||||
@@ -0,0 +1,22 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Queries.GetUsers;
|
||||
|
||||
public class GetUsersHandler : IRequestHandler<GetUsersQuery, ServiceResult<PagedResult<UserResponse>>>
|
||||
{
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public GetUsersHandler(IUserRepository repository)
|
||||
{
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<PagedResult<UserResponse>>> Handle(GetUsersQuery query, CancellationToken ct)
|
||||
{
|
||||
var result = await _repository.GetPagedAsync(query.Page, query.PageSize, ct);
|
||||
return ServiceResult<PagedResult<UserResponse>>.Success(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Queries.GetUsers;
|
||||
|
||||
public record GetUsersQuery(int Page, int PageSize) : IRequest<ServiceResult<PagedResult<UserResponse>>>;
|
||||
@@ -1,3 +1,4 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Data.Interceptors;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
@@ -7,7 +8,7 @@ using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
|
||||
namespace Heimdall.Infrastructure.Data;
|
||||
|
||||
public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
|
||||
public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicationDbContext
|
||||
{
|
||||
private readonly AuditInterceptor _auditInterceptor;
|
||||
|
||||
@@ -49,6 +50,11 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
|
||||
public DbSet<Person> Persons => Set<Person>();
|
||||
public DbSet<KnownFace> KnownFaces => Set<KnownFace>();
|
||||
|
||||
public async Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default)
|
||||
{
|
||||
await DbContextExtensions.SaveChangesWithRetryAsync(this, maxRetries, ct);
|
||||
}
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
base.OnModelCreating(builder);
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Heimdall.Infrastructure.Data.Interceptors;
|
||||
using Heimdall.Infrastructure.Persistence;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Heimdall.Infrastructure.Services;
|
||||
using Heimdall.Infrastructure.Services.Discovery;
|
||||
@@ -36,6 +39,8 @@ public static class DependencyInjection
|
||||
options.UseNpgsql(connectionString, npgsql =>
|
||||
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")));
|
||||
|
||||
services.AddScoped<IApplicationDbContext>(sp => sp.GetRequiredService<AppDbContext>());
|
||||
|
||||
// Identity
|
||||
services.AddIdentity<AppUser, AppRole>(options =>
|
||||
{
|
||||
@@ -103,6 +108,9 @@ public static class DependencyInjection
|
||||
// Credential encryption
|
||||
services.AddScoped<ICredentialProtector, DataProtectorCredentialProtector>();
|
||||
|
||||
// Data access
|
||||
services.AddScoped<IUserRepository, UserRepository>();
|
||||
|
||||
// Application services
|
||||
services.AddScoped<IAuthService, AuthService>();
|
||||
services.AddScoped<ISiteService, SiteService>();
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Infrastructure.Persistence;
|
||||
|
||||
public class UserRepository : IUserRepository
|
||||
{
|
||||
private readonly AppDbContext _db;
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
|
||||
public UserRepository(AppDbContext db, UserManager<AppUser> userManager)
|
||||
{
|
||||
_db = db;
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
public async Task<PagedResult<UserResponse>> GetPagedAsync(int page, int pageSize, CancellationToken ct)
|
||||
{
|
||||
var query = _db.Users.AsNoTracking().OrderBy(u => u.DisplayName);
|
||||
var total = await query.CountAsync(ct);
|
||||
var users = await query
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync(ct);
|
||||
|
||||
var userIds = users.Select(u => u.Id).ToList();
|
||||
|
||||
var roleQuery = from ur in _db.Set<IdentityUserRole<Guid>>()
|
||||
join r in _db.Roles on ur.RoleId equals r.Id
|
||||
where userIds.Contains(ur.UserId)
|
||||
select new { ur.UserId, r.Name };
|
||||
var rolesByUser = (await roleQuery.ToListAsync(ct))
|
||||
.GroupBy(x => x.UserId)
|
||||
.ToDictionary(g => g.Key, g => g.Select(x => x.Name!).ToList());
|
||||
|
||||
var sitesByUser = (await _db.UserSites.AsNoTracking()
|
||||
.Where(us => userIds.Contains(us.UserId))
|
||||
.ToListAsync(ct))
|
||||
.GroupBy(us => us.UserId)
|
||||
.ToDictionary(g => g.Key, g => g.Select(us => us.SiteId).ToList());
|
||||
|
||||
var items = users.Select(u =>
|
||||
{
|
||||
rolesByUser.TryGetValue(u.Id, out var roles);
|
||||
sitesByUser.TryGetValue(u.Id, out var sites);
|
||||
return MapToResponse(u, roles ?? [], sites ?? []);
|
||||
}).ToList();
|
||||
|
||||
return new PagedResult<UserResponse>(items, total, page, pageSize);
|
||||
}
|
||||
|
||||
public async Task<UserResponse?> GetByIdAsync(Guid id, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(id.ToString());
|
||||
if (user is null) return null;
|
||||
|
||||
var roles = await _userManager.GetRolesAsync(user);
|
||||
var siteIds = await _db.UserSites
|
||||
.Where(us => us.UserId == user.Id)
|
||||
.Select(us => us.SiteId)
|
||||
.ToListAsync(ct);
|
||||
|
||||
return new UserResponse(
|
||||
user.Id,
|
||||
user.Email ?? "",
|
||||
user.DisplayName,
|
||||
user.Theme,
|
||||
user.Language,
|
||||
roles,
|
||||
siteIds,
|
||||
await _userManager.GetTwoFactorEnabledAsync(user),
|
||||
await _userManager.IsLockedOutAsync(user),
|
||||
user.LockoutEnd?.UtcDateTime,
|
||||
user.AccessFailedCount,
|
||||
user.EmailConfirmed,
|
||||
user.CreatedAt);
|
||||
}
|
||||
|
||||
public async Task<int> CountAdminUsersAsync(CancellationToken ct)
|
||||
{
|
||||
var adminRole = await _db.Roles.FirstOrDefaultAsync(r => r.Name == AppRoles.Admin, ct);
|
||||
if (adminRole is null) return 0;
|
||||
|
||||
return await _db.Set<IdentityUserRole<Guid>>()
|
||||
.CountAsync(ur => ur.RoleId == adminRole.Id, ct);
|
||||
}
|
||||
|
||||
public async Task AddAuditLogAsync(Guid? userId, string action, string resourceType,
|
||||
string? resourceId, string? oldValue, string? newValue, CancellationToken ct)
|
||||
{
|
||||
_db.AuditLogs.Add(new AuditLog(userId, action, resourceType, resourceId, oldValue, newValue));
|
||||
await _db.SaveChangesWithRetryAsync(ct: ct);
|
||||
}
|
||||
|
||||
public async Task SetUserSitesAsync(Guid userId, IList<Guid> siteIds, CancellationToken ct)
|
||||
{
|
||||
var existing = await _db.UserSites.Where(us => us.UserId == userId).ToListAsync(ct);
|
||||
_db.UserSites.RemoveRange(existing);
|
||||
|
||||
foreach (var siteId in siteIds)
|
||||
_db.UserSites.Add(new UserSite(userId, siteId));
|
||||
|
||||
await _db.SaveChangesWithRetryAsync(ct: ct);
|
||||
}
|
||||
|
||||
public async Task RemoveUserDataAsync(Guid userId, CancellationToken ct)
|
||||
{
|
||||
var userSites = await _db.UserSites.Where(us => us.UserId == userId).ToListAsync(ct);
|
||||
_db.UserSites.RemoveRange(userSites);
|
||||
|
||||
var userGroups = await _db.UserGroups.Where(ug => ug.UserId == userId).ToListAsync(ct);
|
||||
_db.UserGroups.RemoveRange(userGroups);
|
||||
|
||||
var apiKeys = await _db.ApiKeys.Where(ak => ak.CreatedByUserId == userId).ToListAsync(ct);
|
||||
_db.ApiKeys.RemoveRange(apiKeys);
|
||||
|
||||
await _db.SaveChangesWithRetryAsync(ct: ct);
|
||||
}
|
||||
|
||||
private static UserResponse MapToResponse(AppUser user, List<string> roles, List<Guid> siteIds)
|
||||
{
|
||||
return new UserResponse(
|
||||
user.Id,
|
||||
user.Email ?? "",
|
||||
user.DisplayName,
|
||||
user.Theme,
|
||||
user.Language,
|
||||
roles,
|
||||
siteIds,
|
||||
user.TwoFactorEnabled,
|
||||
user.LockoutEnabled && user.LockoutEnd.HasValue && user.LockoutEnd > DateTimeOffset.UtcNow,
|
||||
user.LockoutEnd?.UtcDateTime,
|
||||
user.AccessFailedCount,
|
||||
user.EmailConfirmed,
|
||||
user.CreatedAt);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,9 @@
|
||||
using System.Text;
|
||||
using Heimdall.Application.Common;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
|
||||
namespace Heimdall.Infrastructure.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Encrypts and decrypts camera credentials using ASP.NET Core Data Protection (IDataProtector).
|
||||
/// Uses a dedicated purpose string to isolate camera credentials from other protected data.
|
||||
/// </summary>
|
||||
public interface ICredentialProtector
|
||||
{
|
||||
string Encrypt(string plaintext);
|
||||
string Decrypt(string ciphertext);
|
||||
}
|
||||
|
||||
public sealed class DataProtectorCredentialProtector : ICredentialProtector
|
||||
{
|
||||
private readonly IDataProtector _protector;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -8,14 +9,6 @@ using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Heimdall.Infrastructure.Security;
|
||||
|
||||
public interface IJwtService
|
||||
{
|
||||
(string token, DateTime expiresAt) GenerateAccessToken(AppUser user, IList<string> roles, IList<string> permissions);
|
||||
(string token, DateTime expiresAt) GenerateRefreshToken(AppUser user);
|
||||
ClaimsPrincipal? ValidateRefreshToken(string refreshToken);
|
||||
string? GetUserIdFromExpiredToken(string token);
|
||||
}
|
||||
|
||||
public class JwtService : IJwtService
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
@@ -4,7 +4,6 @@ using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
Reference in new issue
Block a user