Fix camera access and related UI issues (#311)
Heimdall Gitea / Detect CI scope (push) Successful in 27s
Heimdall Gitea / Build and tests (push) Successful in 20m48s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 7m28s
Heimdall Gitea / Build and scan agent image (push) Successful in 11m12s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m59s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m43s
Heimdall Gitea / CI policy (push) Successful in 2s
Heimdall Gitea / Detect CI scope (push) Successful in 27s
Heimdall Gitea / Build and tests (push) Successful in 20m48s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 7m28s
Heimdall Gitea / Build and scan agent image (push) Successful in 11m12s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m59s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m43s
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
This commit was merged in pull request #311.
This commit is contained in:
1 parent
1d60f04691
commit
5b1255ad80
28 files changed
+3731
-40
No files matched your search
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: api-key-localization
|
||||
description: Maintain and verify French and English localization for Heimdall's API key administration page and dialogs.
|
||||
---
|
||||
|
||||
# API key localization
|
||||
|
||||
The API key administration UI is `src/Heimdall.Web/Components/Pages/Admin/ApiKeysPage.razor`. Its text comes from `AdminApiKeys_*` entries in `src/Heimdall.Web/Localization/SharedResources.*.resx` through `UiText`; the active culture is selected by `UiLanguageService`.
|
||||
|
||||
## Updating strings
|
||||
|
||||
1. Keep every `AdminApiKeys_*` key present in the neutral resource and localized resources. Use `SharedResources.en.resx` as the English wording reference and translate all visible create, one-time-secret, revoke, validation, helper, and empty-state copy in `SharedResources.fr.resx`.
|
||||
2. Replace placeholder values that repeat a key suffix (such as `ExpiryHelp`) with actual English fallback copy in `SharedResources.resx` and an actual French translation in `SharedResources.fr.resx`. Check the related `AdminAllAgents_EmptyDescription` entry when auditing the French admin empty states.
|
||||
3. Preserve formatting tokens such as `{0}` in interpolated resource values and preserve the API date format when translating optional date labels.
|
||||
4. Add or update focused bUnit tests under `tests/Heimdall.Web.Tests/Components/Pages/`. Render the page with `PageTestBase`, serve an empty API key list via `api/api-keys`, and assert the French empty-state description and create-dialog labels with key-suffix placeholders absent. For other dialogs, exercise the corresponding UI action and assert the rendered localized text.
|
||||
|
||||
## Acceptance
|
||||
|
||||
Run the focused tests with:
|
||||
|
||||
```sh
|
||||
dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore --filter 'FullyQualifiedName~ApiKeysPageTests|FullyQualifiedName~AllAgentsPageTests'
|
||||
```
|
||||
|
||||
The acceptance evidence should record the command and result. A test run blocked by shared-runner contention is not a pass; rerun it when the runner is available. This localization-only change does not need a disposable Compose acceptance recipe because it changes no runtime behavior or deployment configuration.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
name: camera-access-nullable-select
|
||||
description: Keep nullable camera-access grant selectors type-consistent in the Heimdall Blazor UI and verify site-wide and camera-specific grants.
|
||||
---
|
||||
|
||||
# Camera access nullable selectors
|
||||
|
||||
The grant form in `src/Heimdall.Web/Components/Pages/CameraAccessPanel.razor` stores the selected site and camera as `Guid?` because the form supports an unset selection. Keep each corresponding `MudSelect` and all of its `MudSelectItem` children explicitly typed as `Guid?`; cast non-nullable model IDs with `(Guid?)` in each item value. A plain `Guid` item can compile yet fail at runtime when MudBlazor dispatches the option click to its nullable parent.
|
||||
|
||||
When editing this form, preserve the two grant modes: site-wide grants save a site ID and null camera ID, while camera-specific grants save both IDs. Validate both selection interactions and the serialized saved grants.
|
||||
|
||||
## Acceptance workflow
|
||||
|
||||
1. Run the focused Web tests with `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore` and build `src/Heimdall.Web/Heimdall.Web.csproj` using the SDK pinned in `global.json`.
|
||||
2. For behavior changes, follow [the disposable Compose recipe](../compose-disposable-recipe/SKILL.md): build the changed source using unique local image tags and isolated credentials, project, ports, network, and volumes.
|
||||
3. Bootstrap an isolated administrator, use a real browser/UI-capable test to select a site-wide option and a camera option, and verify the saved grants contain respectively a null and non-null camera ID with no `InvalidCastException`.
|
||||
4. Tear down only that Compose project. Verify its containers, volumes, and networks are absent; remove and verify absence of only the recipe's exact locally built tags, preserving shared base images.
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
name: dashboard-welcome-punctuation
|
||||
description: Keep Heimdall's localized dashboard greeting punctuation consistent across its route aliases.
|
||||
---
|
||||
|
||||
# Dashboard welcome punctuation
|
||||
|
||||
`Dashboard.razor` serves both `/` and `/dashboard`. The `WelcomeUser` resource
|
||||
owns the punctuation at the end of the localized greeting (French and English
|
||||
currently both end in a comma); the Razor markup must add only a space before
|
||||
the display name.
|
||||
|
||||
## Change and acceptance workflow
|
||||
|
||||
1. Inspect `Dashboard.razor` and the `WelcomeUser` values in
|
||||
`SharedResources.fr.resx` and `SharedResources.en.resx` before changing the
|
||||
greeting. Keep one punctuation owner instead of composing punctuation in
|
||||
both places.
|
||||
2. In `DashboardTests`, render the component with `UiLanguageService` set to
|
||||
each supported language and assert the rendered greeting contains exactly
|
||||
the expected localized punctuation and display name.
|
||||
3. Since `/` and `/dashboard` are aliases on the same component, verify both
|
||||
route templates remain declared on the component and exercise this same
|
||||
rendering assertion for the shared output.
|
||||
4. Run the focused web test project. For behavior changes, also run the
|
||||
disposable Compose acceptance recipe from
|
||||
`compose-disposable-recipe/SKILL.md`, using unique project resources and
|
||||
removing only recipe-owned image tags during cleanup.
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
name: site-camera-credentials
|
||||
description: Maintain the per-site camera credential API and its Site Detail and Cameras page flows.
|
||||
---
|
||||
|
||||
# Site camera credentials
|
||||
|
||||
The Web client calls `api/sites/{id}/credentials` from both `SiteDetail.razor`
|
||||
and `CamerasPage.razor`. Keep the GET, POST, and DELETE endpoints in
|
||||
`SitesController` aligned with those client paths. Apply the existing
|
||||
`Site.Read` or `Site.Write` policy and the global site resource-access filter
|
||||
to every credential route.
|
||||
|
||||
Credential passwords are write-only. `SiteCredentialResponse` contains only
|
||||
the credential ID, site ID, label, username, and timestamps; never return,
|
||||
render, or log the stored password. Use the Application handlers and EF Core
|
||||
through the existing application context for persistence.
|
||||
|
||||
## Change and acceptance workflow
|
||||
|
||||
1. Verify the client path and controller route agree for all three methods.
|
||||
2. Test a site with no credentials and a site with a credential in both
|
||||
`/sites/{id}` and `/sites/{id}/cameras`; distinguish a failed request from
|
||||
a normal empty list.
|
||||
3. Exercise add/list/delete with synthetic credentials. Assert the response
|
||||
and list never contain the submitted password.
|
||||
4. Verify unauthenticated requests are rejected and users without access to
|
||||
the site receive a forbidden response.
|
||||
5. Run focused Web and PostgreSQL integration tests, then follow
|
||||
`compose-disposable-recipe` with an isolated Central/PostgreSQL project.
|
||||
Record exact project resources and local image tags, and verify their
|
||||
removal after teardown.
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
name: site-create-permission
|
||||
description: Keep the Sites page site-creation controls aligned with Heimdall's Site.Write permission.
|
||||
---
|
||||
|
||||
# Site creation permission in the Sites page
|
||||
|
||||
`AuthState` resolves role permissions into `Permissions`; check creation with `Auth.HasPermission("Site.Write")` in `SitesPage.razor`. Render both the create affordance and its overlay/dialog only when that permission exists, and route the button through a guarded open method so an event cannot set the dialog visible after access changes.
|
||||
|
||||
The API remains the enforcement boundary. Do not remove or weaken its `Site.Write` authorization policy as part of this UI behavior.
|
||||
|
||||
## Acceptance workflow
|
||||
|
||||
1. Add a focused bUnit test using `PageTestBase.LoginAs("Viewer")`; assert the create button and dialog fields/actions are absent after page load.
|
||||
2. Keep an authorized creation test using an authorized role; exercise opening the dialog and completing a successful create response.
|
||||
3. Run the focused test with `dotnet test tests/Heimdall.Web.Tests --filter FullyQualifiedName~SitesPageTests`.
|
||||
4. For behavior acceptance, run the disposable Compose recipe from `skills/compose-disposable-recipe/SKILL.md`, record its isolated project/tag and cleanup evidence on the Gitea issue. UI component tests do not prove API authorization or field deployment behavior.
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
name: snapshot-gallery-responsive-filters
|
||||
description: Keep the Heimdall snapshot gallery's search, event type, and load controls usable on phone widths while preserving the desktop row.
|
||||
---
|
||||
|
||||
# Snapshot gallery responsive filters
|
||||
|
||||
The snapshot filter controls are owned by `src/Heimdall.Web/Components/Pages/SnapshotsPage.razor`. Keep them together in `.snapshot-filters`: its desktop grid uses three columns for search, event type, and load, and its 600 px breakpoint stacks those controls. Use `minmax(0, ...)` tracks and controls without fixed minimum widths so the page can shrink to a 320 px viewport.
|
||||
|
||||
## Acceptance workflow
|
||||
|
||||
1. Read Gitea issue [#285](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues/285) and retain its criteria for 390 px, narrower phone widths, and desktop.
|
||||
2. Update the `SnapshotsPageTests` bUnit coverage to check that search, event type, and load remain inside the filter layout and that the desktop and phone grid rules remain present without the old 300 px/180 px minimums.
|
||||
3. Run `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --filter FullyQualifiedName~SnapshotsPageTests`.
|
||||
4. For behavior changes, follow `skills/compose-disposable-recipe/SKILL.md` and record the disposable acceptance result, cleanup verification, and any browser viewport evidence on issue #285. A bUnit structure/CSS assertion does not by itself measure rendered document width; use a browser at 390 px and 320 px when available.
|
||||
5. Keep issue #285 open until its desktop, 390 px, narrow-screen, and operational acceptance evidence is complete.
|
||||
@@ -11,7 +11,16 @@ public class UserCameraAccessConfiguration : IEntityTypeConfiguration<UserCamera
|
||||
{
|
||||
builder.ToTable("UserCameraAccesses");
|
||||
|
||||
builder.HasKey(eca => new { eca.UserId, eca.SiteId, eca.CameraId });
|
||||
builder.HasKey(eca => eca.Id);
|
||||
|
||||
// A site-wide grant has a null CameraId, so it cannot participate in
|
||||
// a primary key. Keep duplicate protection with two partial indexes.
|
||||
builder.HasIndex(eca => new { eca.UserId, eca.SiteId })
|
||||
.IsUnique()
|
||||
.HasFilter("\"CameraId\" IS NULL");
|
||||
builder.HasIndex(eca => new { eca.UserId, eca.SiteId, eca.CameraId })
|
||||
.IsUnique()
|
||||
.HasFilter("\"CameraId\" IS NOT NULL");
|
||||
|
||||
builder.HasOne<IdentityAppUser>()
|
||||
.WithMany()
|
||||
|
||||
Generated
+2906
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Heimdall.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AllowSiteWideCameraAccess : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropPrimaryKey(
|
||||
name: "PK_UserCameraAccesses",
|
||||
table: "UserCameraAccesses");
|
||||
|
||||
migrationBuilder.AlterColumn<Guid>(
|
||||
name: "CameraId",
|
||||
table: "UserCameraAccesses",
|
||||
type: "uuid",
|
||||
nullable: true,
|
||||
oldClrType: typeof(Guid),
|
||||
oldType: "uuid");
|
||||
|
||||
migrationBuilder.AddPrimaryKey(
|
||||
name: "PK_UserCameraAccesses",
|
||||
table: "UserCameraAccesses",
|
||||
column: "Id");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_UserCameraAccesses_UserId_SiteId",
|
||||
table: "UserCameraAccesses",
|
||||
columns: new[] { "UserId", "SiteId" },
|
||||
unique: true,
|
||||
filter: "\"CameraId\" IS NULL");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_UserCameraAccesses_UserId_SiteId_CameraId",
|
||||
table: "UserCameraAccesses",
|
||||
columns: new[] { "UserId", "SiteId", "CameraId" },
|
||||
unique: true,
|
||||
filter: "\"CameraId\" IS NOT NULL");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropPrimaryKey(
|
||||
name: "PK_UserCameraAccesses",
|
||||
table: "UserCameraAccesses");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_UserCameraAccesses_UserId_SiteId",
|
||||
table: "UserCameraAccesses");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_UserCameraAccesses_UserId_SiteId_CameraId",
|
||||
table: "UserCameraAccesses");
|
||||
|
||||
// Downgrade cannot preserve site-wide grants in the old schema.
|
||||
// Setting NOT NULL without a default deliberately fails while any
|
||||
// such grants exist; export/remove them before rolling back.
|
||||
migrationBuilder.AlterColumn<Guid>(
|
||||
name: "CameraId",
|
||||
table: "UserCameraAccesses",
|
||||
type: "uuid",
|
||||
nullable: false,
|
||||
oldClrType: typeof(Guid),
|
||||
oldType: "uuid",
|
||||
oldNullable: true);
|
||||
|
||||
migrationBuilder.AddPrimaryKey(
|
||||
name: "PK_UserCameraAccesses",
|
||||
table: "UserCameraAccesses",
|
||||
columns: new[] { "UserId", "SiteId", "CameraId" });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2018,30 +2018,39 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("CameraId")
|
||||
b.Property<Guid?>("CameraId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid>("Id")
|
||||
b.Property<Guid>("SiteId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("UserId", "SiteId", "CameraId");
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CameraId");
|
||||
|
||||
b.HasIndex("SiteId");
|
||||
|
||||
b.HasIndex("UserId", "SiteId")
|
||||
.IsUnique()
|
||||
.HasFilter("\"CameraId\" IS NULL");
|
||||
|
||||
b.HasIndex("UserId", "SiteId", "CameraId")
|
||||
.IsUnique()
|
||||
.HasFilter("\"CameraId\" IS NOT NULL");
|
||||
|
||||
b.ToTable("UserCameraAccesses", (string)null);
|
||||
});
|
||||
|
||||
|
||||
@@ -98,10 +98,10 @@
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" md="6">
|
||||
<MudSelect @bind-Value="_newAccessSiteId" Label="@Text["CameraAccess_Site"]" Variant="Variant.Outlined" Class="w-100">
|
||||
<MudSelect T="Guid?" @bind-Value="_newAccessSiteId" Label="@Text["CameraAccess_Site"]" Variant="Variant.Outlined" Class="w-100">
|
||||
@foreach (var site in _availableSites)
|
||||
{
|
||||
<MudSelectItem Value="@site.Id">@site.Name</MudSelectItem>
|
||||
<MudSelectItem T="Guid?" Value="@((Guid?)site.Id)">@site.Name</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
@@ -109,10 +109,10 @@
|
||||
|
||||
@if (_newAccessType == AccessType.CameraSpecific)
|
||||
{
|
||||
<MudSelect @bind-Value="_newAccessCameraId" Label="@Text["CameraAccess_Camera"]" Variant="Variant.Outlined" Class="w-100 mb-4">
|
||||
<MudSelect T="Guid?" @bind-Value="_newAccessCameraId" Label="@Text["CameraAccess_Camera"]" Variant="Variant.Outlined" Class="w-100 mb-4">
|
||||
@foreach (var camera in _availableCameras)
|
||||
{
|
||||
<MudSelectItem Value="@camera.Id">@camera.Name (@GetSiteName(camera.SiteId))</MudSelectItem>
|
||||
<MudSelectItem T="Guid?" Value="@((Guid?)camera.Id)">@camera.Name (@GetSiteName(camera.SiteId))</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
@Text["Dashboard"]
|
||||
</MudText>
|
||||
<MudText Typo="Typo.body1" Class="mb-2">
|
||||
@Text["WelcomeUser"], <strong>@Auth.User?.DisplayName</strong>
|
||||
@Text["WelcomeUser"] <strong>@Auth.User?.DisplayName</strong>
|
||||
</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-6">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Update" Size="Size.Small" Class="mr-1" />
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
@attribute [Authorize]
|
||||
@layout MainLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject AuthState Auth
|
||||
@inject ISnackbar Snackbar
|
||||
@inject UiText Text
|
||||
@inject UiLanguageService Language
|
||||
@@ -17,9 +18,12 @@
|
||||
</MudText>
|
||||
|
||||
<div class="d-flex justify-space-between align-center mb-4">
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => _showCreate = true)">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> @Text["SitesPage_NewSite"]
|
||||
</MudButton>
|
||||
@if (CanCreateSite)
|
||||
{
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="OpenCreate">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> @Text["SitesPage_NewSite"]
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (_loading)
|
||||
@@ -75,6 +79,8 @@ else
|
||||
</MudTable>
|
||||
}
|
||||
|
||||
@if (CanCreateSite)
|
||||
{
|
||||
<MudOverlay Visible="@_showCreate" OnClick="@(() => _showCreate = false)" />
|
||||
<MudDialog @bind-Visible="_showCreate">
|
||||
<TitleContent><MudText Typo="Typo.h6">@Text["SitesPage_NewSite"]</MudText></TitleContent>
|
||||
@@ -112,6 +118,7 @@ else
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
}
|
||||
|
||||
@* ─── Confirm delete dialog ───────────────────────────────── *@
|
||||
<MudOverlay Visible="@_confirmDeleteShow" OnClick="@(() => _confirmDeleteShow = false)" />
|
||||
@@ -254,6 +261,13 @@ else
|
||||
</MudDialog>
|
||||
|
||||
@code {
|
||||
private bool CanCreateSite => Auth.HasPermission("Site.Write");
|
||||
|
||||
private void OpenCreate()
|
||||
{
|
||||
if (CanCreateSite)
|
||||
_showCreate = true;
|
||||
}
|
||||
private IReadOnlyList<SiteItem>? _sites;
|
||||
private bool _loading = true;
|
||||
private bool _error;
|
||||
|
||||
@@ -14,10 +14,10 @@
|
||||
</MudText>
|
||||
|
||||
<MudPaper Elevation="1" Class="pa-4 mb-4">
|
||||
<MudToolBar>
|
||||
<div class="snapshot-filters">
|
||||
<MudTextField @bind-Value="_search" Label="@Text["SnapshotsPage_SearchLabel"]" Variant="Variant.Outlined"
|
||||
Class="mr-2" style="min-width:300px;" Placeholder="@Text["SnapshotsPage_SearchPlaceholder"]" />
|
||||
<MudSelect T="string" @bind-Value="_type" Label="@Text["SnapshotsPage_Type"]" Variant="Variant.Outlined" Clearable="true" Class="mr-2" Style="min-width:180px;">
|
||||
Class="snapshot-filter-control" Style="width:100%;" Placeholder="@Text["SnapshotsPage_SearchPlaceholder"]" />
|
||||
<MudSelect T="string" @bind-Value="_type" Label="@Text["SnapshotsPage_Type"]" Variant="Variant.Outlined" Clearable="true" Class="snapshot-filter-control" Style="width:100%;">
|
||||
<MudSelectItem Value="@nameof(EventType.MotionDetected)">@Text["SnapshotsPage_Motion"]</MudSelectItem>
|
||||
<MudSelectItem Value="@nameof(EventType.PersonDetected)">@Text["SnapshotsPage_Person"]</MudSelectItem>
|
||||
<MudSelectItem Value="@nameof(EventType.VehicleDetected)">@Text["SnapshotsPage_Vehicle"]</MudSelectItem>
|
||||
@@ -31,9 +31,32 @@
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@ApplyFilters">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Search" Class="mr-1" Size="Size.Small" /> @Text["SnapshotsPage_Load"]
|
||||
</MudButton>
|
||||
</MudToolBar>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<style>
|
||||
.snapshot-filters {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.snapshot-filter-control {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
@@media (max-width: 600px) {
|
||||
.snapshot-filters {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.snapshot-filters button {
|
||||
justify-self: start;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" Class="mt-8" />
|
||||
|
||||
@@ -161,6 +161,48 @@ public class SitesController : ControllerBase
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>List the camera credential pool for a site. Passwords are never returned.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
|
||||
[HttpGet("{id:guid}/credentials")]
|
||||
[ProducesResponseType(typeof(IReadOnlyList<SiteCredentialResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetCredentials(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new ListSiteCredentialsQuery(id), ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Add a camera credential to a site. The password is write-only.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpPost("{id:guid}/credentials")]
|
||||
[ProducesResponseType(typeof(SiteCredentialResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> AddCredential(Guid id, [FromBody] AddSiteCredentialRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(
|
||||
new AddSiteCredentialCommand(id, request.Label, request.Username, request.Password), ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Delete a camera credential from a site.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteWrite)]
|
||||
[HttpDelete("{id:guid}/credentials/{credentialId:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeleteCredential(Guid id, Guid credentialId, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new DeleteSiteCredentialCommand(id, credentialId), ct);
|
||||
return result.IsSuccess
|
||||
? NoContent()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Delete a site (Admin only).</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteDelete)]
|
||||
[HttpDelete("{id:guid}")]
|
||||
|
||||
@@ -1312,7 +1312,7 @@
|
||||
<value>Supprimer cet agent</value>
|
||||
</data>
|
||||
<data name="AdminAllAgents_EmptyDescription" xml:space="preserve">
|
||||
<value>EmptyDescription</value>
|
||||
<value>Aucun agent n'est actuellement enregistré sur un site. Créez un site et générez un jeton d'enregistrement pour connecter un agent.</value>
|
||||
</data>
|
||||
<data name="AdminAllAgents_EmptyTitle" xml:space="preserve">
|
||||
<value>Aucun agent déployé</value>
|
||||
@@ -1354,7 +1354,7 @@
|
||||
<value>Annuler</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_Copied" xml:space="preserve">
|
||||
<value>Copied</value>
|
||||
<value>J'ai copié la clé</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_CopyInstruction" xml:space="preserve">
|
||||
<value>Sélectionnez et copiez la clé avec Ctrl+C</value>
|
||||
@@ -1387,16 +1387,16 @@
|
||||
<value>Aucune clé API</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_EmptyDescription" xml:space="preserve">
|
||||
<value>EmptyDescription</value>
|
||||
<value>Aucune clé API n'est configurée. Créez une clé pour permettre aux agents de se connecter.</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_ExpiresAt" xml:space="preserve">
|
||||
<value>Expire le</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_ExpiryHelp" xml:space="preserve">
|
||||
<value>ExpiryHelp</value>
|
||||
<value>Si ce champ est vide, la clé n'expire jamais.</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_ExpiryLabel" xml:space="preserve">
|
||||
<value>ExpiryLabel</value>
|
||||
<value>Date d'expiration (facultative — AAAA-MM-JJ)</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_InvalidExpiry" xml:space="preserve">
|
||||
<value>Date d'expiration invalide (format : YYYY-MM-DD)</value>
|
||||
@@ -1429,7 +1429,7 @@
|
||||
<value>Préfixe</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_PrefixLabel" xml:space="preserve">
|
||||
<value>PrefixLabel</value>
|
||||
<value>Préfixe :</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_Retry" xml:space="preserve">
|
||||
<value>Réessayer</value>
|
||||
@@ -1468,10 +1468,10 @@
|
||||
<value>Site</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_SiteIdHelp" xml:space="preserve">
|
||||
<value>SiteIdHelp</value>
|
||||
<value>Si un site est indiqué, l'agent pourra accéder uniquement à ce site.</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_SiteIdLabel" xml:space="preserve">
|
||||
<value>SiteIdLabel</value>
|
||||
<value>ID du site (facultatif — laissez vide pour une clé globale)</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_Status" xml:space="preserve">
|
||||
<value>Statut</value>
|
||||
|
||||
@@ -1312,7 +1312,7 @@
|
||||
<value>Supprimer cet agent</value>
|
||||
</data>
|
||||
<data name="AdminAllAgents_EmptyDescription" xml:space="preserve">
|
||||
<value>EmptyDescription</value>
|
||||
<value>No agent is currently registered on any site. Create a site and generate a registration token to connect an agent.</value>
|
||||
</data>
|
||||
<data name="AdminAllAgents_EmptyTitle" xml:space="preserve">
|
||||
<value>Aucun agent déployé</value>
|
||||
@@ -1354,7 +1354,7 @@
|
||||
<value>Annuler</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_Copied" xml:space="preserve">
|
||||
<value>Copied</value>
|
||||
<value>I copied the key</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_CopyInstruction" xml:space="preserve">
|
||||
<value>Sélectionnez et copiez la clé avec Ctrl+C</value>
|
||||
@@ -1387,16 +1387,16 @@
|
||||
<value>Aucune clé API</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_EmptyDescription" xml:space="preserve">
|
||||
<value>EmptyDescription</value>
|
||||
<value>No API keys configured. Create a key to allow agents to connect.</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_ExpiresAt" xml:space="preserve">
|
||||
<value>Expire le</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_ExpiryHelp" xml:space="preserve">
|
||||
<value>ExpiryHelp</value>
|
||||
<value>If blank, the key never expires.</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_ExpiryLabel" xml:space="preserve">
|
||||
<value>ExpiryLabel</value>
|
||||
<value>Expiration date (optional — YYYY-MM-DD)</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_InvalidExpiry" xml:space="preserve">
|
||||
<value>Date d'expiration invalide (format : YYYY-MM-DD)</value>
|
||||
@@ -1429,7 +1429,7 @@
|
||||
<value>Préfixe</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_PrefixLabel" xml:space="preserve">
|
||||
<value>PrefixLabel</value>
|
||||
<value>Prefix:</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_Retry" xml:space="preserve">
|
||||
<value>Réessayer</value>
|
||||
@@ -1468,10 +1468,10 @@
|
||||
<value>Site</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_SiteIdHelp" xml:space="preserve">
|
||||
<value>SiteIdHelp</value>
|
||||
<value>If specified, the agent can access only this site.</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_SiteIdLabel" xml:space="preserve">
|
||||
<value>SiteIdLabel</value>
|
||||
<value>Site ID (optional — leave blank for a global key)</value>
|
||||
</data>
|
||||
<data name="AdminApiKeys_Status" xml:space="preserve">
|
||||
<value>Statut</value>
|
||||
|
||||
@@ -19,6 +19,7 @@ namespace Heimdall.E2E.Tests;
|
||||
public abstract class E2ETestBase : IAsyncLifetime
|
||||
{
|
||||
private readonly string _connectionString;
|
||||
private string? _externalBaseUrl;
|
||||
private WebApplication? _app;
|
||||
private int _port;
|
||||
private IPage? _page;
|
||||
@@ -31,7 +32,7 @@ public abstract class E2ETestBase : IAsyncLifetime
|
||||
}
|
||||
|
||||
protected IPage Page => _page ?? throw new InvalidOperationException("Playwright not initialized");
|
||||
protected string BaseUrl => $"http://127.0.0.1:{_port}";
|
||||
protected string BaseUrl => _externalBaseUrl ?? $"http://127.0.0.1:{_port}";
|
||||
protected WebApplication App => _app ?? throw new InvalidOperationException("App not initialized");
|
||||
|
||||
/// <summary>Seeded admin account (see Seed:AdminLogin/Seed:AdminPassword in-memory config).</summary>
|
||||
@@ -72,8 +73,10 @@ public abstract class E2ETestBase : IAsyncLifetime
|
||||
/// Logs in through the real Blazor UI. Navigates to /login, fills the form,
|
||||
/// submits, and waits for the redirect to the dashboard.
|
||||
/// </summary>
|
||||
protected async Task LoginViaUiAsync(string email = AdminEmail, string password = AdminPassword)
|
||||
protected async Task LoginViaUiAsync(string? email = null, string? password = null)
|
||||
{
|
||||
email ??= Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_EMAIL") ?? AdminEmail;
|
||||
password ??= Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_PASSWORD") ?? AdminPassword;
|
||||
await GotoWithCircuitAsync("/login");
|
||||
|
||||
await Page.WaitForSelectorAsync("input[autocomplete='email']", new() { Timeout = 15000 });
|
||||
@@ -82,15 +85,21 @@ public abstract class E2ETestBase : IAsyncLifetime
|
||||
await Page.ClickAsync("button:has-text('Se connecter')");
|
||||
|
||||
// After a successful login the app redirects to /dashboard
|
||||
await Page.WaitForURLAsync("**/dashboard**", new() { Timeout = 20000 });
|
||||
await Page.WaitForURLAsync("**/dashboard**", new()
|
||||
{
|
||||
Timeout = 20000,
|
||||
WaitUntil = WaitUntilState.Commit
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a JWT access token by calling the REST API directly (no browser).
|
||||
/// Used by tests that need an authenticated HTTP client (e.g. admin setup).
|
||||
/// </summary>
|
||||
protected async Task<string> LoginViaApiAsync(string email = AdminEmail, string password = AdminPassword)
|
||||
protected async Task<string> LoginViaApiAsync(string? email = null, string? password = null)
|
||||
{
|
||||
email ??= Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_EMAIL") ?? AdminEmail;
|
||||
password ??= Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_PASSWORD") ?? AdminPassword;
|
||||
using var http = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var response = await http.PostAsJsonAsync("/api/auth/login", new { email, password });
|
||||
response.EnsureSuccessStatusCode();
|
||||
@@ -102,6 +111,13 @@ public abstract class E2ETestBase : IAsyncLifetime
|
||||
|
||||
public virtual async Task InitializeAsync()
|
||||
{
|
||||
_externalBaseUrl = Environment.GetEnvironmentVariable("HEIMDALL_E2E_BASE_URL")?.TrimEnd('/');
|
||||
if (!string.IsNullOrWhiteSpace(_externalBaseUrl))
|
||||
{
|
||||
await StartPlaywrightAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
// Find a free TCP port
|
||||
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
socket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, 0));
|
||||
|
||||
@@ -125,6 +125,154 @@ public class UserManagementTests : E2ETestBase
|
||||
await Page.WaitForSelectorAsync("text=Après Modification", new() { Timeout = 15000 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admin_can_grant_site_wide_and_camera_access_without_nullable_select_cast()
|
||||
{
|
||||
if (string.Equals(Environment.GetEnvironmentVariable("HEIMDALL_E2E_BOOTSTRAP_ADMIN"), "true",
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var bootstrapEmail = Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_EMAIL")
|
||||
?? throw new InvalidOperationException("HEIMDALL_E2E_ADMIN_EMAIL is required for external acceptance.");
|
||||
var bootstrapPassword = Environment.GetEnvironmentVariable("HEIMDALL_E2E_ADMIN_PASSWORD")
|
||||
?? throw new InvalidOperationException("HEIMDALL_E2E_ADMIN_PASSWORD is required for external acceptance.");
|
||||
using var bootstrap = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
var bootstrapResponse = await bootstrap.PostAsJsonAsync("api/auth/bootstrap-admin", new
|
||||
{
|
||||
email = bootstrapEmail,
|
||||
password = bootstrapPassword,
|
||||
displayName = "Disposable Acceptance Admin"
|
||||
});
|
||||
var bootstrapBody = await bootstrapResponse.Content.ReadAsStringAsync();
|
||||
bootstrapResponse.StatusCode.ShouldBe(HttpStatusCode.OK,
|
||||
$"Bootstrap status={bootstrapResponse.StatusCode}; response={bootstrapBody}");
|
||||
// Bootstrap is performed through the supported one-time endpoint;
|
||||
// the grant workflow below still logs in and operates through UI.
|
||||
}
|
||||
|
||||
var token = await LoginViaApiAsync();
|
||||
using var admin = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
admin.DefaultRequestHeaders.Authorization = new("Bearer", token);
|
||||
// The panel loads the first page of sites; use a sortable prefix so a
|
||||
// shared E2E database with older fixtures still includes this site.
|
||||
var siteName = $"000 Nullable select {Guid.NewGuid():N}";
|
||||
var siteResponse = await admin.PostAsJsonAsync("api/sites", new { name = siteName, timezone = "UTC" });
|
||||
siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
var siteId = (await siteResponse.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>())
|
||||
.GetProperty("id").GetGuid();
|
||||
var listedSites = await admin.GetFromJsonAsync<System.Text.Json.JsonElement>("api/sites?page=1&pageSize=20");
|
||||
listedSites.GetProperty("items").EnumerateArray().ShouldContain(site =>
|
||||
site.GetProperty("id").GetGuid() == siteId);
|
||||
var cameraName = $"Nullable camera {Guid.NewGuid():N}";
|
||||
var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new
|
||||
{
|
||||
siteId,
|
||||
name = cameraName,
|
||||
rtspUrl = $"rtsp://127.0.0.1/{Guid.NewGuid():N}"
|
||||
});
|
||||
cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
var cameraId = (await cameraResponse.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>())
|
||||
.GetProperty("id").GetGuid();
|
||||
|
||||
var email = $"nullable-select-{Guid.NewGuid():N}@heimdall.test";
|
||||
var userResponse = await admin.PostAsJsonAsync("api/users", new
|
||||
{
|
||||
email,
|
||||
password = "NullableSelect123!",
|
||||
displayName = "Nullable Select Viewer",
|
||||
roles = new[] { "Viewer" }
|
||||
});
|
||||
userResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
var userId = (await userResponse.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>())
|
||||
.GetProperty("id").GetGuid();
|
||||
|
||||
var pageErrors = new List<string>();
|
||||
Page.PageError += (_, error) => pageErrors.Add(error);
|
||||
// Use the real login page so the browser cookie and Blazor circuit's
|
||||
// in-memory API token are both initialized for grant saves.
|
||||
await LoginViaUiAsync();
|
||||
await GotoWithCircuitAsync("/users");
|
||||
var userRow = Page.Locator($"tr:has-text('{email}')");
|
||||
await userRow.GetByRole(AriaRole.Button, new() { Name = "Gérer les caméras", Exact = true }).ClickAsync();
|
||||
await Page.Locator(".camera-access-panel").WaitForAsync();
|
||||
// Blazor Server executes HeimdallApiClient calls inside its circuit on
|
||||
// the server, so api/sites is not a browser network response. The
|
||||
// authenticated direct API list assertion above verifies its JSON data.
|
||||
await Page.Locator(".camera-access-panel .mud-progress-circular").WaitForAsync(
|
||||
new() { State = WaitForSelectorState.Detached, Timeout = 15000 });
|
||||
(await Page.Locator(".camera-access-panel .mud-alert-error").CountAsync()).ShouldBe(0);
|
||||
|
||||
var form = Page.Locator(".camera-access-panel");
|
||||
var siteSelect = form.Locator(".mud-select:has(label.mud-input-label:text-is('Site'))").First;
|
||||
var accessTypeSelect = form.Locator(".mud-select:has(label.mud-input-label:text-is('Type d’accès'))").First;
|
||||
await siteSelect.ClickAsync();
|
||||
// MudSelect renders its option list in a page-level popover, outside
|
||||
// .camera-access-panel; wait for the option after opening the popover.
|
||||
var siteOption = Page.Locator(".mud-popover-open .mud-list-item")
|
||||
.Filter(new() { HasText = siteName });
|
||||
try
|
||||
{
|
||||
await siteOption.WaitForAsync(new() { Timeout = 10000 });
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
var popoverTexts = await Page.Locator(".mud-popover-open").AllInnerTextsAsync();
|
||||
var loading = await Page.Locator(".camera-access-panel .mud-progress-circular").CountAsync();
|
||||
var alerts = await Page.Locator(".camera-access-panel .mud-alert").AllInnerTextsAsync();
|
||||
var gridText = await form.Locator(".mud-grid").InnerTextAsync();
|
||||
var selectorCount = await form.Locator(".mud-grid .mud-select").CountAsync();
|
||||
throw new Xunit.Sdk.XunitException($"Site option missing. Popovers=[{string.Join(" | ", popoverTexts)}], grid=[{gridText}], gridSelectors={selectorCount}, loading={loading}, alerts=[{string.Join(" | ", alerts)}]");
|
||||
}
|
||||
await siteOption.ClickAsync();
|
||||
await form.GetByRole(AriaRole.Button, new() { Name = "Ajouter à la liste", Exact = true }).ClickAsync();
|
||||
await form.Locator(".mud-table").First.GetByText(siteName, new() { Exact = true })
|
||||
.WaitForAsync(new() { Timeout = 10000 });
|
||||
var unsavedNotice = form.GetByText("Les changements ne sont appliqués qu’après l’enregistrement.",
|
||||
new() { Exact = true });
|
||||
await unsavedNotice.WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 5000 });
|
||||
await form.GetByRole(AriaRole.Button, new() { Name = "Enregistrer les accès", Exact = true }).ClickAsync();
|
||||
await unsavedNotice.WaitForAsync(new() { State = WaitForSelectorState.Detached, Timeout = 15000 });
|
||||
var saveErrorText = string.Join(" | ", await form.Locator(".mud-alert").AllInnerTextsAsync());
|
||||
var siteGrantReadback = await admin.GetFromJsonAsync<System.Text.Json.JsonElement>(
|
||||
$"api/user-camera-access/user/{userId}");
|
||||
var siteGrantItems = siteGrantReadback.GetProperty("items").EnumerateArray().ToArray();
|
||||
siteGrantItems.ShouldContain(grant => grant.GetProperty("siteId").GetGuid() == siteId
|
||||
&& grant.GetProperty("cameraId").ValueKind == System.Text.Json.JsonValueKind.Null,
|
||||
customMessage: $"Save errors=[{saveErrorText}], API returned count={siteGrantItems.Length}, site matches={siteGrantItems.Count(grant => grant.GetProperty("siteId").GetGuid() == siteId)}, null camera count={siteGrantItems.Count(grant => grant.GetProperty("cameraId").ValueKind == System.Text.Json.JsonValueKind.Null)}");
|
||||
|
||||
await accessTypeSelect.ClickAsync();
|
||||
await Page.Locator(".mud-popover-open .mud-list-item")
|
||||
.Filter(new() { HasText = "spécifique" }).ClickAsync();
|
||||
var cameraSelect = form.Locator(".mud-select:has(label.mud-input-label:text-is('Caméra'))").First;
|
||||
await cameraSelect.WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 10000 });
|
||||
await siteSelect.ClickAsync();
|
||||
siteOption = Page.Locator(".mud-popover-open .mud-list-item")
|
||||
.Filter(new() { HasText = siteName });
|
||||
await siteOption.ClickAsync();
|
||||
await cameraSelect.ClickAsync();
|
||||
var cameraOption = Page.Locator(".mud-popover-open .mud-list-item")
|
||||
.Filter(new() { HasText = cameraName });
|
||||
await cameraOption.WaitForAsync(new() { Timeout = 10000 });
|
||||
await cameraOption.ClickAsync();
|
||||
await form.GetByRole(AriaRole.Button, new() { Name = "Ajouter à la liste", Exact = true }).ClickAsync();
|
||||
await form.Locator(".mud-table").Last.GetByText(cameraName, new() { Exact = false })
|
||||
.WaitForAsync(new() { Timeout = 10000 });
|
||||
unsavedNotice = form.GetByText("Les changements ne sont appliqués qu’après l’enregistrement.",
|
||||
new() { Exact = true });
|
||||
await unsavedNotice.WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 5000 });
|
||||
await form.GetByRole(AriaRole.Button, new() { Name = "Enregistrer les accès", Exact = true }).ClickAsync();
|
||||
await unsavedNotice.WaitForAsync(new() { State = WaitForSelectorState.Detached, Timeout = 15000 });
|
||||
|
||||
var saved = await admin.GetFromJsonAsync<System.Text.Json.JsonElement>(
|
||||
$"api/user-camera-access/user/{userId}");
|
||||
var grants = saved.GetProperty("items").EnumerateArray().ToArray();
|
||||
grants.ShouldContain(grant => grant.GetProperty("siteId").GetGuid() == siteId
|
||||
&& grant.GetProperty("cameraId").ValueKind == System.Text.Json.JsonValueKind.Null);
|
||||
grants.ShouldContain(grant => grant.GetProperty("siteId").GetGuid() == siteId
|
||||
&& grant.GetProperty("cameraId").ValueKind == System.Text.Json.JsonValueKind.String
|
||||
&& grant.GetProperty("cameraId").GetGuid() == cameraId);
|
||||
pageErrors.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admin_can_reset_user_password()
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Heimdall.IntegrationTests.Factories;
|
||||
using Shouldly;
|
||||
|
||||
@@ -6,6 +7,8 @@ namespace Heimdall.IntegrationTests.Controllers;
|
||||
|
||||
public class SitesControllerTests : PostgresTestBase
|
||||
{
|
||||
private static readonly JsonSerializerOptions WebJsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
public SitesControllerTests(PostgreSqlContainerFixture postgres) : base(postgres) { }
|
||||
|
||||
[Fact]
|
||||
@@ -45,4 +48,57 @@ public class SitesControllerTests : PostgresTestBase
|
||||
var response = await client.GetAsync("api/sites?page=1&pageSize=10");
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SiteCredentials_CanBeListedAddedAndDeleted_WithoutReturningPassword()
|
||||
{
|
||||
var client = await Factory.CreateAdminClientAsync();
|
||||
var siteResponse = await client.PostAsJsonAsync("api/sites", new
|
||||
{
|
||||
name = $"Credential Site {Guid.NewGuid():N}",
|
||||
timezone = "UTC"
|
||||
});
|
||||
var site = await siteResponse.Content.ReadFromJsonAsync<Heimdall.Application.DTOs.SiteWithTokenResponse>();
|
||||
site.ShouldNotBeNull();
|
||||
|
||||
var viewer = await Factory.CreateViewerClientAsync(client);
|
||||
(await viewer.GetAsync($"api/sites/{site.Id}/credentials")).StatusCode
|
||||
.ShouldBe(System.Net.HttpStatusCode.Forbidden);
|
||||
|
||||
var emptyResponse = await client.GetAsync($"api/sites/{site.Id}/credentials");
|
||||
emptyResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
(await emptyResponse.Content.ReadFromJsonAsync<List<Heimdall.Application.DTOs.SiteCredentialResponse>>())
|
||||
.ShouldBeEmpty();
|
||||
|
||||
const string submittedPassword = "synthetic-camera-password-only-for-test";
|
||||
var addResponse = await client.PostAsJsonAsync($"api/sites/{site.Id}/credentials", new
|
||||
{
|
||||
label = "Synthetic camera login",
|
||||
username = "camera-test-user",
|
||||
password = submittedPassword
|
||||
});
|
||||
addResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
var responseBody = await addResponse.Content.ReadAsStringAsync();
|
||||
responseBody.ShouldNotContain(submittedPassword);
|
||||
var created = JsonSerializer.Deserialize<Heimdall.Application.DTOs.SiteCredentialResponse>(responseBody, WebJsonOptions);
|
||||
created.ShouldNotBeNull();
|
||||
|
||||
var listResponse = await client.GetAsync($"api/sites/{site.Id}/credentials");
|
||||
var listed = await listResponse.Content.ReadFromJsonAsync<List<Heimdall.Application.DTOs.SiteCredentialResponse>>();
|
||||
listResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
listed.ShouldHaveSingleItem().Id.ShouldBe(created.Id);
|
||||
|
||||
var deleteResponse = await client.DeleteAsync($"api/sites/{site.Id}/credentials/{created.Id}");
|
||||
deleteResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.NoContent);
|
||||
var afterDelete = await client.GetFromJsonAsync<List<Heimdall.Application.DTOs.SiteCredentialResponse>>(
|
||||
$"api/sites/{site.Id}/credentials");
|
||||
afterDelete.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SiteCredentials_RequireAuthentication()
|
||||
{
|
||||
var response = await Factory.CreateClient().GetAsync($"api/sites/{Guid.NewGuid()}/credentials");
|
||||
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized);
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,7 @@ public class AllAgentsPageTests : PageTestBase
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("Aucun agent déployé");
|
||||
cut.Markup.ShouldContain("Aucun agent n'est actuellement enregistré sur un site.");
|
||||
cut.Markup.ShouldContain("Voir les sites");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
using Bunit;
|
||||
using Heimdall.Web.Components.Pages.Admin;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Heimdall.Web.Services;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.Web.Tests.Components.Pages;
|
||||
|
||||
public class ApiKeysPageTests : PageTestBase
|
||||
{
|
||||
[Fact]
|
||||
public void ApiKeyResources_AucunPlaceholderVideOuTechniqueEnFrancaisEtAnglais()
|
||||
{
|
||||
var language = new UiLanguageService();
|
||||
var text = new UiText(language);
|
||||
var keys = new[]
|
||||
{
|
||||
"AdminApiKeys_SiteIdLabel",
|
||||
"AdminApiKeys_SiteIdHelp",
|
||||
"AdminApiKeys_ExpiryLabel",
|
||||
"AdminApiKeys_ExpiryHelp",
|
||||
"AdminAllAgents_EmptyDescription",
|
||||
"AdminApiKeys_EmptyDescription"
|
||||
};
|
||||
|
||||
foreach (var culture in new[] { "fr", "en" })
|
||||
{
|
||||
language.SetLanguage(culture);
|
||||
foreach (var key in keys)
|
||||
{
|
||||
var value = text[key].Trim();
|
||||
value.ShouldNotBeNullOrWhiteSpace();
|
||||
value.ShouldNotBe(key);
|
||||
value.ShouldNotBe(key[(key.LastIndexOf('_') + 1)..]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApiKeysPage_AucuneCle_AfficheLaDescriptionFrancaise()
|
||||
{
|
||||
Handler.OnGet("api/api-keys", Array.Empty<ApiKeyListItem>());
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<ApiKeysPage>();
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("Aucune clé API n'est configurée.");
|
||||
cut.Markup.ShouldContain("Créez une clé pour permettre aux agents de se connecter.");
|
||||
cut.Markup.ShouldNotContain("EmptyDescription");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApiKeysPage_DialogueCreation_AfficheLesLibellesFrancais()
|
||||
{
|
||||
Handler.OnGet("api/api-keys", Array.Empty<ApiKeyListItem>());
|
||||
Handler.On(HttpMethod.Post, "api/api-keys", new CreateApiKeyResult(
|
||||
Guid.NewGuid(), "hdm_test_secret", "hdm_test", null, null));
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<ApiKeysPage>();
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Créer une clé"));
|
||||
await cut.InvokeAsync(() => cut.FindAll("button").First(button => button.TextContent.Contains("Créer une clé")).Click());
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("ID du site (facultatif — laissez vide pour une clé globale)");
|
||||
cut.Markup.ShouldContain("Si un site est indiqué, l'agent pourra accéder uniquement à ce site.");
|
||||
cut.Markup.ShouldContain("Date d'expiration (facultative — AAAA-MM-JJ)");
|
||||
cut.Markup.ShouldContain("Si ce champ est vide, la clé n'expire jamais.");
|
||||
cut.Markup.ShouldNotContain("SiteIdLabel");
|
||||
cut.Markup.ShouldNotContain("ExpiryHelp");
|
||||
});
|
||||
|
||||
await cut.InvokeAsync(() => cut.FindAll("button").Single(button => button.TextContent.Trim() == "Créer").Click());
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("Copiez cette clé maintenant.");
|
||||
cut.Markup.ShouldContain("Elle ne sera plus jamais affichée.");
|
||||
cut.Markup.ShouldContain("Préfixe :");
|
||||
cut.Markup.ShouldContain("J'ai copié la clé");
|
||||
cut.Markup.ShouldNotContain("Copied");
|
||||
});
|
||||
|
||||
Services.GetRequiredService<UiLanguageService>().Language.ShouldBe("fr");
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,62 @@ public class CamerasPageTests : PageTestBase
|
||||
CreatedAt = DateTime.UtcNow.AddDays(-2)
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void CamerasPage_SansIdentifiants_AfficheEtatVideSansErreur()
|
||||
{
|
||||
Handler.OnGet($"api/sites/{SiteId}/credentials", Array.Empty<SiteCredentialItem>());
|
||||
Handler.OnGet("api/cameras/by-site", new PagedData<CameraItem>([], 0, 1, 100));
|
||||
Handler.OnGet("api/discovery/sites", Array.Empty<PendingDiscoveryItem>());
|
||||
Handler.OnGet("api/agents/by-site", new PagedData<AgentItem>([], 0, 1, 50));
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<CamerasPage>(p => p.Add(x => x.SiteId, SiteId));
|
||||
|
||||
cut.FindAll(".mud-tab").Single(tab => tab.TextContent.Contains("Identifiants", StringComparison.Ordinal)).Click();
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("Aucun identifiant déclaré");
|
||||
cut.Markup.ShouldNotContain("Une erreur est survenue");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CamerasPage_AjouterIdentifiantDepuisSiteVide_AppelleApiEtAfficheSucces()
|
||||
{
|
||||
Handler.OnGet($"api/sites/{SiteId}/credentials", Array.Empty<SiteCredentialItem>());
|
||||
Handler.OnGet("api/cameras/by-site", new PagedData<CameraItem>([], 0, 1, 100));
|
||||
Handler.OnGet("api/discovery/sites", Array.Empty<PendingDiscoveryItem>());
|
||||
Handler.OnGet("api/agents/by-site", new PagedData<AgentItem>([], 0, 1, 50));
|
||||
Handler.On(HttpMethod.Post, $"api/sites/{SiteId}/credentials", new SiteCredentialItem
|
||||
{
|
||||
Id = Guid.NewGuid(), SiteId = SiteId, Label = "synthetic admin", Username = "camera-user", CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<CamerasPage>(p => p.Add(page => page.SiteId, SiteId));
|
||||
cut.FindAll(".mud-tab").Single(tab => tab.TextContent.Contains("Identifiants", StringComparison.Ordinal)).Click();
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Aucun identifiant déclaré"));
|
||||
cut.FindAll("button").First(button => button.TextContent.Trim() == "Ajouter").Click();
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Ajouter un identifiant caméra"));
|
||||
|
||||
var inputs = cut.FindAll("input");
|
||||
inputs.Count.ShouldBeGreaterThanOrEqualTo(3);
|
||||
inputs[0].Input("synthetic admin");
|
||||
inputs[1].Input("camera-user");
|
||||
inputs[2].Input("synthetic-only-password");
|
||||
await cut.InvokeAsync(() => cut.FindAll("div.mud-dialog-actions button")
|
||||
.Single(button => button.TextContent.Trim() == "Ajouter")
|
||||
.Click());
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
Services.GetRequiredService<ISnackbar>().ShownSnackbars
|
||||
.Select(message => message.Message?.ToString() ?? "")
|
||||
.ShouldContain("Identifiant ajouté");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CamerasPage_AfficheTuilesCameras()
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@ using Heimdall.Web.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using MudBlazor;
|
||||
using Shouldly;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Heimdall.Web.Tests.Components.Pages;
|
||||
|
||||
@@ -91,6 +92,31 @@ public class DashboardTests : PageTestBase
|
||||
});
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("fr", "Bienvenue, Jean Dupont")]
|
||||
[InlineData("en", "Welcome, Jean Dupont")]
|
||||
public void DashboardPage_AfficheUneSeulePonctuationPourChaqueCulture(string language, string expected)
|
||||
{
|
||||
typeof(Dashboard).GetCustomAttributes(typeof(Microsoft.AspNetCore.Components.RouteAttribute), inherit: true)
|
||||
.Cast<Microsoft.AspNetCore.Components.RouteAttribute>()
|
||||
.Select(route => route.Template)
|
||||
.ShouldBe(["/", "/dashboard"]);
|
||||
|
||||
SetupHappyPath();
|
||||
LoginAs("Admin", "Jean Dupont");
|
||||
Services.GetRequiredService<UiLanguageService>().SetLanguage(language);
|
||||
|
||||
var cut = RenderPage<Dashboard>();
|
||||
var greeting = cut.FindComponent<Dashboard>().Find("p");
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
var text = Regex.Replace(greeting.TextContent, @"\s+", " ").Trim();
|
||||
text.ShouldBe(expected);
|
||||
text.ShouldNotContain(",,");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DashboardPage_AfficheSites()
|
||||
{
|
||||
|
||||
@@ -13,6 +13,24 @@ public class SiteDetailTests : PageTestBase
|
||||
{
|
||||
private static readonly Guid SiteId = Guid.NewGuid();
|
||||
|
||||
[Fact]
|
||||
public void SiteDetail_SansIdentifiants_AfficheEtatVideSansAlerteDeChargement()
|
||||
{
|
||||
Handler.OnGet($"api/sites/{SiteId}/credentials", Array.Empty<SiteCredentialItem>());
|
||||
Handler.OnGet("capacity/history", Array.Empty<SiteCapacityHistoryPoint>());
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", null, "UTC", null, true, false, DateTime.UtcNow));
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<SiteDetail>(p => p.Add(x => x.Id, SiteId));
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
cut.Markup.ShouldContain("Aucun identifiant déclaré");
|
||||
cut.Markup.ShouldNotContain("Une erreur est survenue");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SiteDetail_AfficheInformations()
|
||||
{
|
||||
|
||||
@@ -14,6 +14,20 @@ public class SitesPageTests : PageTestBase
|
||||
private static SiteItem Site(string name = "Site Alpha") =>
|
||||
new(SiteId, name, "1 rue de la Surveillance", "Europe/Paris", null, true, false, DateTime.UtcNow.AddDays(-5));
|
||||
|
||||
[Fact]
|
||||
public void SitesPage_SansSiteWrite_MasqueEtBloqueLaCreation()
|
||||
{
|
||||
Handler.OnGet("api/sites", new PagedData<SiteItem>([], 0, 1, 20));
|
||||
LoginAs("Viewer");
|
||||
|
||||
var cut = RenderPage<SitesPage>();
|
||||
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Aucun site."));
|
||||
cut.FindAll("button").ShouldNotContain(b => b.TextContent.Contains("Nouveau site"));
|
||||
cut.Markup.ShouldNotContain("Nom du site");
|
||||
cut.Markup.ShouldNotContain("Créer");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SitesPage_AfficheListeDesSites()
|
||||
{
|
||||
|
||||
@@ -57,6 +57,29 @@ public class SnapshotsPageTests : PageTestBase
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Aucune capture trouvée."));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SnapshotsPage_FiltresSAdaptentAuxPetitsEcransEtGardentLaRangeeDesktop()
|
||||
{
|
||||
Handler.OnGet("api/events", new EventPageResult([], 0, 1, 48));
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<SnapshotsPage>();
|
||||
|
||||
var filterLayout = cut.Find(".snapshot-filters");
|
||||
filterLayout.QuerySelector("input").ShouldNotBeNull();
|
||||
filterLayout.QuerySelector(".mud-select").ShouldNotBeNull();
|
||||
filterLayout.QuerySelector("button").ShouldNotBeNull();
|
||||
|
||||
// The desktop grid keeps all three controls on one row; the phone
|
||||
// breakpoint stacks them and permits the controls to shrink to the
|
||||
// available width (including 390 px and narrower viewports).
|
||||
cut.Markup.ShouldContain("grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr) auto");
|
||||
cut.Markup.ShouldContain("@media (max-width: 600px)");
|
||||
cut.Markup.ShouldContain("grid-template-columns: minmax(0, 1fr)");
|
||||
cut.Markup.ShouldNotContain("min-width:300px");
|
||||
cut.Markup.ShouldNotContain("min-width:180px");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SnapshotsPage_Recherche_FiltreLesSnapshots()
|
||||
{
|
||||
|
||||
@@ -159,6 +159,32 @@ public sealed class HeimdallApiClientTests : IDisposable
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SiteCredentials_ReadAddAndDelete_UseSiteScopedEndpoints()
|
||||
{
|
||||
SetAuthToken();
|
||||
var siteId = Guid.NewGuid();
|
||||
var credentialId = Guid.NewGuid();
|
||||
var item = new SiteCredentialItem
|
||||
{
|
||||
Id = credentialId, SiteId = siteId, Label = "Synthetic", Username = "camera-user"
|
||||
};
|
||||
_handler.QueueResponse(HttpStatusCode.OK, new[] { item });
|
||||
var listed = await _sut.GetSiteCredentialsAsync(siteId);
|
||||
Assert.Single(listed);
|
||||
Assert.Equal(credentialId, listed[0].Id);
|
||||
Assert.Contains($"api/sites/{siteId}/credentials", _handler.LastRequest!.RequestUri!.ToString());
|
||||
|
||||
_handler.QueueResponse(HttpStatusCode.OK, item);
|
||||
var added = await _sut.AddSiteCredentialAsync(siteId, "Synthetic", "camera-user", "fake-password");
|
||||
Assert.Equal(credentialId, added!.Id);
|
||||
Assert.Equal(HttpMethod.Post, _handler.LastRequest!.Method);
|
||||
|
||||
_handler.QueueResponse(HttpStatusCode.NoContent);
|
||||
Assert.True(await _sut.DeleteSiteCredentialAsync(siteId, credentialId));
|
||||
Assert.Contains($"api/sites/{siteId}/credentials/{credentialId}", _handler.LastRequest!.RequestUri!.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddUserToGroupAsync_WhenSuccess_ReturnsTrue()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user