This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
All commands run from HelpdeskDb/ (the solution root):
# Build
dotnet build HelpdeskDb.sln
# Run the web app
dotnet run --project WebApp/WebApp.csproj
# Run all tests
dotnet test HelpdeskDb.sln
# Run a single test class
dotnet test App.Tests/App.Tests.csproj --filter "FullyQualifiedName~HappyFlowTest"
# Run a single test method
dotnet test App.Tests/App.Tests.csproj --filter "FullyQualifiedName~HappyFlowTest.CreateNewAsset"
# Add EF migration
dotnet ef migrations add <MigrationName> --project App.DAL.EF --startup-project WebApp
# Apply migrations
dotnet ef database update --project App.DAL.EF --startup-project WebAppThis is an ASP.NET Core 10 asset-management helpdesk app (tracking physical IT assets stored in cupboards/rooms, with owners, categories, and reservations). The solution follows a strict layered architecture with manual mappers at each boundary — no AutoMapper.
WebApp
└── App.BLL / App.BLL.Contracts
└── App.DAL.EF / App.DAL.Contracts
└── App.Domain
└── Base.* (reusable base classes)
App.DTO (used by WebApp for API contracts, versioned under v1/)
App.BLL.DTO (used by BLL services internally)
App.DAL.DTO (used by DAL repositories)
- App.Domain — EF entity classes, all inherit
BaseEntity(which hasId,CreatedAt,CreatedBy,ChangedAt,ChangedBy) - App.DAL.EF —
AppDbContext,AppUOW(Unit of Work), repositories. Cascade delete is globally disabled (usesDeleteBehavior.Restrict).SaveChangesAsyncauto-stamps audit fields and blocksUserIdmodification. - App.BLL —
AppBLLaggregates all services. Services receive the UoW and a BLL mapper. Business logic lives here. - App.DTO — Versioned public API DTOs under
v1/. SeparateCreateObjects/andUpdateObjects/subdirectories. Each entity has its own manual mapper inMappers/. - App.Resources —
.resxlocalization files for all domain entities and views. Three files per entity:Entity.resx(English/default),Entity.et.resx,Entity.ru.resx. - WebApp — Three controller groups:
ApiControllers/— REST API (JWT Bearer, versionedapi/v{version}/...)Areas/Admin/Controllers/— MVC admin area (cookie auth, requires admin roles)Controllers/— MVC user-facing pages (cookie auth)ApiControllers/Identity/AccountController— login/logout/refresh-token using FreeIPA
Every entity has three mapper layers, each implementing IMapper<TSource, TDest> from Base.Contracts:
App.Domain.Entity
↕ App.DAL.EF/Mappers/EntityUOWMapper.cs (Domain ↔ DAL.DTO)
App.DAL.DTO.Entity
↕ App.BLL/Mappers/EntityBLLMapper.cs (DAL.DTO ↔ BLL.DTO)
App.BLL.DTO.Entity
↕ App.DTO/v1/Mappers/EntityMapper.cs (BLL.DTO ↔ App.DTO)
App.DTO.v1.Entity
Navigation properties are nulled out in mappers to avoid circular references — only scalar fields and FK IDs are copied. Complex aggregated read results (e.g. AssetViewModel) live in App.DAL.DTO/ViewModels/ and App.BLL.DTO/ViewModels/ and use separate view model mappers.
Authentication is via FreeIPA (ipa.lapikud.ee), not ASP.NET Identity. On login, the app calls the IPA JSON-RPC API and bidirectionally syncs roles: adds roles present in IPA and removes roles from DB that are no longer in IPA. Roles are also re-synced on every /renewRefreshToken call so changes to IPA group membership propagate without requiring the user to log out. Roles used: admins, helpdesk_db_admins, members, pixels.
Because IIpaAuthClient is scoped (each request gets a fresh FreeIPA.DotNet.IpaClient with no session), SyncRolesFromIpaAsync first authenticates the client with a dedicated IPA service account before issuing the user_show RPC. Configure via IpaServiceAccount__Username / IpaServiceAccount__Password env vars (see .env.example); the account needs read access to user_show (memberof_group), which any authenticated IPA user typically has. If the service account is misconfigured or IPA is unreachable, sync logs a warning and leaves existing DB roles untouched — it never fails the request.
Both cookie auth (MVC) and JWT Bearer (API) are registered. API controllers use [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)].
The API delivers the JWT to the SPA as an HttpOnly cookie named hd_jwt (path /api, set by AccountController.SetAuthCookies). The companion refresh token rides in hd_rt (path /api/v1/account). Both are SameSite=Strict and HttpOnly; Secure is set when the request is HTTPS or the environment is Production (UseSecureCookies = Request.IsHttps || _env.IsProduction()) — note docker-compose runs the backend with ASPNETCORE_ENVIRONMENT=Production, so cookies are always Secure there. The JwtBearerEvents.OnMessageReceived handler in Program.cs pulls the JWT out of the hd_jwt cookie when the Authorization header is missing, so the SPA never needs to send a Bearer header. GET /api/v1/account/me lets the SPA hydrate its identity state from the server-validated cookie.
Refresh tokens are hashed at rest. The raw token (32 random bytes, hex) is sent only in the hd_rt cookie; the DB stores its SHA-256 hex digest (HashRefreshToken in AccountController). Logout and renew hash the cookie value before matching. Rotation keeps the previous token's hash in PreviousRefreshToken with a 1-minute grace window so an in-flight request with the old token still succeeds. Refresh-token lifetime is hardcoded to 7 days (BaseRefreshToken / renew logic) — it is not configurable via JWTSecurity.
JWT validation is hardened in Program.cs: the app fails fast at startup on a missing or short JWTSecurity__Key, pins ValidAlgorithms to HMAC-SHA512, and sets ClockSkew = TimeSpan.Zero.
IPA calls go through the IIpaAuthClient abstraction (WebApp/ApiControllers/Identity/IIpaAuthClient.cs), registered scoped in Program.cs. The real implementation IpaAuthClient wraps FreeIPA.DotNet.IpaClient. AccountController depends on IIpaAuthClient (not the concrete client), which lets tests substitute FakeIpaAuthClient instead of hitting the real IPA server. Both the API login and the MVC Areas/Identity/Pages/Account/Login.cshtml.cs resolve IIpaAuthClient from DI.
The FrontendOnly policy (registered in Program.cs) reads its allowlist from the AllowedOrigins configuration array and calls AllowCredentials() so the auth cookies survive cross-origin requests. Because of AllowCredentials(), AllowAnyOrigin() cannot be used — the allowlist must be explicit. appsettings.json ships an empty AllowedOrigins: [""] placeholder; real values come from .env (via AllowedOrigins__0=http://localhost:3000, AllowedOrigins__1=https://..., etc.) since DotNetEnv loads .env into the environment before the configuration builder runs.
If a deployed frontend and backend are on different registrable domains (e.g. app.foo.com and api.bar.com), SameSite=Strict will block the auth cookies on cross-site requests — switch the cookie options in AccountController.SetAuthCookies to SameSiteMode.None + Secure=true (HTTPS only) when that happens.
TLS is expected to terminate at a reverse proxy (in dev, the Next.js server acts as that proxy for /api/*). Program.cs registers UseForwardedHeaders early in the pipeline with XForwardedFor | XForwardedProto and cleared KnownNetworks/KnownProxies, so Request.IsHttps reflects the client's real scheme when the proxy sends X-Forwarded-Proto (the frontend's src/middleware.ts does this). UseHsts() runs in non-Development environments. UseHttpsRedirection() is opt-in via the EnableHttpsRedirection configuration key (default false) so a plain-HTTP backend behind a TLS proxy is not redirected into a loop.
Launch profiles (WebApp/Properties/launchSettings.json): http → http://localhost:5018 (the default used by docs and the frontend proxy); https → https://localhost:7234 + http://localhost:5018 (dotnet run --launch-profile https).
Assets are the core entity. Each asset can have:
- Many
CategoryAssets(junction →Category) - Many
LocationAssets(junction →Location) - Many
OwnerAssets(junction →Owner) - One
RemovedAssets(soft-remove record) - Many
AssetReservations(user + time range)IsReturned(bool): set viaPOST Home/Returned.AssetReturned()sets it true and trimsreservationTotonowif it was in the future.IsReturnedgates all three availability queries:IsAssetReservationAvailable,HasActiveOrFutureReservation, andGetAssetsReservedByUserall filter!IsReturned— so a returned asset is immediately re-reservable.- Availability check applies a ±10-minute buffer around reservation times to prevent back-to-back conflicts.
SerialNumberandBarcodeonAssetare nullable strings (no min-length — optional identifiers). Both are included in the MVC overview search.AssetReservationextendsBaseEntityUser<AppUser>(notBaseEntity) —UserIdis inherited from the base class.- Reservation ownership is server-enforced: the API
HomeController.Reservealways sets the reservation'sUserIdfromUser.GetUserId(), ignoring any client-suppliedUserId(covered byHappyFlowTest.ReserveAsset_IgnoresClientSuppliedUserId).
Physical location hierarchy: Room → CupboardInRoom → Cupboard → LocationInCupboard → Location.
Each new entity touches all layers. Follow this checklist in order:
App.Domain/Entity.cs— domain class extendingBaseEntityApp.DAL.DTO/Entity.cs— DAL DTO (mirrors domain, no EF attributes)App.DAL.EF/Mappers/EntityUOWMapper.cs— implementsIMapper<DAL.DTO.Entity, Domain.Entity>App.DAL.EF/AppDbContext.cs— addDbSet<Domain.Entity>App.DAL.Contracts/IEntityRepository.cs— repository interface extendingIBaseRepository<DAL.DTO.Entity>App.DAL.EF/Repositories/EntityRepository.cs— extendsBaseRepository<DAL.DTO.Entity, Domain.Entity>App.DAL.Contracts/IAppUOW.cs— add propertyIEntityRepository EntityRepositoryApp.DAL.EF/AppUOW.cs— wire up lazy-initialized repositoryApp.BLL.DTO/Entity.cs— BLL DTOApp.BLL/Mappers/EntityBLLMapper.cs— implementsIMapper<BLL.DTO.Entity, DAL.DTO.Entity>App.BLL.Contracts/IEntityService.cs— service interface extendingIBaseService<BLL.DTO.Entity>App.BLL/Services/EntityService.cs— extendsBaseService<BLL.DTO.Entity, DAL.DTO.Entity, IEntityRepository>App.BLL.Contracts/IAppBLL.cs— add propertyIEntityService EntityServiceApp.BLL/AppBLL.cs— wire up lazy-initialized service with its BLL mapperApp.DTO/v1/Entity.cs— public API DTOApp.DTO/v1/Mappers/EntityMapper.cs— implementsIMapper<App.DTO.v1.Entity, BLL.DTO.Entity>WebApp/ApiControllers/EntitiesController.cs— REST controllerApp.Resources/Domain/Entity.resx,Entity.et.resx,Entity.ru.resx— localization strings- EF migration —
dotnet ef migrations add Add<Entity> ...
Views/AssetReservations/Index.cshtml (standalone reservations list): shows IsReturned as a column. Edit/Delete actions shown only when userId == currentUser && reservationTo >= now. Since AssetReturned() trims reservationTo to now, returned rows automatically lose their action links.
Views/Shared/_AssetListPartial.cshtml (overview "Assets Reserved By User" table): when asset.Reserved == true, shows "Change reservation time" + "Returned" + "Remove Reservation" buttons. After pressing "Returned", the asset disappears from the list because GetAssetsReservedByUser filters !IsReturned.
All tests are self-contained — no external PostgreSQL or FreeIPA server is required to run dotnet test.
Integration tests (App.Tests/IntegrationTests/) use CustomWebApplicationFactory<Program>, which:
- Swaps the Npgsql
DbContextOptions<AppDbContext>registration for a SQLite in-memory connection (DataSource=:memory:), kept open for the lifetime of the factory so the schema survives between calls. - Replaces
IIpaAuthClientwithFakeIpaAuthClient(App.Tests/IntegrationTests/FakeIpaAuthClient.cs) so login succeeds without real IPA credentials. The fake returns a successful login and a cannedmemberof_grouppayload listing all four roles (admins,members,pixels,helpdesk_db_admins) — tweakFakeIpaAuthClient.Groupsto simulate different role sets. - Injects a test JWT signing key + issuer/audience via
AddInMemoryCollection, so the test host does not depend on.env. - Seeds deterministic rows with fixed Guid IDs (roles, categories, rooms, cupboards, cupboardsInRooms, locations, locationsInCupboards — no owners; those come from the runtime
DataSeederor per-user creation at login) inSeedDatabefore tests run.
Unit tests (App.Tests/UnitTests/) use TestDatabaseFixture.CreateContext() — EF Core's InMemory provider with a fresh uniquely-named database per test (AppTests_{Guid.NewGuid()}). The fixture seeds the same entity shape as the integration factory and mocks IUserNameResolver. Repository and service layers both have coverage; unit tests exercise repositories directly against the in-memory context (not via Moq mocks of EF).
The Program class is declared public partial specifically to enable WebApplicationFactory<Program> in tests.
appsettings.json ships with empty secrets (connection strings and JWT key are blank). Real values must come from HelpdeskDb/.env (gitignored) for dotnet run and docker-compose. Tests do not read .env — they inject their own in-memory configuration.
First-time setup:
cp .env.example .env # then edit .env with your valuesDotNetEnv (v3.1.1) is called at the very top of Program.cs (Env.TraversePath().Load()) before the WebApplicationBuilder is created, so .env values are available to the configuration system as environment variable overrides.
Key variables in .env:
| Variable | Used by |
|---|---|
ConnectionStrings__DefaultConnection |
dotnet run local dev |
JWTSecurity__Key |
JWT signing (both local and Docker) |
POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD |
docker-compose db container |
DOCKER_DB_CONNECTION |
docker-compose webapp container (host = lapikudhelpdesk-db-postgres, matching the db service's container_name) |
AllowedOrigins__0, AllowedOrigins__1, … |
CORS allowlist for the FrontendOnly policy (one frontend origin per index, no trailing slash) |
JWT settings are under JWTSecurity: (Key, Issuer, Audience, ExpiresInSeconds). Refresh-token lifetime is not configurable — it is hardcoded to 7 days. Supported cultures and default culture are also in appsettings.json. EnableHttpsRedirection (default false) toggles UseHttpsRedirection() — see "HTTPS and reverse proxies".
On startup, DataSeeder runs migrations and seeds roles plus the real workspace structure (rooms Kontor/Akadeemia tee 5 and Ladu/Küberneetika maja; the office cabinet "Kapp" with positions Kapp 1x1–5x4; owner "Lapikud") if the tables are empty. The Ladu's cabinets and categories are not seeded.