feat(mvp): complete Blazor UI + User Management + integration tests
This commit is contained in:
1 parent
b217c932e8
commit
38816aec8a
26 files changed
+1893
-45
No files matched your search
@@ -0,0 +1,100 @@
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/users")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
|
||||
public class UsersController : ControllerBase
|
||||
{
|
||||
private readonly IUserService _userService;
|
||||
|
||||
public UsersController(IUserService userService) => _userService = userService;
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> List(
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _userService.ListAsync(page, pageSize, ct);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.GetByIdAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create([FromBody] CreateUserRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.CreateAsync(request, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
public async Task<IActionResult> Update(
|
||||
Guid id, [FromBody] UpdateUserRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.UpdateAsync(id, request, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/roles")]
|
||||
public async Task<IActionResult> AssignRoles(
|
||||
Guid id, [FromBody] AssignRolesRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.AssignRolesAsync(id, request, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/sites")]
|
||||
public async Task<IActionResult> AssignSites(
|
||||
Guid id, [FromBody] AssignSitesRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.AssignSitesAsync(id, request, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/reset-password")]
|
||||
public async Task<IActionResult> ResetPassword(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.ResetPasswordAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/lock")]
|
||||
public async Task<IActionResult> Lock(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.LockAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/unlock")]
|
||||
public async Task<IActionResult> Unlock(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _userService.UnlockAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,10 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Heimdall.IntegrationTests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.8" />
|
||||
|
||||
+57
-16
@@ -12,10 +12,17 @@ var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// ── Services ──────────────────────────────────────────────────────
|
||||
|
||||
builder.Services.AddControllers(options =>
|
||||
if (!builder.Environment.IsEnvironment("Testing"))
|
||||
{
|
||||
options.Filters.Add<ExceptionFilter>();
|
||||
});
|
||||
builder.Services.AddControllers(options =>
|
||||
{
|
||||
options.Filters.Add<ExceptionFilter>();
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
builder.Services.AddControllers();
|
||||
}
|
||||
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
@@ -23,13 +30,14 @@ builder.Services.AddOpenApi();
|
||||
builder.Services.AddApplication();
|
||||
|
||||
// ── Infrastructure layer ──────────────────────────────────────────
|
||||
builder.Services.AddInfrastructure(builder.Configuration);
|
||||
builder.Services.AddInfrastructure(builder.Configuration, builder.Environment.EnvironmentName);
|
||||
|
||||
// ── Authentication ────────────────────────────────────────────────
|
||||
var jwtKey = builder.Configuration["Jwt:Key"]
|
||||
?? Environment.GetEnvironmentVariable("JWT__KEY")
|
||||
?? throw new InvalidOperationException("JWT:Key is not configured");
|
||||
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? "heimdall";
|
||||
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? "heimdall-api";
|
||||
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall";
|
||||
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api";
|
||||
|
||||
builder.Services.AddAuthentication(options =>
|
||||
{
|
||||
@@ -71,24 +79,38 @@ var allowedOrigins = builder.Configuration["Cors:AllowedOrigins"]?.Split(',')
|
||||
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("ApiPolicy", policy =>
|
||||
policy.WithOrigins(allowedOrigins)
|
||||
.AllowCredentials()
|
||||
.AllowAnyHeader()
|
||||
.WithMethods("GET", "POST", "PUT", "DELETE", "PATCH"));
|
||||
var isWildcard = allowedOrigins.Length == 1 && allowedOrigins[0] == "*";
|
||||
if (isWildcard)
|
||||
{
|
||||
options.AddPolicy("ApiPolicy", policy =>
|
||||
policy.AllowAnyOrigin()
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod());
|
||||
}
|
||||
else
|
||||
{
|
||||
options.AddPolicy("ApiPolicy", policy =>
|
||||
policy.WithOrigins(allowedOrigins)
|
||||
.AllowCredentials()
|
||||
.AllowAnyHeader()
|
||||
.WithMethods("GET", "POST", "PUT", "DELETE", "PATCH"));
|
||||
}
|
||||
});
|
||||
|
||||
// ── Pipeline ──────────────────────────────────────────────────────
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Apply migrations on startup
|
||||
using (var scope = app.Services.CreateScope())
|
||||
// Apply migrations on startup (skip in Testing with InMemory)
|
||||
if (!app.Environment.IsEnvironment("Testing"))
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
if (db.Database.GetPendingMigrations().Any())
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
db.Database.Migrate();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
if (db.Database.GetPendingMigrations().Any())
|
||||
{
|
||||
db.Database.Migrate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,6 +119,8 @@ using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var roleManager = scope.ServiceProvider
|
||||
.GetRequiredService<Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Domain.Entities.AppRole>>();
|
||||
var userManager = scope.ServiceProvider
|
||||
.GetRequiredService<Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser>>();
|
||||
|
||||
foreach (var roleName in AppRoles.All)
|
||||
{
|
||||
@@ -105,6 +129,23 @@ using (var scope = app.Services.CreateScope())
|
||||
await roleManager.CreateAsync(new Heimdall.Domain.Entities.AppRole(roleName));
|
||||
}
|
||||
}
|
||||
|
||||
// In Testing, seed an admin user for integration tests
|
||||
if (app.Environment.IsEnvironment("Testing"))
|
||||
{
|
||||
var testAdmin = await userManager.FindByEmailAsync("testadmin@heimdall.test");
|
||||
if (testAdmin is null)
|
||||
{
|
||||
testAdmin = new Heimdall.Domain.Entities.AppUser
|
||||
{
|
||||
UserName = "testadmin@heimdall.test",
|
||||
Email = "testadmin@heimdall.test",
|
||||
DisplayName = "Test Admin"
|
||||
};
|
||||
await userManager.CreateAsync(testAdmin, "TestAdmin123!");
|
||||
await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace Heimdall.Application.DTOs;
|
||||
|
||||
public record UserResponse(
|
||||
Guid Id,
|
||||
string Email,
|
||||
string DisplayName,
|
||||
string? Theme,
|
||||
string Language,
|
||||
IList<string> Roles,
|
||||
IList<Guid> SiteIds,
|
||||
bool TwoFactorEnabled,
|
||||
bool IsLockedOut,
|
||||
DateTime? LockoutEnd,
|
||||
int AccessFailedCount,
|
||||
bool EmailConfirmed,
|
||||
DateTime CreatedAt);
|
||||
|
||||
public record CreateUserRequest(
|
||||
string Email,
|
||||
string Password,
|
||||
string DisplayName,
|
||||
IList<string>? Roles);
|
||||
|
||||
public record UpdateUserRequest(string DisplayName, string? Theme, string? Language);
|
||||
|
||||
public record AssignRolesRequest(IList<string> Roles);
|
||||
|
||||
public record AssignSitesRequest(IList<Guid> SiteIds);
|
||||
|
||||
public record ResetPasswordResponse(string TemporaryPassword);
|
||||
@@ -0,0 +1,17 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public interface IUserService
|
||||
{
|
||||
Task<ServiceResult<PagedResult<UserResponse>>> ListAsync(int page, int pageSize, CancellationToken ct);
|
||||
Task<ServiceResult<UserResponse>> GetByIdAsync(Guid id, CancellationToken ct);
|
||||
Task<ServiceResult<UserResponse>> CreateAsync(CreateUserRequest request, CancellationToken ct);
|
||||
Task<ServiceResult<UserResponse>> UpdateAsync(Guid id, UpdateUserRequest request, CancellationToken ct);
|
||||
Task<ServiceResult> AssignRolesAsync(Guid id, AssignRolesRequest request, CancellationToken ct);
|
||||
Task<ServiceResult> AssignSitesAsync(Guid id, AssignSitesRequest request, CancellationToken ct);
|
||||
Task<ServiceResult<ResetPasswordResponse>> ResetPasswordAsync(Guid id, CancellationToken ct);
|
||||
Task<ServiceResult> LockAsync(Guid id, CancellationToken ct);
|
||||
Task<ServiceResult> UnlockAsync(Guid id, CancellationToken ct);
|
||||
}
|
||||
@@ -15,14 +15,17 @@ public static class DependencyInjection
|
||||
public static IServiceCollection AddInfrastructure(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration,
|
||||
bool isTestEnvironment = false)
|
||||
string? environmentName = null)
|
||||
{
|
||||
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
|
||||
?? configuration.GetConnectionString("Default")
|
||||
?? "Host=localhost;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall";
|
||||
var env = environmentName ?? Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
|
||||
var isTesting = env == "Testing";
|
||||
|
||||
if (!isTestEnvironment)
|
||||
if (!isTesting)
|
||||
{
|
||||
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
|
||||
?? configuration.GetConnectionString("Default")
|
||||
?? "Host=localhost;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall";
|
||||
|
||||
services.AddDbContext<AppDbContext>(options =>
|
||||
{
|
||||
options.UseNpgsql(connectionString, npgsql =>
|
||||
@@ -51,6 +54,7 @@ public static class DependencyInjection
|
||||
services.AddScoped<IAuthService, AuthService>();
|
||||
services.AddScoped<ISiteService, SiteService>();
|
||||
services.AddScoped<IAgentService, AgentService>();
|
||||
services.AddScoped<IUserService, UserService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
public class UserService : IUserService
|
||||
{
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly AppDbContext _db;
|
||||
|
||||
public UserService(UserManager<AppUser> userManager, AppDbContext db)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<PagedResult<UserResponse>>> ListAsync(int page, int pageSize, CancellationToken ct)
|
||||
{
|
||||
var query = _db.Users.OrderBy(u => u.DisplayName);
|
||||
|
||||
var total = await query.CountAsync(ct);
|
||||
var users = await query
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync(ct);
|
||||
|
||||
var items = new List<UserResponse>();
|
||||
foreach (var user in users)
|
||||
{
|
||||
items.Add(await MapToResponse(user));
|
||||
}
|
||||
|
||||
return ServiceResult<PagedResult<UserResponse>>.Success(
|
||||
new PagedResult<UserResponse>(items, total, page, pageSize));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<UserResponse>> GetByIdAsync(Guid id, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(id.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult<UserResponse>.NotFound("User not found");
|
||||
|
||||
return ServiceResult<UserResponse>.Success(await MapToResponse(user));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<UserResponse>> CreateAsync(CreateUserRequest request, CancellationToken ct)
|
||||
{
|
||||
var existing = await _userManager.FindByEmailAsync(request.Email);
|
||||
if (existing is not null)
|
||||
return ServiceResult<UserResponse>.Conflict("Email already registered");
|
||||
|
||||
var user = new AppUser
|
||||
{
|
||||
UserName = request.Email,
|
||||
Email = request.Email,
|
||||
DisplayName = request.DisplayName
|
||||
};
|
||||
|
||||
var result = await _userManager.CreateAsync(user, request.Password);
|
||||
if (!result.Succeeded)
|
||||
return ServiceResult<UserResponse>.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
|
||||
// Assign default role
|
||||
var roles = request.Roles is { Count: > 0 } ? request.Roles : new List<string> { AppRoles.Viewer };
|
||||
await _userManager.AddToRolesAsync(user, roles);
|
||||
|
||||
_db.AuditLogs.Add(new AuditLog(null, "UserCreated", "User", user.Id.ToString()));
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return ServiceResult<UserResponse>.Success(await MapToResponse(user));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<UserResponse>> UpdateAsync(Guid id, UpdateUserRequest request, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(id.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult<UserResponse>.NotFound("User not found");
|
||||
|
||||
user.DisplayName = request.DisplayName;
|
||||
user.Theme = request.Theme ?? user.Theme;
|
||||
user.Language = request.Language ?? user.Language;
|
||||
|
||||
var result = await _userManager.UpdateAsync(user);
|
||||
if (!result.Succeeded)
|
||||
return ServiceResult<UserResponse>.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
|
||||
return ServiceResult<UserResponse>.Success(await MapToResponse(user));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> AssignRolesAsync(Guid id, AssignRolesRequest request, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(id.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
var currentRoles = await _userManager.GetRolesAsync(user);
|
||||
await _userManager.RemoveFromRolesAsync(user, currentRoles);
|
||||
await _userManager.AddToRolesAsync(user, request.Roles);
|
||||
|
||||
_db.AuditLogs.Add(new AuditLog(null, "UserRolesUpdated", "User",
|
||||
id.ToString(), string.Join(",", currentRoles), string.Join(",", request.Roles)));
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> AssignSitesAsync(Guid id, AssignSitesRequest request, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(id.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
var existing = await _db.UserSites.Where(us => us.UserId == id).ToListAsync(ct);
|
||||
_db.UserSites.RemoveRange(existing);
|
||||
|
||||
foreach (var siteId in request.SiteIds)
|
||||
{
|
||||
_db.UserSites.Add(new UserSite(id, siteId));
|
||||
}
|
||||
|
||||
await _db.SaveChangesAsync(ct);
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<ResetPasswordResponse>> ResetPasswordAsync(Guid id, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(id.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult<ResetPasswordResponse>.NotFound("User not found");
|
||||
|
||||
// Generate a temporary password
|
||||
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)));
|
||||
|
||||
// Force password change on next login
|
||||
user.LockoutEnd = DateTimeOffset.UtcNow;
|
||||
await _userManager.UpdateAsync(user);
|
||||
|
||||
_db.AuditLogs.Add(new AuditLog(null, "UserPasswordReset", "User", id.ToString()));
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return ServiceResult<ResetPasswordResponse>.Success(
|
||||
new ResetPasswordResponse(temporaryPassword));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> LockAsync(Guid id, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(id.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue);
|
||||
|
||||
_db.AuditLogs.Add(new AuditLog(null, "UserLocked", "User", id.ToString()));
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> UnlockAsync(Guid id, CancellationToken ct)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(id.ToString());
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
await _userManager.SetLockoutEndDateAsync(user, null);
|
||||
await _userManager.ResetAccessFailedCountAsync(user);
|
||||
|
||||
_db.AuditLogs.Add(new AuditLog(null, "UserUnlocked", "User", id.ToString()));
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
private async Task<UserResponse> MapToResponse(AppUser user)
|
||||
{
|
||||
var roles = await _userManager.GetRolesAsync(user);
|
||||
var siteIds = await _db.UserSites
|
||||
.Where(us => us.UserId == user.Id)
|
||||
.Select(us => us.SiteId)
|
||||
.ToListAsync();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private static string GenerateTemporaryPassword()
|
||||
{
|
||||
const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%";
|
||||
var random = new Random();
|
||||
return new string(Enumerable.Range(0, 16).Select(_ => chars[random.Next(chars.Length)]).ToArray());
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,9 @@
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<base href="/" />
|
||||
<ResourcePreloader />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet" />
|
||||
<link rel="stylesheet" href="@Assets["lib/bootstrap/dist/css/bootstrap.min.css"]" />
|
||||
<link rel="stylesheet" href="@Assets["_content/MudBlazor/MudBlazor.min.css"]" />
|
||||
<link rel="stylesheet" href="@Assets["app.css"]" />
|
||||
<link rel="stylesheet" href="@Assets["Heimdall.Web.styles.css"]" />
|
||||
<ImportMap />
|
||||
@@ -16,8 +17,8 @@
|
||||
|
||||
<body>
|
||||
<Routes />
|
||||
<ReconnectModal />
|
||||
<script src="@Assets["_framework/blazor.web.js"]"></script>
|
||||
<script src="@Assets["_content/MudBlazor/MudBlazor.min.js"]"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,23 +1,81 @@
|
||||
@inherits LayoutComponentBase
|
||||
@inject AuthState Auth
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<div class="page">
|
||||
<div class="sidebar">
|
||||
<NavMenu />
|
||||
</div>
|
||||
<MudThemeProvider />
|
||||
<MudDialogProvider />
|
||||
<MudSnackbarProvider />
|
||||
|
||||
<main>
|
||||
<div class="top-row px-4">
|
||||
<a href="https://learn.microsoft.com/aspnet/core/" target="_blank">About</a>
|
||||
</div>
|
||||
<MudLayout>
|
||||
<MudAppBar Elevation="1">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Inherit"
|
||||
@onclick="@(() => _drawerOpen = !_drawerOpen)" />
|
||||
<MudText Typo="Typo.h6" Class="ml-2">Heimdall</MudText>
|
||||
<MudSpacer />
|
||||
@if (Auth.IsLoggedIn)
|
||||
{
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Notifications" Color="Color.Inherit" />
|
||||
<MudMenu AnchorOrigin="Origin.BottomRight">
|
||||
<ActivatorContent>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.AccountCircle" Color="Color.Inherit" />
|
||||
</ActivatorContent>
|
||||
<ChildContent>
|
||||
<MudMenuItem>
|
||||
<MudText>@Auth.User?.DisplayName</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">@Auth.User?.Email</MudText>
|
||||
</MudMenuItem>
|
||||
<MudDivider />
|
||||
<MudMenuItem OnClick="@Logout">Déconnexion</MudMenuItem>
|
||||
</ChildContent>
|
||||
</MudMenu>
|
||||
}
|
||||
</MudAppBar>
|
||||
|
||||
<article class="content px-4">
|
||||
<MudDrawer @bind-Open="_drawerOpen" Variant="DrawerVariant.Responsive" ClipMode="DrawerClipMode.Never">
|
||||
<MudNavMenu>
|
||||
@if (Auth.IsLoggedIn)
|
||||
{
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="px-4 py-2">Navigation</MudText>
|
||||
|
||||
<MudNavLink Href="/dashboard" Match="NavLinkMatch.Prefix">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Dashboard" /> Dashboard
|
||||
</MudNavLink>
|
||||
<MudNavLink Href="/sites" Match="NavLinkMatch.Prefix">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Videocam" /> Sites & Caméras
|
||||
</MudNavLink>
|
||||
|
||||
@if (Auth.User?.Roles?.Contains("Admin") == true)
|
||||
{
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="px-4 py-2 mt-2">Administration</MudText>
|
||||
<MudNavLink Href="/users" Match="NavLinkMatch.Prefix">
|
||||
<MudIcon Icon="@Icons.Material.Filled.People" /> Utilisateurs
|
||||
</MudNavLink>
|
||||
}
|
||||
|
||||
<MudDivider Class="my-4" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudNavLink Href="/login" Match="NavLinkMatch.Prefix">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Login" /> Connexion
|
||||
</MudNavLink>
|
||||
}
|
||||
</MudNavMenu>
|
||||
</MudDrawer>
|
||||
|
||||
<MudMainContent>
|
||||
<MudContainer MaxWidth="MaxWidth.Large" Class="py-8">
|
||||
@Body
|
||||
</article>
|
||||
</main>
|
||||
</div>
|
||||
</MudContainer>
|
||||
</MudMainContent>
|
||||
</MudLayout>
|
||||
|
||||
<div id="blazor-error-ui" data-nosnippet>
|
||||
An unhandled error has occurred.
|
||||
<a href="." class="reload">Reload</a>
|
||||
<span class="dismiss">🗙</span>
|
||||
</div>
|
||||
@code {
|
||||
private bool _drawerOpen = true;
|
||||
|
||||
private void Logout()
|
||||
{
|
||||
Auth.Logout();
|
||||
Navigation.NavigateTo("/login", true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
@inherits LayoutComponentBase
|
||||
|
||||
<MudThemeProvider />
|
||||
<MudDialogProvider />
|
||||
<MudSnackbarProvider />
|
||||
|
||||
<MudLayout>
|
||||
<MudMainContent>
|
||||
@Body
|
||||
</MudMainContent>
|
||||
</MudLayout>
|
||||
@@ -0,0 +1,102 @@
|
||||
@page "/"
|
||||
@page "/dashboard"
|
||||
@attribute [Authorize]
|
||||
@layout MainLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject AuthState Auth
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudText Typo="Typo.h4" Class="mb-2">
|
||||
Dashboard
|
||||
</MudText>
|
||||
<MudText Typo="Typo.body1" Class="mb-6">
|
||||
Bienvenue, <strong>@Auth.User?.DisplayName</strong>
|
||||
</MudText>
|
||||
|
||||
<MudGrid>
|
||||
<MudItem xs="12" sm="6" lg="3">
|
||||
<MudPaper Elevation="3" Class="pa-4" Style="border-radius: 12px;">
|
||||
<MudText Typo="Typo.h4" Color="Color.Primary">@_siteCount</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Sites</MudText>
|
||||
</MudPaper>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6" lg="3">
|
||||
<MudPaper Elevation="3" Class="pa-4" Style="border-radius: 12px;">
|
||||
<MudText Typo="Typo.h4" Color="Color.Secondary">@_cameraCount</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Caméras</MudText>
|
||||
</MudPaper>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6" lg="3">
|
||||
<MudPaper Elevation="3" Class="pa-4" Style="border-radius: 12px;">
|
||||
<MudText Typo="Typo.h4" Color="Color.Warning">@_onlineCount</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Sites actifs</MudText>
|
||||
</MudPaper>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<MudGrid Class="mt-8">
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.h5" Class="mb-4">Sites récents</MudText>
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else if (_sites?.Count > 0)
|
||||
{
|
||||
<MudTable Items="@_sites" Hover="true" Striped="true" Elevation="1">
|
||||
<HeaderContent>
|
||||
<MudTh>Nom</MudTh>
|
||||
<MudTh>Adresse</MudTh>
|
||||
<MudTh>Statut</MudTh>
|
||||
<MudTh>Créé le</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd><MudLink Href="@($"/sites/{context.Id}")">@context.Name</MudLink></MudTd>
|
||||
<MudTd DataLabel="Adresse">@context.Address</MudTd>
|
||||
<MudTd DataLabel="Statut">
|
||||
<MudText Color="@(context.Enabled ? Color.Success : Color.Default)" Typo="Typo.body2">
|
||||
@(context.Enabled ? "● Actif" : "○ Inactif")
|
||||
</MudText>
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Créé le">@context.CreatedAt.ToString("g")</MudTd>
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudPaper Class="pa-8 text-center">
|
||||
<MudText>Aucun site. <MudLink Href="/sites">Créer un site</MudLink></MudText>
|
||||
</MudPaper>
|
||||
}
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
@code {
|
||||
private int _siteCount;
|
||||
#pragma warning disable CS0649
|
||||
private int _cameraCount;
|
||||
private int _onlineCount;
|
||||
#pragma warning restore CS0649
|
||||
private IReadOnlyList<SiteItem>? _sites;
|
||||
private bool _loading = true;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await Api.GetSitesAsync(1, 5);
|
||||
if (result is not null)
|
||||
{
|
||||
_sites = result.Items;
|
||||
_siteCount = result.TotalCount;
|
||||
_onlineCount = result.Items.Count(s => s.Enabled);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Erreur : {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally { _loading = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
@page "/login"
|
||||
@layout MudBlazorLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject AuthState Auth
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.ExtraSmall" Class="mt-16">
|
||||
<MudPaper Elevation="5" Class="pa-8" Style="border-radius: 16px;">
|
||||
<MudText Typo="Typo.h4" Align="Align.Center" Class="mb-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Shield" Size="Size.Large" Color="Color.Primary" />
|
||||
Heimdall
|
||||
</MudText>
|
||||
<MudText Typo="Typo.body2" Align="Align.Center" Color="Color.Secondary" Class="mb-8">
|
||||
Plateforme de surveillance vidéo
|
||||
</MudText>
|
||||
|
||||
<MudTextField @bind-Value="_email" Label="Email" Variant="Variant.Outlined"
|
||||
Class="mb-4" Required="true" Immediate="true" />
|
||||
<MudTextField @bind-Value="_password" Label="Mot de passe" Variant="Variant.Outlined"
|
||||
InputType="InputType.Password" Class="mb-6" Required="true" Immediate="true" />
|
||||
|
||||
@if (!string.IsNullOrEmpty(_errorMessage))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_errorMessage</MudAlert>
|
||||
}
|
||||
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" FullWidth="true"
|
||||
OnClick="@LoginAsync" Disabled="@_loading" Class="mb-4">
|
||||
@if (_loading) { <MudProgressCircular Size="Size.Small" Class="mr-2" /> }
|
||||
Se connecter
|
||||
</MudButton>
|
||||
|
||||
<MudText Typo="Typo.body2" Align="Align.Center">
|
||||
Pas encore de compte ?
|
||||
<MudLink Href="/register">Créer un compte</MudLink>
|
||||
</MudText>
|
||||
</MudPaper>
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
private string _email = "";
|
||||
private string _password = "";
|
||||
private bool _loading;
|
||||
private string _errorMessage = "";
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
if (Auth.IsLoggedIn)
|
||||
Navigation.NavigateTo("/dashboard");
|
||||
}
|
||||
|
||||
private async Task LoginAsync()
|
||||
{
|
||||
_loading = true;
|
||||
_errorMessage = "";
|
||||
try
|
||||
{
|
||||
var result = await Api.LoginAsync(_email, _password);
|
||||
if (result is null)
|
||||
{
|
||||
_errorMessage = "Email ou mot de passe invalide";
|
||||
return;
|
||||
}
|
||||
Auth.Login(result);
|
||||
Snackbar.Add("Connexion réussie", Severity.Success);
|
||||
Navigation.NavigateTo("/dashboard");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_errorMessage = $"Erreur : {ex.Message}";
|
||||
}
|
||||
finally { _loading = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
@page "/register"
|
||||
@layout MudBlazorLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject AuthState Auth
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.ExtraSmall" Class="mt-16">
|
||||
<MudPaper Elevation="5" Class="pa-8" Style="border-radius: 16px;">
|
||||
<MudText Typo="Typo.h5" Align="Align.Center" Class="mb-6">Créer un compte</MudText>
|
||||
|
||||
<MudTextField @bind-Value="_displayName" Label="Nom d'affichage" Variant="Variant.Outlined"
|
||||
Class="mb-4" Required="true" Immediate="true" />
|
||||
<MudTextField @bind-Value="_email" Label="Email" Variant="Variant.Outlined"
|
||||
Class="mb-4" Required="true" Immediate="true" />
|
||||
<MudTextField @bind-Value="_password" Label="Mot de passe" Variant="Variant.Outlined"
|
||||
InputType="InputType.Password" Class="mb-6" Required="true" Immediate="true"
|
||||
HelperText="Minimum 12 caractères" />
|
||||
|
||||
@if (!string.IsNullOrEmpty(_errorMessage))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_errorMessage</MudAlert>
|
||||
}
|
||||
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" FullWidth="true"
|
||||
OnClick="@RegisterAsync" Disabled="@_loading" Class="mb-4">
|
||||
@if (_loading) { <MudProgressCircular Size="Size.Small" Class="mr-2" /> }
|
||||
S'inscrire
|
||||
</MudButton>
|
||||
|
||||
<MudText Typo="Typo.body2" Align="Align.Center">
|
||||
Déjà un compte ?
|
||||
<MudLink Href="/login">Se connecter</MudLink>
|
||||
</MudText>
|
||||
</MudPaper>
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
private string _email = "";
|
||||
private string _password = "";
|
||||
private string _displayName = "";
|
||||
private bool _loading;
|
||||
private string _errorMessage = "";
|
||||
|
||||
private async Task RegisterAsync()
|
||||
{
|
||||
_loading = true;
|
||||
_errorMessage = "";
|
||||
try
|
||||
{
|
||||
var result = await Api.RegisterAsync(_email, _password, _displayName);
|
||||
if (result is null)
|
||||
{
|
||||
_errorMessage = "Erreur lors de l'inscription";
|
||||
return;
|
||||
}
|
||||
Auth.Login(result);
|
||||
Snackbar.Add("Compte créé avec succès", Severity.Success);
|
||||
Navigation.NavigateTo("/dashboard");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_errorMessage = $"Erreur : {ex.Message}";
|
||||
}
|
||||
finally { _loading = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
@page "/sites/{Id:guid}"
|
||||
@attribute [Authorize]
|
||||
@layout MainLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject ISnackbar Snackbar
|
||||
@inject NavigationManager Nav
|
||||
|
||||
<MudText Typo="Typo.h4" Class="mb-6">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Videocam" Class="mr-2" />
|
||||
Site : @_site?.Name
|
||||
</MudText>
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else if (_site is null)
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning">Site introuvable</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudPaper Elevation="2" Class="pa-6 mb-6" Style="border-radius: 12px;">
|
||||
<MudText Typo="Typo.h6" Class="mb-4">Informations</MudText>
|
||||
<MudGrid>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Nom</MudText>
|
||||
<MudText Typo="Typo.body1">@_site.Name</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Adresse</MudText>
|
||||
<MudText Typo="Typo.body1">@(_site.Address ?? "-")</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Fuseau horaire</MudText>
|
||||
<MudText Typo="Typo.body1">@_site.Timezone</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Statut</MudText>
|
||||
<MudText Color="@(_site.Enabled ? Color.Success : Color.Default)">
|
||||
@(_site.Enabled ? "● Actif" : "○ Inactif")
|
||||
</MudText>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
</MudPaper>
|
||||
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Default" OnClick="@(() => Nav.NavigateTo("/sites"))">
|
||||
← Retour aux sites
|
||||
</MudButton>
|
||||
}
|
||||
|
||||
@code {
|
||||
[Parameter] public Guid Id { get; set; }
|
||||
|
||||
private SiteItem? _site;
|
||||
private bool _loading = true;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
_site = await Api.GetSiteAsync(Id);
|
||||
}
|
||||
catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); }
|
||||
finally { _loading = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
@page "/sites"
|
||||
@attribute [Authorize]
|
||||
@layout MainLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudText Typo="Typo.h4" Class="mb-6">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Videocam" Class="mr-2" />
|
||||
Sites
|
||||
</MudText>
|
||||
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => _showCreate = true)" Class="mb-4">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> Nouveau site
|
||||
</MudButton>
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@_sites" Hover="true" Striped="true" Elevation="2">
|
||||
<HeaderContent>
|
||||
<MudTh>Nom</MudTh>
|
||||
<MudTh>Adresse</MudTh>
|
||||
<MudTh>Fuseau</MudTh>
|
||||
<MudTh>Statut</MudTh>
|
||||
<MudTh>Actions</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd DataLabel="Nom"><MudLink Href="@($"/sites/{context.Id}")">@context.Name</MudLink></MudTd>
|
||||
<MudTd DataLabel="Adresse">@context.Address</MudTd>
|
||||
<MudTd DataLabel="Fuseau">@context.Timezone</MudTd>
|
||||
<MudTd DataLabel="Statut">
|
||||
<MudText Color="@(context.Enabled ? Color.Success : Color.Default)" Typo="Typo.body2">
|
||||
@(context.Enabled ? "● Actif" : "○ Inactif")
|
||||
</MudText>
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Actions">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ContentCopy" Size="Size.Small"
|
||||
OnClick="@(() => CopyToken(context.Id))" />
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small" Color="Color.Error"
|
||||
OnClick="@(() => DeleteSite(context.Id, context.Name))" />
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
<NoRecordsContent>
|
||||
<MudText Align="Align.Center" Class="py-4">Aucun site.</MudText>
|
||||
</NoRecordsContent>
|
||||
</MudTable>
|
||||
}
|
||||
|
||||
@if (_showCreate)
|
||||
{
|
||||
<MudOverlay Visible="@_showCreate" OnClick="@(() => _showCreate = false)" />
|
||||
<MudDialog @bind-Visible="_showCreate">
|
||||
<TitleContent><MudText Typo="Typo.h6">Nouveau site</MudText></TitleContent>
|
||||
<DialogContent>
|
||||
<MudTextField @bind-Value="_newName" Label="Nom du site *" Variant="Variant.Outlined"
|
||||
Class="mb-4" Required="true" Immediate="true" />
|
||||
<MudTextField @bind-Value="_newAddress" Label="Adresse" Variant="Variant.Outlined" Class="mb-4" />
|
||||
<MudTextField @bind-Value="_newTimezone" Label="Fuseau horaire" Variant="Variant.Outlined"
|
||||
Class="mb-4" HelperText="Ex: Europe/Paris (défaut: UTC)" />
|
||||
@if (!string.IsNullOrEmpty(_creationError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_creationError</MudAlert>
|
||||
}
|
||||
@if (!string.IsNullOrEmpty(_createdToken))
|
||||
{
|
||||
<MudAlert Severity="Severity.Success" Class="mb-4">
|
||||
<strong>Token d'enregistrement :</strong><br />
|
||||
<code class="d-block mt-2 p-2" style="background:#f5f5f5;word-break:break-all;font-size:0.9rem;">
|
||||
@_createdToken
|
||||
</code>
|
||||
<MudText Typo="Typo.body2" Color="Color.Warning" Class="mt-2">
|
||||
⚠ Copiez ce token maintenant. Il ne sera plus affiché.
|
||||
</MudText>
|
||||
</MudAlert>
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@CancelCreate">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@ConfirmCreate"
|
||||
Disabled="@IsCreateDisabled">
|
||||
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
@(!string.IsNullOrEmpty(_createdToken) ? "Fermer" : "Créer")
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
}
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<SiteItem>? _sites;
|
||||
private bool _loading = true;
|
||||
private bool _showCreate;
|
||||
private bool _saving;
|
||||
private string _newName = "";
|
||||
private string? _newAddress;
|
||||
private string? _newTimezone;
|
||||
private string _creationError = "";
|
||||
private string _createdToken = "";
|
||||
private bool IsCreateDisabled => _saving || !string.IsNullOrEmpty(_createdToken);
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadSites();
|
||||
|
||||
private async Task LoadSites()
|
||||
{
|
||||
_loading = true;
|
||||
try
|
||||
{
|
||||
var result = await Api.GetSitesAsync();
|
||||
_sites = result?.Items;
|
||||
}
|
||||
catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); }
|
||||
finally { _loading = false; }
|
||||
}
|
||||
|
||||
private void CancelCreate()
|
||||
{
|
||||
_showCreate = false;
|
||||
_creationError = "";
|
||||
_createdToken = "";
|
||||
_newName = "";
|
||||
_newAddress = null;
|
||||
_newTimezone = null;
|
||||
}
|
||||
|
||||
private async Task ConfirmCreate()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_newName)) { _creationError = "Le nom est requis"; return; }
|
||||
_saving = true;
|
||||
_creationError = "";
|
||||
try
|
||||
{
|
||||
var result = await Api.CreateSiteAsync(_newName, _newAddress, _newTimezone);
|
||||
if (result is null) { _creationError = "Erreur lors de la création"; return; }
|
||||
_createdToken = result.RegistrationToken ?? "Token non disponible";
|
||||
Snackbar.Add("Site créé avec succès", Severity.Success);
|
||||
await LoadSites();
|
||||
}
|
||||
catch (Exception ex) { _creationError = $"Erreur : {ex.Message}"; }
|
||||
finally { _saving = false; }
|
||||
}
|
||||
|
||||
private async Task CopyToken(Guid siteId)
|
||||
{
|
||||
Snackbar.Add("Génération du token...", Severity.Info);
|
||||
// For MVP, the token is generated at creation time
|
||||
// A dedicated token generation endpoint can be called here
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task DeleteSite(Guid id, string name)
|
||||
{
|
||||
if (await Api.DeleteSiteAsync(id))
|
||||
{
|
||||
Snackbar.Add($"Site \"{name}\" supprimé", Severity.Success);
|
||||
await LoadSites();
|
||||
}
|
||||
else
|
||||
Snackbar.Add("Erreur lors de la suppression", Severity.Error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
@page "/users"
|
||||
@attribute [Authorize]
|
||||
@layout MainLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudText Typo="Typo.h4" Class="mb-6">
|
||||
<MudIcon Icon="@Icons.Material.Filled.People" Class="mr-2" />
|
||||
Utilisateurs
|
||||
</MudText>
|
||||
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => _showCreate = true)" Class="mb-4">
|
||||
<MudIcon Icon="@Icons.Material.Filled.PersonAdd" Class="mr-1" /> Nouvel utilisateur
|
||||
</MudButton>
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTable Items="@_users" Hover="true" Striped="true" Elevation="2">
|
||||
<HeaderContent>
|
||||
<MudTh>Nom</MudTh>
|
||||
<MudTh>Email</MudTh>
|
||||
<MudTh>Rôles</MudTh>
|
||||
<MudTh>Statut</MudTh>
|
||||
<MudTh>Inscrit le</MudTh>
|
||||
<MudTh>Actions</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd DataLabel="Nom">@context.DisplayName</MudTd>
|
||||
<MudTd DataLabel="Email">@context.Email</MudTd>
|
||||
<MudTd DataLabel="Rôles">
|
||||
@foreach (var r in context.Roles ?? [])
|
||||
{
|
||||
<MudText Typo="Typo.body2" Class="d-inline mr-1"
|
||||
Color="@(r=="Admin"?Color.Tertiary:r=="Supervisor"?Color.Secondary:Color.Primary)">
|
||||
@r
|
||||
</MudText>
|
||||
}
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Statut">
|
||||
@if (context.IsLockedOut)
|
||||
{
|
||||
<MudText Color="Color.Error" Typo="Typo.body2">🔒 Verrouillé</MudText>
|
||||
}
|
||||
else if (!context.EmailConfirmed)
|
||||
{
|
||||
<MudText Color="Color.Warning" Typo="Typo.body2">⏳ En attente</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Color="Color.Success" Typo="Typo.body2">✓ Actif</MudText>
|
||||
}
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Inscrit le">@context.CreatedAt.ToString("g")</MudTd>
|
||||
<MudTd DataLabel="Actions">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Edit" Size="Size.Small"
|
||||
OnClick="@(() => OpenEdit(context))" />
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
<NoRecordsContent>
|
||||
<MudText Align="Align.Center" Class="py-4">Aucun utilisateur</MudText>
|
||||
</NoRecordsContent>
|
||||
</MudTable>
|
||||
|
||||
@* Pagination *@
|
||||
<MudPaper Class="d-flex align-center pa-4 mt-4">
|
||||
<MudText Typo="Typo.body2" Class="mr-4">
|
||||
Page @_page sur @_totalPages (@_total utilisateurs)
|
||||
</MudText>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Class="mr-2"
|
||||
Disabled="@(_page <= 1)" OnClick="@(() => GoToPage(_page - 1))">
|
||||
← Précédent
|
||||
</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small"
|
||||
Disabled="@(_page >= _totalPages)" OnClick="@(() => GoToPage(_page + 1))">
|
||||
Suivant →
|
||||
</MudButton>
|
||||
</MudPaper>
|
||||
}
|
||||
|
||||
@* Dialog: Créer un utilisateur *@
|
||||
@if (_showCreate)
|
||||
{
|
||||
<MudOverlay Visible="@_showCreate" OnClick="@(() => _showCreate = false)" />
|
||||
<MudDialog @bind-Visible="_showCreate">
|
||||
<TitleContent><MudText Typo="Typo.h6">Nouvel utilisateur</MudText></TitleContent>
|
||||
<DialogContent>
|
||||
<MudTextField @bind-Value="_createEmail" Label="Email *" Variant="Variant.Outlined"
|
||||
Class="mb-4" Required="true" Immediate="true" />
|
||||
<MudTextField @bind-Value="_createDisplayName" Label="Nom d'affichage *" Variant="Variant.Outlined"
|
||||
Class="mb-4" Required="true" Immediate="true" />
|
||||
<MudTextField @bind-Value="_createPassword" Label="Mot de passe *" Variant="Variant.Outlined"
|
||||
InputType="InputType.Password" Class="mb-4" Required="true" Immediate="true"
|
||||
HelperText="Minimum 12 caractères" />
|
||||
<MudText Typo="Typo.body2" Class="mb-2">Rôle</MudText>
|
||||
<MudSelect @bind-Value="_createRole" Label="Rôle" Variant="Variant.Outlined" Class="mb-4">
|
||||
<MudSelectItem Value="@("Viewer")">Viewer</MudSelectItem>
|
||||
<MudSelectItem Value="@("Supervisor")">Supervisor</MudSelectItem>
|
||||
<MudSelectItem Value="@("Admin")">Admin</MudSelectItem>
|
||||
</MudSelect>
|
||||
@if (!string.IsNullOrEmpty(_createError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_createError</MudAlert>
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _showCreate = false)">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@CreateUser" Disabled="@_saving">
|
||||
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
Créer
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
}
|
||||
|
||||
@* Dialog: Modifier un utilisateur *@
|
||||
@if (_editUser is not null && _showEdit)
|
||||
{
|
||||
<MudOverlay Visible="@_showEdit" OnClick="@(() => _showEdit = false)" />
|
||||
<MudDialog @bind-Visible="_showEdit" Class="edit-user-dialog">
|
||||
<TitleContent><MudText Typo="Typo.h6">Utilisateur : @_editUser.DisplayName</MudText></TitleContent>
|
||||
<DialogContent>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">@_editUser.Email</MudText>
|
||||
|
||||
@* Section: Informations *@
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2">Informations</MudText>
|
||||
<MudTextField @bind-Value="_editDisplayName" Label="Nom d'affichage" Variant="Variant.Outlined"
|
||||
Class="mb-4" Immediate="true" />
|
||||
<MudTextField @bind-Value="_editTheme" Label="Thème" Variant="Variant.Outlined"
|
||||
Class="mb-4" Immediate="true" HelperText="Light, Dark ou Auto" />
|
||||
|
||||
@* Section: Rôles *@
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">Rôles</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-2">
|
||||
Sélectionnez les rôles de l'utilisateur
|
||||
</MudText>
|
||||
<MudSelect @bind-Value="_editRole" Label="Rôle" Variant="Variant.Outlined" Class="mb-4">
|
||||
<MudSelectItem Value="@("Viewer")">Viewer (lecture seule)</MudSelectItem>
|
||||
<MudSelectItem Value="@("Supervisor")">Supervisor (gestion sites/caméras)</MudSelectItem>
|
||||
<MudSelectItem Value="@("Admin")">Admin (accès complet)</MudSelectItem>
|
||||
</MudSelect>
|
||||
|
||||
@* Section: Statut du compte *@
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">Statut du compte</MudText>
|
||||
<MudPaper Class="pa-4 mb-4" Elevation="0" Style="background: #f9f9f9; border-radius: 8px;">
|
||||
<MudGrid>
|
||||
<MudItem xs="6">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">2FA</MudText>
|
||||
<MudText Typo="Typo.body1">
|
||||
<MudIcon Icon="@(_editUser.TwoFactorEnabled ? Icons.Material.Filled.CheckCircle : Icons.Material.Filled.Cancel)"
|
||||
Color="@(_editUser.TwoFactorEnabled ? Color.Success : Color.Default)" Size="Size.Small" />
|
||||
@(_editUser.TwoFactorEnabled ? "Activé" : "Désactivé")
|
||||
</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="6">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Email confirmé</MudText>
|
||||
<MudText Typo="Typo.body1">
|
||||
<MudIcon Icon="@(_editUser.EmailConfirmed ? Icons.Material.Filled.CheckCircle : Icons.Material.Filled.Cancel)"
|
||||
Color="@(_editUser.EmailConfirmed ? Color.Success : Color.Default)" Size="Size.Small" />
|
||||
@(_editUser.EmailConfirmed ? "Oui" : "Non")
|
||||
</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="6" Class="mt-2">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Tentatives échouées</MudText>
|
||||
<MudText Typo="Typo.body1">@_editUser.AccessFailedCount / 5</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="6" Class="mt-2">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Verrouillé</MudText>
|
||||
<MudText Typo="Typo.body1" Color="@(_editUser.IsLockedOut ? Color.Error : Color.Success)">
|
||||
@(_editUser.IsLockedOut ? "Oui" : "Non")
|
||||
</MudText>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
</MudPaper>
|
||||
|
||||
@* Actions du compte *@
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">Actions</MudText>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Warning" FullWidth="true" Class="mb-2"
|
||||
OnClick="@ResetPassword">
|
||||
<MudIcon Icon="@Icons.Material.Filled.LockReset" Class="mr-1" /> Réinitialiser le mot de passe
|
||||
</MudButton>
|
||||
@if (_editUser.IsLockedOut)
|
||||
{
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Success" FullWidth="true" Class="mb-2"
|
||||
OnClick="@UnlockUser">
|
||||
<MudIcon Icon="@Icons.Material.Filled.LockOpen" Class="mr-1" /> Déverrouiller le compte
|
||||
</MudButton>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Error" FullWidth="true" Class="mb-2"
|
||||
OnClick="@LockUser">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Lock" Class="mr-1" /> Verrouiller le compte
|
||||
</MudButton>
|
||||
}
|
||||
|
||||
@if (!string.IsNullOrEmpty(_editError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mt-2">@_editError</MudAlert>
|
||||
}
|
||||
@if (!string.IsNullOrEmpty(_temporaryPassword))
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning" Class="mt-2">
|
||||
<strong>Nouveau mot de passe temporaire :</strong><br />
|
||||
<code class="mt-2 d-block p-2" style="background:#fff;word-break:break-all;">
|
||||
@_temporaryPassword
|
||||
</code>
|
||||
<MudText Typo="Typo.body2" Color="Color.Warning" Class="mt-2">
|
||||
⚠ L'utilisateur devra changer ce mot de passe à la prochaine connexion.
|
||||
</MudText>
|
||||
</MudAlert>
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@CloseEdit">Fermer</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@SaveEdit" Disabled="@_saving">
|
||||
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
Enregistrer
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
}
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<UserItem>? _users;
|
||||
private bool _loading = true;
|
||||
private int _page = 1;
|
||||
private int _totalPages = 1;
|
||||
private int _total;
|
||||
private bool _saving;
|
||||
|
||||
// Create dialog
|
||||
private bool _showCreate;
|
||||
private string _createEmail = "";
|
||||
private string _createPassword = "";
|
||||
private string _createDisplayName = "";
|
||||
private string _createRole = "Viewer";
|
||||
private string _createError = "";
|
||||
|
||||
// Edit dialog
|
||||
private UserItem? _editUser;
|
||||
private bool _showEdit;
|
||||
private string _editDisplayName = "";
|
||||
private string _editTheme = "";
|
||||
private string _editRole = "";
|
||||
private string _editError = "";
|
||||
private string _temporaryPassword = "";
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadUsers();
|
||||
|
||||
private async Task LoadUsers()
|
||||
{
|
||||
_loading = true;
|
||||
try
|
||||
{
|
||||
var result = await Api.GetUsersAsync(_page);
|
||||
if (result is not null)
|
||||
{
|
||||
_users = result.Items;
|
||||
_total = result.TotalCount;
|
||||
_totalPages = Math.Max(1, (int)Math.Ceiling(result.TotalCount / (double)result.PageSize));
|
||||
}
|
||||
}
|
||||
catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); }
|
||||
finally { _loading = false; }
|
||||
}
|
||||
|
||||
private async Task GoToPage(int p)
|
||||
{
|
||||
_page = p;
|
||||
await LoadUsers();
|
||||
}
|
||||
|
||||
// ─── Create ───────────────────────────────────────────────────
|
||||
|
||||
private async Task CreateUser()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_createEmail) || string.IsNullOrWhiteSpace(_createPassword)
|
||||
|| string.IsNullOrWhiteSpace(_createDisplayName))
|
||||
{ _createError = "Tous les champs sont requis"; return; }
|
||||
_saving = true;
|
||||
_createError = "";
|
||||
try
|
||||
{
|
||||
var result = await Api.CreateUserAsync(_createEmail, _createPassword, _createDisplayName,
|
||||
new List<string> { _createRole });
|
||||
if (result is null) { _createError = "Erreur lors de la création"; return; }
|
||||
_showCreate = false;
|
||||
_createEmail = ""; _createPassword = ""; _createDisplayName = ""; _createRole = "Viewer";
|
||||
Snackbar.Add("Utilisateur créé avec succès", Severity.Success);
|
||||
await LoadUsers();
|
||||
}
|
||||
catch (Exception ex) { _createError = $"Erreur : {ex.Message}"; }
|
||||
finally { _saving = false; }
|
||||
}
|
||||
|
||||
// ─── Edit ─────────────────────────────────────────────────────
|
||||
|
||||
private void OpenEdit(UserItem user)
|
||||
{
|
||||
_editUser = user;
|
||||
_editDisplayName = user.DisplayName;
|
||||
_editTheme = user.Theme ?? "Auto";
|
||||
_editRole = user.Roles?.FirstOrDefault() ?? "Viewer";
|
||||
_editError = "";
|
||||
_temporaryPassword = "";
|
||||
_showEdit = true;
|
||||
}
|
||||
|
||||
private void CloseEdit()
|
||||
{
|
||||
_showEdit = false;
|
||||
_editUser = null;
|
||||
_temporaryPassword = "";
|
||||
}
|
||||
|
||||
private async Task SaveEdit()
|
||||
{
|
||||
if (_editUser is null) return;
|
||||
_saving = true;
|
||||
_editError = "";
|
||||
try
|
||||
{
|
||||
// Update display name
|
||||
await Api.UpdateUserAsync(_editUser.Id, _editDisplayName, _editTheme, null);
|
||||
// Update roles
|
||||
await Api.AssignRolesAsync(_editUser.Id, new List<string> { _editRole });
|
||||
Snackbar.Add("Utilisateur mis à jour", Severity.Success);
|
||||
CloseEdit();
|
||||
await LoadUsers();
|
||||
}
|
||||
catch (Exception ex) { _editError = $"Erreur : {ex.Message}"; }
|
||||
finally { _saving = false; }
|
||||
}
|
||||
|
||||
// ─── Lock / Unlock / Reset Password ───────────────────────────
|
||||
|
||||
private async Task LockUser()
|
||||
{
|
||||
if (_editUser is null) return;
|
||||
if (await Api.LockUserAsync(_editUser.Id))
|
||||
{
|
||||
_editUser.IsLockedOut = true;
|
||||
Snackbar.Add("Compte verrouillé", Severity.Success);
|
||||
}
|
||||
else Snackbar.Add("Erreur", Severity.Error);
|
||||
}
|
||||
|
||||
private async Task UnlockUser()
|
||||
{
|
||||
if (_editUser is null) return;
|
||||
if (await Api.UnlockUserAsync(_editUser.Id))
|
||||
{
|
||||
_editUser.IsLockedOut = false;
|
||||
_editUser.AccessFailedCount = 0;
|
||||
Snackbar.Add("Compte déverrouillé", Severity.Success);
|
||||
}
|
||||
else Snackbar.Add("Erreur", Severity.Error);
|
||||
}
|
||||
|
||||
private async Task ResetPassword()
|
||||
{
|
||||
if (_editUser is null) return;
|
||||
_saving = true;
|
||||
_temporaryPassword = "";
|
||||
try
|
||||
{
|
||||
var result = await Api.ResetPasswordAsync(_editUser.Id);
|
||||
if (result is null) { _editError = "Erreur lors de la réinitialisation"; return; }
|
||||
_temporaryPassword = result.TemporaryPassword;
|
||||
Snackbar.Add("Mot de passe réinitialisé", Severity.Success);
|
||||
}
|
||||
catch (Exception ex) { _editError = $"Erreur : {ex.Message}"; }
|
||||
finally { _saving = false; }
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,10 @@
|
||||
@using static Microsoft.AspNetCore.Components.Web.RenderMode
|
||||
@using Microsoft.AspNetCore.Components.Web.Virtualization
|
||||
@using Microsoft.JSInterop
|
||||
@using MudBlazor
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Heimdall.Web
|
||||
@using Heimdall.Web.Components
|
||||
@using Heimdall.Web.Components.Layout
|
||||
@using Heimdall.Web.Components.Pages
|
||||
@using Heimdall.Web.Services
|
||||
@@ -1,25 +1,47 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Web.Components;
|
||||
using Heimdall.Web.Services;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using MudBlazor.Services;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents();
|
||||
|
||||
// Auth for Blazor
|
||||
builder.Services.AddScoped<AuthenticationStateProvider, HeimdallAuthStateProvider>();
|
||||
builder.Services.AddAuthorizationCore();
|
||||
|
||||
builder.Services.AddMudServices(config =>
|
||||
{
|
||||
config.SnackbarConfiguration.PositionClass = "mud-alert-center-top";
|
||||
config.SnackbarConfiguration.PreventDuplicates = true;
|
||||
config.SnackbarConfiguration.ShowCloseIcon = true;
|
||||
config.SnackbarConfiguration.VisibleStateDuration = 4000;
|
||||
});
|
||||
|
||||
builder.Services.AddScoped<HeimdallApiClient>();
|
||||
builder.Services.AddHttpClient("HeimdallApi", client =>
|
||||
{
|
||||
client.BaseAddress = new Uri("http://localhost:5000/");
|
||||
client.Timeout = TimeSpan.FromSeconds(30);
|
||||
});
|
||||
|
||||
// Auth state
|
||||
builder.Services.AddScoped<AuthState>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseExceptionHandler("/Error", createScopeForErrors: true);
|
||||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
||||
app.UseHsts();
|
||||
}
|
||||
|
||||
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAntiforgery();
|
||||
|
||||
app.MapStaticAssets();
|
||||
app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode();
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Heimdall.Web.Services;
|
||||
|
||||
public class AuthState
|
||||
{
|
||||
public string? AccessToken { get; set; }
|
||||
public string? RefreshToken { get; set; }
|
||||
public UserInfo? User { get; set; }
|
||||
public bool IsLoggedIn => User is not null;
|
||||
|
||||
public void Login(AuthResponse response)
|
||||
{
|
||||
AccessToken = response.AccessToken;
|
||||
RefreshToken = response.RefreshToken;
|
||||
User = response.User;
|
||||
}
|
||||
|
||||
public void Logout()
|
||||
{
|
||||
AccessToken = null;
|
||||
RefreshToken = null;
|
||||
User = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Response DTOs ────────────────────────────────────────────────
|
||||
|
||||
public record AuthResponse(
|
||||
[property: JsonPropertyName("accessToken")] string AccessToken,
|
||||
[property: JsonPropertyName("refreshToken")] string RefreshToken,
|
||||
[property: JsonPropertyName("expiresAt")] DateTime ExpiresAt,
|
||||
[property: JsonPropertyName("requires2fa")] bool Requires2fa,
|
||||
[property: JsonPropertyName("user")] UserInfo? User);
|
||||
|
||||
public record UserInfo(
|
||||
[property: JsonPropertyName("id")] Guid Id,
|
||||
[property: JsonPropertyName("email")] string Email,
|
||||
[property: JsonPropertyName("displayName")] string DisplayName,
|
||||
[property: JsonPropertyName("roles")] IList<string>? Roles);
|
||||
|
||||
public record SiteItem(
|
||||
[property: JsonPropertyName("id")] Guid Id,
|
||||
[property: JsonPropertyName("name")] string Name,
|
||||
[property: JsonPropertyName("address")] string? Address,
|
||||
[property: JsonPropertyName("timezone")] string Timezone,
|
||||
[property: JsonPropertyName("enabled")] bool Enabled,
|
||||
[property: JsonPropertyName("createdAt")] DateTime CreatedAt);
|
||||
|
||||
public record SiteWithTokenResult(
|
||||
[property: JsonPropertyName("id")] Guid Id,
|
||||
[property: JsonPropertyName("name")] string Name,
|
||||
[property: JsonPropertyName("address")] string? Address,
|
||||
[property: JsonPropertyName("timezone")] string Timezone,
|
||||
[property: JsonPropertyName("registrationToken")] string? RegistrationToken,
|
||||
[property: JsonPropertyName("tokenExpiresAt")] DateTime? TokenExpiresAt);
|
||||
|
||||
public class UserItem
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Email { get; set; } = "";
|
||||
public string DisplayName { get; set; } = "";
|
||||
public string? Theme { get; set; }
|
||||
public string Language { get; set; } = "fr";
|
||||
public IList<string>? Roles { get; set; }
|
||||
public IList<Guid>? SiteIds { get; set; }
|
||||
public bool TwoFactorEnabled { get; set; }
|
||||
public bool IsLockedOut { get; set; }
|
||||
public DateTime? LockoutEnd { get; set; }
|
||||
public int AccessFailedCount { get; set; }
|
||||
public bool EmailConfirmed { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
}
|
||||
|
||||
public record PasswordResetResult(
|
||||
[property: JsonPropertyName("temporaryPassword")] string TemporaryPassword);
|
||||
|
||||
public record PagedData<T>(
|
||||
[property: JsonPropertyName("items")] IReadOnlyList<T> Items,
|
||||
[property: JsonPropertyName("totalCount")] int TotalCount,
|
||||
[property: JsonPropertyName("page")] int Page,
|
||||
[property: JsonPropertyName("pageSize")] int PageSize);
|
||||
@@ -0,0 +1,151 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Heimdall.Web.Services;
|
||||
|
||||
public class HeimdallApiClient
|
||||
{
|
||||
private readonly IHttpClientFactory _httpFactory;
|
||||
private readonly AuthState _authState;
|
||||
private static readonly JsonSerializerOptions Json = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
||||
};
|
||||
|
||||
public HeimdallApiClient(IHttpClientFactory httpFactory, AuthState authState)
|
||||
{
|
||||
_httpFactory = httpFactory;
|
||||
_authState = authState;
|
||||
}
|
||||
|
||||
private HttpClient CreateClient()
|
||||
{
|
||||
var client = _httpFactory.CreateClient("HeimdallApi");
|
||||
if (_authState.AccessToken is not null)
|
||||
client.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("Bearer", _authState.AccessToken);
|
||||
return client;
|
||||
}
|
||||
|
||||
// ─── Auth ─────────────────────────────────────────────────────
|
||||
|
||||
public async Task<AuthResponse?> LoginAsync(string email, string password)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/auth/login", new { email, password });
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<AuthResponse>(Json);
|
||||
}
|
||||
|
||||
public async Task<AuthResponse?> RegisterAsync(string email, string password, string displayName)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/auth/register",
|
||||
new { email, password, displayName });
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<AuthResponse>(Json);
|
||||
}
|
||||
|
||||
// ─── Users ────────────────────────────────────────────────────
|
||||
|
||||
public async Task<PagedData<UserItem>?> GetUsersAsync(int page = 1, int pageSize = 20)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.GetFromJsonAsync<PagedData<UserItem>>(
|
||||
$"api/users?page={page}&pageSize={pageSize}", Json);
|
||||
}
|
||||
|
||||
public async Task<UserItem?> GetUserAsync(Guid id)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.GetFromJsonAsync<UserItem>($"api/users/{id}", Json);
|
||||
}
|
||||
|
||||
public async Task<UserItem?> CreateUserAsync(string email, string password, string displayName, IList<string> roles)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/users",
|
||||
new { email, password, displayName, roles }, Json);
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<UserItem>(Json);
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateUserAsync(Guid id, string displayName, string? theme, string? language)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PutAsJsonAsync($"api/users/{id}",
|
||||
new { displayName, theme, language }, Json);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
public async Task<bool> AssignRolesAsync(Guid userId, IList<string> roles)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PutAsJsonAsync($"api/users/{userId}/roles",
|
||||
new { roles }, Json);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
public async Task<bool> AssignSitesAsync(Guid userId, IList<Guid> siteIds)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PutAsJsonAsync($"api/users/{userId}/sites",
|
||||
new { siteIds }, Json);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
public async Task<PasswordResetResult?> ResetPasswordAsync(Guid userId)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync($"api/users/{userId}/reset-password", null);
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<PasswordResetResult>(Json);
|
||||
}
|
||||
|
||||
public async Task<bool> LockUserAsync(Guid userId)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync($"api/users/{userId}/lock", null);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
public async Task<bool> UnlockUserAsync(Guid userId)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync($"api/users/{userId}/unlock", null);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
// ─── Sites ────────────────────────────────────────────────────
|
||||
|
||||
public async Task<PagedData<SiteItem>?> GetSitesAsync(int page = 1, int pageSize = 20)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.GetFromJsonAsync<PagedData<SiteItem>>(
|
||||
$"api/sites?page={page}&pageSize={pageSize}", Json);
|
||||
}
|
||||
|
||||
public async Task<SiteItem?> GetSiteAsync(Guid id)
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.GetFromJsonAsync<SiteItem>($"api/sites/{id}", Json);
|
||||
}
|
||||
|
||||
public async Task<SiteWithTokenResult?> CreateSiteAsync(string name, string? address, string? timezone)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/sites",
|
||||
new { name, address, timezone }, Json);
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<SiteWithTokenResult>(Json);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteSiteAsync(Guid id)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.DeleteAsync($"api/sites/{id}");
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
|
||||
namespace Heimdall.Web.Services;
|
||||
|
||||
public class HeimdallAuthStateProvider : AuthenticationStateProvider
|
||||
{
|
||||
private readonly AuthState _authState;
|
||||
|
||||
public HeimdallAuthStateProvider(AuthState authState)
|
||||
{
|
||||
_authState = authState;
|
||||
}
|
||||
|
||||
public override Task<AuthenticationState> GetAuthenticationStateAsync()
|
||||
{
|
||||
if (!_authState.IsLoggedIn || _authState.User is null)
|
||||
{
|
||||
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
|
||||
}
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, _authState.User.Id.ToString()),
|
||||
new(ClaimTypes.Name, _authState.User.DisplayName),
|
||||
new(ClaimTypes.Email, _authState.User.Email),
|
||||
};
|
||||
|
||||
if (_authState.User.Roles is not null)
|
||||
{
|
||||
foreach (var role in _authState.User.Roles)
|
||||
{
|
||||
claims.Add(new Claim(ClaimTypes.Role, role));
|
||||
claims.Add(new Claim("permission", role)); // Map role to permission for policies
|
||||
}
|
||||
}
|
||||
|
||||
var identity = new ClaimsIdentity(claims, "HeimdallAuth");
|
||||
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(identity)));
|
||||
}
|
||||
|
||||
public void NotifyAuthStateChanged()
|
||||
{
|
||||
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Net.Http.Json;
|
||||
using Heimdall.IntegrationTests.Factories;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.IntegrationTests.Controllers;
|
||||
|
||||
public class AuthControllerTests : IClassFixture<HeimdallWebApplicationFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
|
||||
public AuthControllerTests(HeimdallWebApplicationFactory factory)
|
||||
{
|
||||
_client = factory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_ValidRequest_ReturnsOk()
|
||||
{
|
||||
var response = await _client.PostAsJsonAsync("api/auth/register", new
|
||||
{
|
||||
email = $"test-{Guid.NewGuid()}@heimdall.test",
|
||||
password = "TestPassword123!",
|
||||
displayName = "Test User"
|
||||
});
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_DuplicateEmail_ReturnsConflict()
|
||||
{
|
||||
var email = $"dup-{Guid.NewGuid()}@heimdall.test";
|
||||
|
||||
var first = await _client.PostAsJsonAsync("api/auth/register", new
|
||||
{
|
||||
email,
|
||||
password = "TestPassword123!",
|
||||
displayName = "User 1"
|
||||
});
|
||||
first.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var second = await _client.PostAsJsonAsync("api/auth/register", new
|
||||
{
|
||||
email,
|
||||
password = "TestPassword123!",
|
||||
displayName = "User 2"
|
||||
});
|
||||
|
||||
second.StatusCode.ShouldBe(System.Net.HttpStatusCode.Conflict);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_ValidCredentials_ReturnsOk()
|
||||
{
|
||||
var email = $"login-{Guid.NewGuid()}@heimdall.test";
|
||||
await _client.PostAsJsonAsync("api/auth/register", new
|
||||
{
|
||||
email,
|
||||
password = "TestPassword123!",
|
||||
displayName = "Login User"
|
||||
});
|
||||
|
||||
var response = await _client.PostAsJsonAsync("api/auth/login", new
|
||||
{
|
||||
email,
|
||||
password = "TestPassword123!"
|
||||
});
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_InvalidPassword_ReturnsUnauthorized()
|
||||
{
|
||||
var email = $"badpwd-{Guid.NewGuid()}@heimdall.test";
|
||||
await _client.PostAsJsonAsync("api/auth/register", new
|
||||
{
|
||||
email,
|
||||
password = "TestPassword123!",
|
||||
displayName = "Bad Pwd User"
|
||||
});
|
||||
|
||||
var response = await _client.PostAsJsonAsync("api/auth/login", new
|
||||
{
|
||||
email,
|
||||
password = "WrongPassword!"
|
||||
});
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Heimdall.IntegrationTests.Factories;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.IntegrationTests.Controllers;
|
||||
|
||||
public class SitesControllerTests : IClassFixture<HeimdallWebApplicationFactory>
|
||||
{
|
||||
private readonly HeimdallWebApplicationFactory _factory;
|
||||
private static readonly JsonSerializerOptions Json = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
public SitesControllerTests(HeimdallWebApplicationFactory factory)
|
||||
{
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSites_WithoutAuth_ReturnsUnauthorized()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
var response = await client.GetAsync("api/sites?page=1&pageSize=10");
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSite_WithAuth_ReturnsOk()
|
||||
{
|
||||
var client = await CreateAuthenticatedAdminClient();
|
||||
|
||||
var response = await client.PostAsJsonAsync("api/sites", new
|
||||
{
|
||||
name = "Site Test",
|
||||
address = "Paris",
|
||||
timezone = "Europe/Paris"
|
||||
});
|
||||
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListSites_WithAuth_ReturnsOk()
|
||||
{
|
||||
var client = await CreateAuthenticatedAdminClient();
|
||||
|
||||
var response = await client.GetAsync("api/sites?page=1&pageSize=10");
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
private async Task<HttpClient> CreateAuthenticatedAdminClient()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
|
||||
// Login with seeded admin user
|
||||
var loginResponse = await client.PostAsJsonAsync("api/auth/login", new
|
||||
{
|
||||
email = "testadmin@heimdall.test",
|
||||
password = "TestAdmin123!"
|
||||
});
|
||||
|
||||
var content = await loginResponse.Content
|
||||
.ReadFromJsonAsync<AuthTestResponse>(Json);
|
||||
|
||||
client.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("Bearer", content!.AccessToken);
|
||||
|
||||
return client;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Heimdall.IntegrationTests.Factories;
|
||||
|
||||
public class HeimdallWebApplicationFactory : WebApplicationFactory<Program>
|
||||
{
|
||||
private readonly string _dbName = $"HeimdallTestDb_{Guid.NewGuid():N}";
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
Environment.SetEnvironmentVariable("JWT__KEY", "ThisIsATestKeyThatIsAtLeast32BytesLong!");
|
||||
Environment.SetEnvironmentVariable("JWT__ISSUER", "heimdall-test");
|
||||
Environment.SetEnvironmentVariable("JWT__AUDIENCE", "heimdall-test");
|
||||
|
||||
builder.UseEnvironment("Testing");
|
||||
builder.UseSetting("Cors:AllowedOrigins", "*");
|
||||
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
services.AddDbContext<AppDbContext>(options =>
|
||||
{
|
||||
options.UseInMemoryDatabase(_dbName);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="NSubstitute" Version="6.0.0" />
|
||||
<PackageReference Include="Shouldly" Version="4.3.0" />
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Heimdall.IntegrationTests;
|
||||
|
||||
public record AuthTestResponse(
|
||||
[property: JsonPropertyName("accessToken")] string AccessToken,
|
||||
[property: JsonPropertyName("refreshToken")] string RefreshToken,
|
||||
[property: JsonPropertyName("expiresAt")] DateTime ExpiresAt,
|
||||
[property: JsonPropertyName("requires2fa")] bool Requires2fa,
|
||||
[property: JsonPropertyName("user")] object? User);
|
||||
Reference in new issue
Block a user