diff --git a/src/Heimdall.Api/Controllers/UsersController.cs b/src/Heimdall.Api/Controllers/UsersController.cs new file mode 100644 index 0000000..4fb42fb --- /dev/null +++ b/src/Heimdall.Api/Controllers/UsersController.cs @@ -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 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 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 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 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 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 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 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 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 Unlock(Guid id, CancellationToken ct) + { + var result = await _userService.UnlockAsync(id, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } +} diff --git a/src/Heimdall.Api/Heimdall.Api.csproj b/src/Heimdall.Api/Heimdall.Api.csproj index b56ead6..0f78837 100644 --- a/src/Heimdall.Api/Heimdall.Api.csproj +++ b/src/Heimdall.Api/Heimdall.Api.csproj @@ -6,6 +6,10 @@ enable + + + + diff --git a/src/Heimdall.Api/Program.cs b/src/Heimdall.Api/Program.cs index 8d6436f..5a1a5c7 100644 --- a/src/Heimdall.Api/Program.cs +++ b/src/Heimdall.Api/Program.cs @@ -12,10 +12,17 @@ var builder = WebApplication.CreateBuilder(args); // ── Services ────────────────────────────────────────────────────── -builder.Services.AddControllers(options => +if (!builder.Environment.IsEnvironment("Testing")) { - options.Filters.Add(); -}); + builder.Services.AddControllers(options => + { + options.Filters.Add(); + }); +} +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(); - if (db.Database.GetPendingMigrations().Any()) + using (var scope = app.Services.CreateScope()) { - db.Database.Migrate(); + var db = scope.ServiceProvider.GetRequiredService(); + if (db.Database.GetPendingMigrations().Any()) + { + db.Database.Migrate(); + } } } @@ -97,6 +119,8 @@ using (var scope = app.Services.CreateScope()) { var roleManager = scope.ServiceProvider .GetRequiredService>(); + var userManager = scope.ServiceProvider + .GetRequiredService>(); 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()) diff --git a/src/Heimdall.Application/DTOs/UserDto.cs b/src/Heimdall.Application/DTOs/UserDto.cs new file mode 100644 index 0000000..a254ea2 --- /dev/null +++ b/src/Heimdall.Application/DTOs/UserDto.cs @@ -0,0 +1,30 @@ +namespace Heimdall.Application.DTOs; + +public record UserResponse( + Guid Id, + string Email, + string DisplayName, + string? Theme, + string Language, + IList Roles, + IList SiteIds, + bool TwoFactorEnabled, + bool IsLockedOut, + DateTime? LockoutEnd, + int AccessFailedCount, + bool EmailConfirmed, + DateTime CreatedAt); + +public record CreateUserRequest( + string Email, + string Password, + string DisplayName, + IList? Roles); + +public record UpdateUserRequest(string DisplayName, string? Theme, string? Language); + +public record AssignRolesRequest(IList Roles); + +public record AssignSitesRequest(IList SiteIds); + +public record ResetPasswordResponse(string TemporaryPassword); diff --git a/src/Heimdall.Application/Services/IUserService.cs b/src/Heimdall.Application/Services/IUserService.cs new file mode 100644 index 0000000..e6b5def --- /dev/null +++ b/src/Heimdall.Application/Services/IUserService.cs @@ -0,0 +1,17 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; + +namespace Heimdall.Application.Services; + +public interface IUserService +{ + Task>> ListAsync(int page, int pageSize, CancellationToken ct); + Task> GetByIdAsync(Guid id, CancellationToken ct); + Task> CreateAsync(CreateUserRequest request, CancellationToken ct); + Task> UpdateAsync(Guid id, UpdateUserRequest request, CancellationToken ct); + Task AssignRolesAsync(Guid id, AssignRolesRequest request, CancellationToken ct); + Task AssignSitesAsync(Guid id, AssignSitesRequest request, CancellationToken ct); + Task> ResetPasswordAsync(Guid id, CancellationToken ct); + Task LockAsync(Guid id, CancellationToken ct); + Task UnlockAsync(Guid id, CancellationToken ct); +} diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 23ba60f..10c63a6 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -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(options => { options.UseNpgsql(connectionString, npgsql => @@ -51,6 +54,7 @@ public static class DependencyInjection services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); return services; } diff --git a/src/Heimdall.Infrastructure/Services/UserService.cs b/src/Heimdall.Infrastructure/Services/UserService.cs new file mode 100644 index 0000000..705d4bc --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/UserService.cs @@ -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 _userManager; + private readonly AppDbContext _db; + + public UserService(UserManager userManager, AppDbContext db) + { + _userManager = userManager; + _db = db; + } + + public async Task>> 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(); + foreach (var user in users) + { + items.Add(await MapToResponse(user)); + } + + return ServiceResult>.Success( + new PagedResult(items, total, page, pageSize)); + } + + public async Task> GetByIdAsync(Guid id, CancellationToken ct) + { + var user = await _userManager.FindByIdAsync(id.ToString()); + if (user is null) + return ServiceResult.NotFound("User not found"); + + return ServiceResult.Success(await MapToResponse(user)); + } + + public async Task> CreateAsync(CreateUserRequest request, CancellationToken ct) + { + var existing = await _userManager.FindByEmailAsync(request.Email); + if (existing is not null) + return ServiceResult.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.Failure( + string.Join(", ", result.Errors.Select(e => e.Description))); + + // Assign default role + var roles = request.Roles is { Count: > 0 } ? request.Roles : new List { AppRoles.Viewer }; + await _userManager.AddToRolesAsync(user, roles); + + _db.AuditLogs.Add(new AuditLog(null, "UserCreated", "User", user.Id.ToString())); + await _db.SaveChangesAsync(ct); + + return ServiceResult.Success(await MapToResponse(user)); + } + + public async Task> UpdateAsync(Guid id, UpdateUserRequest request, CancellationToken ct) + { + var user = await _userManager.FindByIdAsync(id.ToString()); + if (user is null) + return ServiceResult.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.Failure( + string.Join(", ", result.Errors.Select(e => e.Description))); + + return ServiceResult.Success(await MapToResponse(user)); + } + + public async Task 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 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> ResetPasswordAsync(Guid id, CancellationToken ct) + { + var user = await _userManager.FindByIdAsync(id.ToString()); + if (user is null) + return ServiceResult.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.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.Success( + new ResetPasswordResponse(temporaryPassword)); + } + + public async Task 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 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 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()); + } +} diff --git a/src/Heimdall.Web/Components/App.razor b/src/Heimdall.Web/Components/App.razor index 40d066e..cb69fb6 100644 --- a/src/Heimdall.Web/Components/App.razor +++ b/src/Heimdall.Web/Components/App.razor @@ -5,8 +5,9 @@ - + + @@ -16,8 +17,8 @@ - + diff --git a/src/Heimdall.Web/Components/Layout/MainLayout.razor b/src/Heimdall.Web/Components/Layout/MainLayout.razor index 78624f3..981b532 100644 --- a/src/Heimdall.Web/Components/Layout/MainLayout.razor +++ b/src/Heimdall.Web/Components/Layout/MainLayout.razor @@ -1,23 +1,81 @@ @inherits LayoutComponentBase +@inject AuthState Auth +@inject NavigationManager Navigation -
- + + + -
-
- About -
+ + + + Heimdall + + @if (Auth.IsLoggedIn) + { + + + + + + + + @Auth.User?.DisplayName + @Auth.User?.Email + + + Déconnexion + + + } + -
+ + + @if (Auth.IsLoggedIn) + { + Navigation + + + Dashboard + + + Sites & Caméras + + + @if (Auth.User?.Roles?.Contains("Admin") == true) + { + Administration + + Utilisateurs + + } + + + } + else + { + + Connexion + + } + + + + + @Body -
-
-
+ + + -
- An unhandled error has occurred. - Reload - 🗙 -
+@code { + private bool _drawerOpen = true; + + private void Logout() + { + Auth.Logout(); + Navigation.NavigateTo("/login", true); + } +} diff --git a/src/Heimdall.Web/Components/Layout/MudBlazorLayout.razor b/src/Heimdall.Web/Components/Layout/MudBlazorLayout.razor new file mode 100644 index 0000000..b821904 --- /dev/null +++ b/src/Heimdall.Web/Components/Layout/MudBlazorLayout.razor @@ -0,0 +1,11 @@ +@inherits LayoutComponentBase + + + + + + + + @Body + + diff --git a/src/Heimdall.Web/Components/Pages/Dashboard.razor b/src/Heimdall.Web/Components/Pages/Dashboard.razor new file mode 100644 index 0000000..a61451e --- /dev/null +++ b/src/Heimdall.Web/Components/Pages/Dashboard.razor @@ -0,0 +1,102 @@ +@page "/" +@page "/dashboard" +@attribute [Authorize] +@layout MainLayout +@inject HeimdallApiClient Api +@inject AuthState Auth +@inject ISnackbar Snackbar + + + Dashboard + + + Bienvenue, @Auth.User?.DisplayName + + + + + + @_siteCount + Sites + + + + + @_cameraCount + Caméras + + + + + @_onlineCount + Sites actifs + + + + + + + Sites récents + + @if (_loading) + { + + } + else if (_sites?.Count > 0) + { + + + Nom + Adresse + Statut + Créé le + + + @context.Name + @context.Address + + + @(context.Enabled ? "● Actif" : "○ Inactif") + + + @context.CreatedAt.ToString("g") + + + } + else + { + + Aucun site. Créer un site + + } + + + +@code { + private int _siteCount; +#pragma warning disable CS0649 + private int _cameraCount; + private int _onlineCount; +#pragma warning restore CS0649 + private IReadOnlyList? _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; } + } +} diff --git a/src/Heimdall.Web/Components/Pages/Login.razor b/src/Heimdall.Web/Components/Pages/Login.razor new file mode 100644 index 0000000..19c696a --- /dev/null +++ b/src/Heimdall.Web/Components/Pages/Login.razor @@ -0,0 +1,75 @@ +@page "/login" +@layout MudBlazorLayout +@inject HeimdallApiClient Api +@inject AuthState Auth +@inject NavigationManager Navigation +@inject ISnackbar Snackbar + + + + + + Heimdall + + + Plateforme de surveillance vidéo + + + + + + @if (!string.IsNullOrEmpty(_errorMessage)) + { + @_errorMessage + } + + + @if (_loading) { } + Se connecter + + + + Pas encore de compte ? + Créer un compte + + + + +@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; } + } +} diff --git a/src/Heimdall.Web/Components/Pages/Register.razor b/src/Heimdall.Web/Components/Pages/Register.razor new file mode 100644 index 0000000..63dda30 --- /dev/null +++ b/src/Heimdall.Web/Components/Pages/Register.razor @@ -0,0 +1,67 @@ +@page "/register" +@layout MudBlazorLayout +@inject HeimdallApiClient Api +@inject AuthState Auth +@inject NavigationManager Navigation +@inject ISnackbar Snackbar + + + + Créer un compte + + + + + + @if (!string.IsNullOrEmpty(_errorMessage)) + { + @_errorMessage + } + + + @if (_loading) { } + S'inscrire + + + + Déjà un compte ? + Se connecter + + + + +@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; } + } +} diff --git a/src/Heimdall.Web/Components/Pages/SiteDetail.razor b/src/Heimdall.Web/Components/Pages/SiteDetail.razor new file mode 100644 index 0000000..554c343 --- /dev/null +++ b/src/Heimdall.Web/Components/Pages/SiteDetail.razor @@ -0,0 +1,67 @@ +@page "/sites/{Id:guid}" +@attribute [Authorize] +@layout MainLayout +@inject HeimdallApiClient Api +@inject ISnackbar Snackbar +@inject NavigationManager Nav + + + + Site : @_site?.Name + + +@if (_loading) +{ + +} +else if (_site is null) +{ + Site introuvable +} +else +{ + + Informations + + + Nom + @_site.Name + + + Adresse + @(_site.Address ?? "-") + + + Fuseau horaire + @_site.Timezone + + + Statut + + @(_site.Enabled ? "● Actif" : "○ Inactif") + + + + + + + ← Retour aux sites + +} + +@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; } + } +} diff --git a/src/Heimdall.Web/Components/Pages/SitesPage.razor b/src/Heimdall.Web/Components/Pages/SitesPage.razor new file mode 100644 index 0000000..5a73b01 --- /dev/null +++ b/src/Heimdall.Web/Components/Pages/SitesPage.razor @@ -0,0 +1,162 @@ +@page "/sites" +@attribute [Authorize] +@layout MainLayout +@inject HeimdallApiClient Api +@inject ISnackbar Snackbar + + + + Sites + + + + Nouveau site + + +@if (_loading) +{ + +} +else +{ + + + Nom + Adresse + Fuseau + Statut + Actions + + + @context.Name + @context.Address + @context.Timezone + + + @(context.Enabled ? "● Actif" : "○ Inactif") + + + + + + + + + Aucun site. + + +} + +@if (_showCreate) +{ + + + Nouveau site + + + + + @if (!string.IsNullOrEmpty(_creationError)) + { + @_creationError + } + @if (!string.IsNullOrEmpty(_createdToken)) + { + + Token d'enregistrement :
+ + @_createdToken + + + ⚠ Copiez ce token maintenant. Il ne sera plus affiché. + +
+ } +
+ + Annuler + + @if (_saving) { } + @(!string.IsNullOrEmpty(_createdToken) ? "Fermer" : "Créer") + + +
+} + +@code { + private IReadOnlyList? _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); + } +} diff --git a/src/Heimdall.Web/Components/Pages/UsersPage.razor b/src/Heimdall.Web/Components/Pages/UsersPage.razor new file mode 100644 index 0000000..5f2732e --- /dev/null +++ b/src/Heimdall.Web/Components/Pages/UsersPage.razor @@ -0,0 +1,379 @@ +@page "/users" +@attribute [Authorize] +@layout MainLayout +@inject HeimdallApiClient Api +@inject ISnackbar Snackbar + + + + Utilisateurs + + + + Nouvel utilisateur + + +@if (_loading) +{ + +} +else +{ + + + Nom + Email + Rôles + Statut + Inscrit le + Actions + + + @context.DisplayName + @context.Email + + @foreach (var r in context.Roles ?? []) + { + + @r + + } + + + @if (context.IsLockedOut) + { + 🔒 Verrouillé + } + else if (!context.EmailConfirmed) + { + ⏳ En attente + } + else + { + ✓ Actif + } + + @context.CreatedAt.ToString("g") + + + + + + Aucun utilisateur + + + + @* Pagination *@ + + + Page @_page sur @_totalPages (@_total utilisateurs) + + + ← Précédent + + + Suivant → + + +} + +@* Dialog: Créer un utilisateur *@ +@if (_showCreate) +{ + + + Nouvel utilisateur + + + + + Rôle + + Viewer + Supervisor + Admin + + @if (!string.IsNullOrEmpty(_createError)) + { + @_createError + } + + + Annuler + + @if (_saving) { } + Créer + + + +} + +@* Dialog: Modifier un utilisateur *@ +@if (_editUser is not null && _showEdit) +{ + + + Utilisateur : @_editUser.DisplayName + + @_editUser.Email + + @* Section: Informations *@ + Informations + + + + @* Section: Rôles *@ + Rôles + + Sélectionnez les rôles de l'utilisateur + + + Viewer (lecture seule) + Supervisor (gestion sites/caméras) + Admin (accès complet) + + + @* Section: Statut du compte *@ + Statut du compte + + + + 2FA + + + @(_editUser.TwoFactorEnabled ? "Activé" : "Désactivé") + + + + Email confirmé + + + @(_editUser.EmailConfirmed ? "Oui" : "Non") + + + + Tentatives échouées + @_editUser.AccessFailedCount / 5 + + + Verrouillé + + @(_editUser.IsLockedOut ? "Oui" : "Non") + + + + + + @* Actions du compte *@ + Actions + + Réinitialiser le mot de passe + + @if (_editUser.IsLockedOut) + { + + Déverrouiller le compte + + } + else + { + + Verrouiller le compte + + } + + @if (!string.IsNullOrEmpty(_editError)) + { + @_editError + } + @if (!string.IsNullOrEmpty(_temporaryPassword)) + { + + Nouveau mot de passe temporaire :
+ + @_temporaryPassword + + + ⚠ L'utilisateur devra changer ce mot de passe à la prochaine connexion. + +
+ } +
+ + Fermer + + @if (_saving) { } + Enregistrer + + +
+} + +@code { + private IReadOnlyList? _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 { _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 { _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; } + } +} diff --git a/src/Heimdall.Web/Components/_Imports.razor b/src/Heimdall.Web/Components/_Imports.razor index a6d9834..12aab38 100644 --- a/src/Heimdall.Web/Components/_Imports.razor +++ b/src/Heimdall.Web/Components/_Imports.razor @@ -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 diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 586e949..bad27fd 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -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(); +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(); +builder.Services.AddHttpClient("HeimdallApi", client => +{ + client.BaseAddress = new Uri("http://localhost:5000/"); + client.Timeout = TimeSpan.FromSeconds(30); +}); + +// Auth state +builder.Services.AddScoped(); + 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() .AddInteractiveServerRenderMode(); diff --git a/src/Heimdall.Web/Services/AuthState.cs b/src/Heimdall.Web/Services/AuthState.cs new file mode 100644 index 0000000..9901ca3 --- /dev/null +++ b/src/Heimdall.Web/Services/AuthState.cs @@ -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? 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? Roles { get; set; } + public IList? 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( + [property: JsonPropertyName("items")] IReadOnlyList Items, + [property: JsonPropertyName("totalCount")] int TotalCount, + [property: JsonPropertyName("page")] int Page, + [property: JsonPropertyName("pageSize")] int PageSize); diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs new file mode 100644 index 0000000..54f2e13 --- /dev/null +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -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 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(Json); + } + + public async Task 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(Json); + } + + // ─── Users ──────────────────────────────────────────────────── + + public async Task?> GetUsersAsync(int page = 1, int pageSize = 20) + { + var client = CreateClient(); + return await client.GetFromJsonAsync>( + $"api/users?page={page}&pageSize={pageSize}", Json); + } + + public async Task GetUserAsync(Guid id) + { + var client = CreateClient(); + return await client.GetFromJsonAsync($"api/users/{id}", Json); + } + + public async Task CreateUserAsync(string email, string password, string displayName, IList 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(Json); + } + + public async Task 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 AssignRolesAsync(Guid userId, IList roles) + { + var client = CreateClient(); + var response = await client.PutAsJsonAsync($"api/users/{userId}/roles", + new { roles }, Json); + return response.IsSuccessStatusCode; + } + + public async Task AssignSitesAsync(Guid userId, IList siteIds) + { + var client = CreateClient(); + var response = await client.PutAsJsonAsync($"api/users/{userId}/sites", + new { siteIds }, Json); + return response.IsSuccessStatusCode; + } + + public async Task 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(Json); + } + + public async Task LockUserAsync(Guid userId) + { + var client = CreateClient(); + var response = await client.PostAsync($"api/users/{userId}/lock", null); + return response.IsSuccessStatusCode; + } + + public async Task UnlockUserAsync(Guid userId) + { + var client = CreateClient(); + var response = await client.PostAsync($"api/users/{userId}/unlock", null); + return response.IsSuccessStatusCode; + } + + // ─── Sites ──────────────────────────────────────────────────── + + public async Task?> GetSitesAsync(int page = 1, int pageSize = 20) + { + var client = CreateClient(); + return await client.GetFromJsonAsync>( + $"api/sites?page={page}&pageSize={pageSize}", Json); + } + + public async Task GetSiteAsync(Guid id) + { + var client = CreateClient(); + return await client.GetFromJsonAsync($"api/sites/{id}", Json); + } + + public async Task 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(Json); + } + + public async Task DeleteSiteAsync(Guid id) + { + var client = CreateClient(); + var response = await client.DeleteAsync($"api/sites/{id}"); + return response.IsSuccessStatusCode; + } +} diff --git a/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs b/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs new file mode 100644 index 0000000..3579cb6 --- /dev/null +++ b/src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs @@ -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 GetAuthenticationStateAsync() + { + if (!_authState.IsLoggedIn || _authState.User is null) + { + return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); + } + + var claims = new List + { + 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()); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs new file mode 100644 index 0000000..9ed1d36 --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/AuthControllerTests.cs @@ -0,0 +1,91 @@ +using System.Net.Http.Json; +using Heimdall.IntegrationTests.Factories; +using Shouldly; + +namespace Heimdall.IntegrationTests.Controllers; + +public class AuthControllerTests : IClassFixture +{ + 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); + } +} diff --git a/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs new file mode 100644 index 0000000..302e878 --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Controllers/SitesControllerTests.cs @@ -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 +{ + 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 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(Json); + + client.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", content!.AccessToken); + + return client; + } +} diff --git a/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs b/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs new file mode 100644 index 0000000..4bce513 --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Factories/HeimdallWebApplicationFactory.cs @@ -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 +{ + 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(options => + { + options.UseInMemoryDatabase(_dbName); + }); + }); + } +} diff --git a/tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj b/tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj index 72482d6..7cf658e 100644 --- a/tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj +++ b/tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj @@ -9,6 +9,8 @@ + + diff --git a/tests/Heimdall.IntegrationTests/Models/TestModels.cs b/tests/Heimdall.IntegrationTests/Models/TestModels.cs new file mode 100644 index 0000000..787dd80 --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Models/TestModels.cs @@ -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);