28 Commits

Author SHA1 Message Date
Aaron Po
c0cb013f54 Show a user's avatar on the public profile (#333) 2026-10-13 01:23:29 -04:00
Aaron Po
dfe248ea5f Create pull_request_template.md 2026-10-11 21:40:41 -04:00
Aaron Po
ff775e3b8a Raise frontend contrast, unify the page frame, and add browser identity (#328) 2026-10-08 00:17:45 -04:00
Aaron Po
0e51630439 Make the production compose stack deployable and disclose the AI-generated catalogue (#329) 2026-10-08 00:17:45 -04:00
Aaron Po
bd0e9e4a20 Create landing page (#321) 2026-10-03 18:46:32 -04:00
Aaron Po
c5972b9f04 Features/public biography endpoint (#316) 2026-09-26 19:51:10 -04:00
Aaron Po
e1b6cba1d4 Upgrade MediatR to 12.5.0 and forward cancellation tokens through pipeline behaviors (#320) 2026-09-26 19:50:44 -04:00
Aaron Po
0ff42c3c70 Add authenticated user profile page with locked-down account endpoint (#315) 2026-09-23 00:58:54 -04:00
Aaron Po
a6a9046457 Fix CA1873 warning and consolidate test fixtures (#313) 2026-09-12 22:14:55 -04:00
Aaron Po
40ae75808c Add ValidationBehavior test coverage (#311) 2026-09-12 21:08:24 -04:00
Aaron Po
fbede956e9 Fix seed pipeline crash and make seeding failures fail CI (#309) 2026-09-12 17:11:02 -04:00
Aaron Po
3793fca65e Features/exceptions pipeline integration (#308) 2026-09-12 16:24:14 -04:00
Aaron Po
78d0eaa739 Move Infrastructure.Configuration into Configuration (#291) 2026-09-12 15:59:37 -04:00
Aaron Po
180ed41e68 Move Infrastructure.FileUpload into Features.PhotoUpload (#290) 2026-09-12 00:22:19 -04:00
Aaron Po
ce2c90070e Update web docs for Infrastructure.Email move (#289) 2026-09-11 23:59:47 -04:00
Aaron Po
de63e9f216 Move Infrastructure.Email into Features.Emails (#288) 2026-09-11 23:46:04 -04:00
Aaron Po
7187631ebc Move Infrastructure.Jwt into Features.Users (#287) 2026-09-11 23:14:30 -04:00
Aaron Po
5fa78fbdf6 Move Infrastructure.PasswordHashing into Features.Users (#286) 2026-09-11 22:21:22 -04:00
Aaron Po
f85ff79a2c Move email templates into Features.Emails (#283) 2026-09-11 02:11:50 -04:00
Aaron Po
a3ec7d63f2 Add validator tests for brewery and user commands (#282) 2026-09-06 17:48:03 -04:00
Aaron Po
9d5a463d93 Rename auth feature to Features.Users (#281) 2026-09-06 01:23:51 -04:00
Aaron Po
d958933250 Replace shared email commands with MediatR notifications (#280) 2026-09-05 22:37:00 -04:00
Aaron Po
4aa7ba5d9b Update doc comments in Features.Breweries source (#279) 2026-09-05 14:57:39 -04:00
Aaron Po
272a25fb05 docs(database): update City dbml doc to reflect composite unique constraint (#278) 2026-09-05 00:44:59 -04:00
Aaron Po
d9411eb00e refactor(database): update seed pipeline to use dapper (#277) 2026-09-05 00:37:14 -04:00
Aaron Po
78ad32e93a refactor(api-core): move service registration (#275) 2026-09-03 05:19:20 -04:00
Aaron Po
d6e176bcd9 Split dbo schema into per-domain SQL schemas (#274) 2026-09-02 22:23:30 -04:00
Aaron Po
8d59f09cb2 chore/update layouts in diagrams (#273) 2026-09-02 21:28:23 -04:00
363 changed files with 8038 additions and 2504 deletions

101
.github/pull_request_template.md vendored Normal file
View File

@@ -0,0 +1,101 @@
## Summary
<!--
State WHAT is changing and WHY, in two to five sentences.
A reader should understand the change without opening the diff.
Describe the problem first, then the outcome.
-->
## Type of change
<!-- Tick the one option that best describes this PR. -->
- [ ] Bug fix
- [ ] New feature
- [ ] Refactor (no change in behaviour)
- [ ] Performance improvement
- [ ] Documentation
- [ ] Tests only
- [ ] Build, CI or dependency update
- [ ] Other (please specify):
## Related issues
<!--
Link the issue(s) this PR relates to. Use one keyword per issue so that each is closed on merge:
Fixes #123
Fixes #124, fixes #125
Fixes owner/other-repo#456
Closing keywords only take effect when the PR targets the repository's default branch.
Use "Related to #123" if the PR should not close the issue.
If there is no issue, write "N/A" and explain the motivation in the Summary.
-->
## Approach and context
<!--
Explain how the change works and why this approach was chosen.
Include, where relevant:
- The decisions you made that are not obvious from the code.
- Alternatives you considered and why you rejected them.
- Known limitations or shortcomings, and any planned follow-up work.
- Background such as benchmark results or design documents.
Summarise the key points of any external link. Links may be inaccessible to future readers.
-->
## How this was tested
<!--
Describe what you ran and what you observed. Be specific, and state only what you actually did.
For example: the automated tests added or changed, manual steps and their outcome,
environments or platforms covered, and anything you were unable to test.
For a bug fix, note the test that fails without the fix.
-->
## Compatibility and risk
- [ ] This change is backwards compatible.
- [ ] This change is **breaking** (complete the details below).
- [ ] This change deprecates existing behaviour (complete the details below).
<!--
If breaking or deprecating, describe: what changes, who is affected,
and the migration path or recommended alternative.
Also note any deployment, configuration, data migration or rollback considerations.
-->
## User-facing change
<!--
Does this PR change behaviour that users, operators or API consumers will notice?
If not, write "None".
If so, write one or two sentences suitable for release notes, in plain language and from the
user's point of view. If users must take action when upgrading, state clearly that action is required.
-->
```release-note
```
## Notes for reviewers
<!--
Help reviewers focus. For example:
- Where to start, or a suggested order in which to read the files.
- Areas where you would particularly value scrutiny, or where you are uncertain.
- How any mechanical, generated or bulk changes were produced (for example a search-and-replace
or a code generator), so that reviewers can reproduce the steps.
- Screenshots or recordings for visual changes (include before and after where useful).
-->
## Checklist
- [ ] The PR has a single, focused purpose and contains no unrelated changes.
- [ ] The title is a clear, imperative summary of the change (for example, "Add retry to payment client").
- [ ] I have added or updated tests that cover this change.
- [ ] The build succeeds and the tests pass locally.
- [ ] The code follows the existing patterns and style of this repository.
- [ ] I have updated documentation, changelogs or API references where required.
- [ ] I have reviewed my own diff, and this description reflects the final state of the change.

View File

@@ -33,7 +33,7 @@ jobs:
if: always()
run: |
status=0
for name in test-env-api-specs test-env-unit-tests test-env-frontend-tests; do
for name in test-env-database-migrations test-env-database-seed test-env-api-specs test-env-unit-tests test-env-frontend-tests; do
code="$(docker inspect -f '{{.State.ExitCode}}' "$name" 2>/dev/null || echo 1)"
echo "$name exited with $code"
if [ "$code" != "0" ]; then

View File

@@ -1,4 +1,8 @@
flowchart TD
---
config:
layout: elk
---
flowchart LR
Start([start]) --> ParseArgs["main.cc: ParseArguments(argc, argv)"]
ParseArgs --> ArgsValid{Arguments valid?}
ArgsValid -- no --> LogErr[Log error / usage info] --> Stop1([stop])

View File

@@ -1,3 +1,8 @@
---
config:
layout: elk
---
classDiagram
class BiergartenPipelineOrchestrator {
-shared_ptr~ILogger~ logger_

View File

@@ -1,4 +1,9 @@
flowchart TD
---
config:
layout: elk
---
flowchart LR
Start([start]) --> ParseArgs["Main: ParseArguments(argc, argv)"]
ParseArgs --> InvalidArgs{Invalid args?}
InvalidArgs -- yes --> LogErr["spdlog::error"] --> Stop1([stop])

View File

@@ -1,3 +1,7 @@
---
config:
layout: elk
---
classDiagram
namespace DomainModels {
class Location {

View File

@@ -77,7 +77,7 @@ flowchart TB
subgraph SHARED["Shared Projects"]
direction LR
SH1["Shared.Contracts<br/>ResponseBody envelope"]
SH2["Shared.Application<br/>ValidationBehavior,<br/>cross-slice email commands"]
SH2["Shared.Application<br/>ValidationBehavior"]
end
subgraph DOMAIN["Domain Layer"]
@@ -89,16 +89,14 @@ flowchart TB
subgraph INFRA["Infrastructure Layer"]
direction LR
I1["Database.Connection"]
I2["Infrastructure.Jwt"]
I3["Infrastructure.PasswordHashing"]
I4["Infrastructure.Email /<br/>Email.Templates"]
I5["Infrastructure.FileUpload"]
I4["Email.Templates"]
end
DB[("Database (SQL Server)")]
HOST -- "discovers controllers via<br/>AddApplicationPart" --> SLICES
S1 -- "SendRegistrationEmailCommand<br/>(via Shared.Application contract)" --> S3
S3 == "ProjectReference<br/>(handles UserRegisteredNotification & ConfirmationEmailResendRequestedNotification)" ==> S1
S1 -- "ProjectReference<br/>(avatar upload)" --> S5
SLICES --> SHARED
@@ -123,7 +121,8 @@ own
| Component | Description |
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Program.cs` | Registers MediatR (scanning every `Features.*` assembly), FluentValidation, and uses `AddApplicationPart` so each slice's controllers are discovered by MVC. |
| `Program.cs` | Thin composition root: builds the host and calls the `ServiceCollectionExtensions` methods below. |
| `ServiceCollectionExtensions.cs` | Registers MediatR (scanning every `Features.*` assembly), FluentValidation, and uses `AddApplicationPart` so each slice's controllers are discovered by MVC. |
| `GlobalException.cs` | Global exception filter (host-level cross-cutting concern). |
| `Authentication/JwtAuthenticationHandler.cs` | JWT auth scheme middleware. |
| Swagger/OpenAPI documentation, health check endpoints | Host-level documentation and health endpoints. |
@@ -132,7 +131,6 @@ own
- Every `Features.*` project (for controller/MediatR discovery)
- `Shared.Contracts`, `Shared.Application`
- `Infrastructure.Jwt` (for the auth middleware)
**Rules**:
@@ -166,19 +164,21 @@ brewery photo upload command) rather than bound to an HTTP route directly.
- `Domain.Entities`, `Domain.Exceptions`
- `Database.Connection` (generic ADO.NET connection/command plumbing) plus
whichever infrastructure project the slice needs (`Infrastructure.Jwt`/
`Infrastructure.PasswordHashing` for Users, `Infrastructure.Email`/
`Infrastructure.Email.Templates` for Emails, `Infrastructure.FileUpload` for
PhotoUpload)
whichever infrastructure project the slice needs (`Infrastructure.PasswordHashing`
for Users, `Infrastructure.Email.Templates` for Emails)
- `Shared.Contracts`, `Shared.Application`
- No other `Features.*` project, with one exception: `Features.Users` references
`Features.PhotoUpload` directly for avatar uploads
- No other `Features.*` project, with two exceptions: `Features.Users`
references `Features.PhotoUpload` directly for avatar uploads, and
`Features.Emails` references `Features.Users` directly to handle
`UserRegisteredNotification` and `ConfirmationEmailResendRequestedNotification`
**Rules**:
- All business logic for that feature lives in its command/query handlers
- No direct controller-to-repository calls; everything flows through MediatR
- Read endpoints return a dedicated `Dto`, never the domain entity directly
- Read endpoints return a dedicated `Dto` rather than the domain entity
directly. The one exception is `UserController.GetAuthenticated`, which
returns the caller's own `UserAccount` entity
#### Shared projects (`Shared.Contracts`, `Shared.Application`)
@@ -189,8 +189,8 @@ needs it, or because duplicating it four times would be worse than sharing it
| Project | Purpose |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Shared.Contracts` | `ResponseBody<T>`/`ResponseBody`, the API response envelope every controller returns |
| `Shared.Application` | `ValidationBehavior<TRequest,TResponse>` (the MediatR pipeline behavior that runs FluentValidation before a handler executes) and the cross-slice email commands (`SendRegistrationEmailCommand`, `SendResendConfirmationEmailCommand`) |
| `Shared.Contracts` | `ResponseBody<T>`/`ResponseBody`, the API response envelope `AuthController`, `BreweryController`, and `CityController` return; `UserController`'s read endpoints return their DTOs unwrapped |
| `Shared.Application` | `ValidationBehavior<TRequest,TResponse>`, the MediatR pipeline behavior that runs FluentValidation before a handler executes |
**Rules**:
@@ -207,11 +207,8 @@ whichever slices need them
| Project | Description |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Database.Connection` | Generic ADO.NET connection/command plumbing (`DefaultSqlConnectionFactory`, the abstract `DapperRepository` base class), not domain-specific; each slice's own `Repository/` folder builds on this. |
| `Infrastructure.Jwt` | JWT token generation and validation. |
| `Infrastructure.PasswordHashing` | Argon2id password hashing. |
| `Infrastructure.Email` | Email sending capabilities (SMTP/MailKit). |
| `Infrastructure.Email.Templates` | Email template rendering (Razor components). |
| `Infrastructure.FileUpload` | `IFileStorageProvider` abstraction over S3-compatible object storage, implemented by `S3FileStorageProvider` (targets the SeaweedFS container in dev; any S3-compatible endpoint in other environments) using the AWS SDK's `AmazonS3Client` with `ForcePathStyle = true`. |
**Dependencies**:
@@ -269,7 +266,8 @@ everything needed to understand or change one capability lives in one project
- Controllers generally bind directly to the Command/Query as the request body;
there is no separate request DTO + mapping step for writes
- The exception to this is for authenticated routes, when the current user id
needs to be extracted from the authentication token to be used in a command.
needs to be extracted from the authentication token to be used in a command
or query.
- A single shared `ValidationBehavior<TRequest,TResponse>`
(`Shared.Application/Behaviors/`) runs FluentValidation validators in the
MediatR pipeline before any handler executes
@@ -384,6 +382,7 @@ web/frontend/
│ │ - catalog beers, beer styles
│ │ - home landing page
│ │ - theme theme switcher/guide
│ │ - users public user profile page (/users/:id)
│ ├── hooks/ Shared hooks not tied to one feature, for example useMediaQuery
│ ├── routes.ts Route table (React Router 8 config-based routing)
│ ├── root.tsx App shell and global providers
@@ -400,6 +399,8 @@ web/frontend/
`/breweries/:id`) with Leaflet-powered maps and geolocation-based "nearby"
search
- Render the auth demo, account dashboard, and theme guide routes
- Render the public user profile route (`/users/:id`), including a user's
following list and (via brewery comments) links back to commenter profiles
- Manage cookie-backed website session state
- Call the .NET API for login, registration, token refresh, confirmation, and
brewery/location data
@@ -564,11 +565,12 @@ are not seeded either.
**Environments**:
| Environment | Compose file |
| ----------- | -------------------------- |
| Development | `docker-compose.dev.yaml` |
| Testing | `docker-compose.test.yaml` |
| Production | `docker-compose.prod.yaml` |
| Environment | Compose file |
| --------------- | ------------------------------- |
| Development | `docker-compose.dev.yaml` |
| Testing | `docker-compose.test.yaml` |
| Production | `docker-compose.prod.yaml` |
| Production seed | `docker-compose.prod.seed.yaml` |
For details, see [Docker Guide](docker.md).

View File

@@ -15,33 +15,51 @@ convention. For the vertical-slice code that talks to this schema, see
## Schema
The full schema lives under
`web/backend/Database/Database.Migrations/scripts/01-schema/` with one numbered
script per table.
The schema is split into six SQL Server schemas, one per feature area, each
living in its own numbered folder under
`web/backend/Database/Database.Migrations/scripts/`. The folder numbers
(`01`-`06`) fix the load order so foreign-key dependencies resolve — DbUp runs
embedded scripts in alphabetical-by-resource-name order, so e.g. `04-Brewery`
(which references `Auth`, `Geolocation`, and `Media`) runs after all three.
Each folder's `00-Schema.sql` creates its SQL schema before its tables run:
```
01-schema
├── 01-UserAccount.sql
├── 02-Photo.sql
├── 03-UserVerification.sql
├── 04-UserCredential.sql
├── 05-UserFollow.sql
├── 06-Country.sql
├── 07-StateProvince.sql
├── 08-City.sql
├── 09-BreweryPost.sql
├── 10-BreweryPostLocation.sql
├── 11-BreweryPostPhoto.sql
├── 12-BeerStyle.sql
├── 13-BeerPost.sql
├── 14-BeerPostPhoto.sql
├── 15-BeerPostComment.sql
├── 16-UserProfile.sql
└── 17-UserAvatar.sql
scripts
├── 01-Auth (UserAccount, UserVerification, UserCredential)
│ ├── 00-Schema.sql
│ ├── 01-UserAccount.sql
│ ├── 02-UserVerification.sql
│ └── 03-UserCredential.sql
├── 02-Geolocation (Country, StateProvince, City)
│ ├── 00-Schema.sql
│ ├── 01-Country.sql
│ ├── 02-StateProvince.sql
│ └── 03-City.sql
├── 03-Media (Photo)
│ ├── 00-Schema.sql
│ └── 01-Photo.sql
├── 04-Brewery (BreweryPost, BreweryPostLocation, BreweryPostPhoto)
│ ├── 00-Schema.sql
│ ├── 01-BreweryPost.sql
│ ├── 02-BreweryPostLocation.sql
│ └── 03-BreweryPostPhoto.sql
├── 05-Beer (BeerStyle, BeerPost, BeerPostPhoto, BeerPostComment)
│ ├── 00-Schema.sql
│ ├── 01-BeerStyle.sql
│ ├── 02-BeerPost.sql
│ ├── 03-BeerPostPhoto.sql
│ └── 04-BeerPostComment.sql
└── 06-Social (UserFollow, UserProfile, UserAvatar)
├── 00-Schema.sql
├── 01-UserFollow.sql
├── 02-UserProfile.sql
└── 03-UserAvatar.sql
```
Each script is run in order by `Database.Migrations` (DbUp) on startup. Each
table is queried directly by the owning feature slice's repository (see
Each script is run in order by `Database.Migrations` (DbUp) on startup. Tables
are referenced schema-qualified in code (e.g. `Auth.UserAccount`), not under
the default `dbo` schema. Each table is queried directly by the owning
feature slice's repository (see
[Direct SQL via Dapper/ADO.NET](architecture.md#direct-sql-via-dapperadonet)).
A generated DBML copy of the schema (for import into a diagramming tool such as
@@ -58,14 +76,14 @@ updates (`UPDATE ... WHERE ... AND RowVersion = @RowVersion`).
| `UserAccount` | `Domain.Entities.UserAccount`, `Features.Users` | `Username` and `Email` are unique |
| `UserCredential` | `Domain.Entities.UserCredential`, `Features.Users` | Argon2id password hash; `IsRevoked`/`RevokedAt` track credential rotation, not JWTs |
| `UserVerification` | `Domain.Entities.UserVerification`, `Features.Users` | Written when a user confirms their email |
| `UserProfile` | `Domain.Entities.UserProfile`, `Features.Users` | 1:1 with `UserAccount`; holds the user's biography; written via `IUserProfileRepository` |
| `UserAvatar` | `Domain.Entities.UserAvatar`, `Features.Users` | Links a `UserProfile` to a `Photo` as its avatar; written via `IUserProfileRepository.SaveAvatarAsync` |
| `UserProfile` | `Domain.Entities.UserProfile`, `Features.Users` | 1:1 with `UserAccount`; holds the user's biography; written via `IUserProfileRepository`, read via `IUserListRepository`'s left joins in both `GetByIdAsync` and `GetAllAsync` |
| `UserAvatar` | `Domain.Entities.UserAvatar`, `Features.Users` | Links a `UserProfile` to a `Photo` as its avatar; written via `IUserProfileRepository.SaveAvatarAsync`, read via `IUserListRepository`'s `ValidTo IS NULL` join for the active avatar |
| `BreweryPost` | `Domain.Entities.BreweryPost`, `Features.Breweries` | A user-submitted brewery listing |
| `BreweryPostLocation` | `Domain.Entities.BreweryPostLocation`, `Features.Breweries` | 1:1 with `BreweryPost`; `Coordinates` is a `GEOGRAPHY` column, read via a plain Dapper query that selects `CONVERT(varbinary(max), Coordinates)`, since Dapper can't deserialize SQL Server UDTs directly |
| `City` | `Domain.Entities.City`, `Features.Locations` | Referenced by `BreweryPostLocation.CityID`; written via `ILocationRepository`, read via `ILocationRepository` and `IBreweryRepository`'s location joins, currently written only by `Database.Seed` |
| `City` | `Domain.Entities.City`, `Features.Locations` | Referenced by `BreweryPostLocation.CityID`; `CityName` and `StateProvinceID` together are unique; written via `ILocationRepository`, read via `ILocationRepository` and `IBreweryRepository`'s location joins, currently written only by `Database.Seed` |
| `StateProvince` | `Domain.Entities.StateProvince`, `Features.Locations` | Referenced by `City.StateProvinceID`; created on demand by `ILocationRepository.GetOrCreateCityIdAsync`, read via `IBreweryRepository`'s location joins |
| `Country` | `Domain.Entities.Country`, `Features.Locations` | Referenced by `StateProvince.CountryID`; created on demand by `ILocationRepository.GetOrCreateCityIdAsync`, read via `IBreweryRepository`'s location joins |
| `Photo` | `Domain.Entities.Photo`, `Features.PhotoUpload` | Written via `IPhotoUploadRepository.CreateAsync`, sent as an `UploadPhotoCommand` from other features' handlers; not yet seeded by `Database.Seed` |
| `Photo` | `Domain.Entities.Photo`, `Features.PhotoUpload` | Written via `IPhotoUploadRepository.CreateAsync`, sent as an `UploadPhotoCommand` from other features' handlers; `Hyperlink` holds the object key within the bucket, which readers sign into a time-limited URL via `IFileStorageProvider.GetPresignedUrl`; the active avatar's row is also read via `IUserListRepository`'s `Media.Photo` join; not yet seeded by `Database.Seed` |
### Tables defined in the schema but not yet wired to a feature slice

View File

@@ -127,9 +127,9 @@ sequenceDiagram
TokenSvc-->>RegHandler: Confirmation Token
deactivate TokenSvc
RegHandler->>Mediator: Send(SendRegistrationEmailCommand) (Shared.Application cross-slice contract)
RegHandler->>Mediator: Publish(UserRegisteredNotification)
activate Mediator
Note right of Mediator: Routed to Features.Emails' SendRegistrationEmailHandler — the second of two cross-slice dispatches in this flow (profile creation is the first)
Note right of Mediator: Features.Emails has a direct ProjectReference on Features.Users and handles the notification via UserRegisteredNotificationHandler — the second of two cross-slice dispatches in this flow (profile creation is the first)
Mediator->>EmailDispatcher: SendRegistrationEmailAsync(firstName, email, confirmationToken)
activate EmailDispatcher
@@ -147,15 +147,15 @@ sequenceDiagram
SMTP-->>EmailDispatcher: Success / throws
deactivate SMTP
deactivate EmailDispatcher
deactivate Mediator
alt Email sent successfully
RegHandler->>RegHandler: emailSent = true
else mediator.Send throws
RegHandler->>RegHandler: catch(Exception), log to stderr, emailSent = false
Note right of Mediator: UserRegisteredNotificationHandler completes normally
else EmailDispatcher throws
Note right of Mediator: UserRegisteredNotificationHandler catches and logs the exception — registration is unaffected
end
deactivate Mediator
RegHandler-->>Mediator: RegistrationPayload(userAccountId, username, refreshToken, accessToken, confirmationEmailSent)
RegHandler-->>Mediator: RegistrationPayload(userAccountId, username, refreshToken, accessToken)
deactivate RegHandler
Mediator-->>API: RegistrationPayload
deactivate Mediator

View File

@@ -51,13 +51,20 @@ sequenceDiagram
TokenSvc-->>ResendHandler: confirmation token
deactivate TokenSvc
ResendHandler->>Mediator: Send(SendResendConfirmationEmailCommand)
ResendHandler->>Mediator: Publish(ConfirmationEmailResendRequestedNotification)
activate Mediator
Note right of Mediator: Features.Emails has a direct ProjectReference on Features.Users and handles the notification via ConfirmationEmailResendRequestedNotificationHandler
Mediator->>EmailDispatcher: SendResendConfirmationEmailAsync(firstName, email, confirmationToken)
activate EmailDispatcher
EmailDispatcher->>Template: Render email (same Razor pipeline as registration)
EmailDispatcher->>SMTP: SendAsync(email, subject, body)
deactivate EmailDispatcher
alt Email sent successfully
Note right of Mediator: ConfirmationEmailResendRequestedNotificationHandler completes normally
else EmailDispatcher throws
Note right of Mediator: ConfirmationEmailResendRequestedNotificationHandler catches and logs the exception — the resend request is unaffected
end
deactivate Mediator
end
end

View File

@@ -1,39 +1,46 @@
# Database Schema
Five diagrams, one per schema category — mirrors the `identity` / `media` /
`location` / `brewery` / `beer` schema split. Every table also has a
Six diagrams, one per SQL Server schema — mirrors the `Auth` / `Geolocation` /
`Media` / `Brewery` / `Beer` / `Social` schema split under
`web/backend/Database/Database.Migrations/scripts/`. Every table also has a
`RowVersion ROWVERSION` column (optimistic concurrency), omitted below for
brevity. Tables marked `(*)` have no repository/feature slice yet.
Boxes with no attribute list (e.g. `Photo` in the identity diagram) are owned by
a different schema and shown only to keep the relationship visible; see the
Boxes with no attribute list (e.g. `Photo` in the auth diagram) are owned by a
different schema and shown only to keep the relationship visible; see the
diagram named after that schema for its full definition.
## Identity (`identity`)
## Auth (`Auth`)
```mermaid
--8<-- "web/diagrams/database-schema/identity.mmd"
--8<-- "web/diagrams/database-schema/auth.mmd"
```
## Media (`media`)
## Social (`Social`)
```mermaid
--8<-- "web/diagrams/database-schema/social.mmd"
```
## Media (`Media`)
```mermaid
--8<-- "web/diagrams/database-schema/media.mmd"
```
## Location (`location`)
## Geolocation (`Geolocation`)
```mermaid
--8<-- "web/diagrams/database-schema/location.mmd"
--8<-- "web/diagrams/database-schema/geolocation.mmd"
```
## Brewery (`brewery`)
## Brewery (`Brewery`)
```mermaid
--8<-- "web/diagrams/database-schema/brewery.mmd"
```
## Beer (`beer`)
## Beer (`Beer`)
```mermaid
--8<-- "web/diagrams/database-schema/beer.mmd"

View File

@@ -1,12 +1,16 @@
---
config:
layout: elk
---
erDiagram
User ||--o{ Cred : "has credentials"
User ||--o| Verify : "has verification"
%% Cross-schema: defined in full in social.mmd / media.mmd / brewery.mmd / beer.mmd
User ||--o| Profile : "has profile"
User ||--o{ Follow : "follows"
User ||--o{ Follow : "followed by"
%% Cross-schema: defined in full in media.mmd / brewery.mmd / beer.mmd
Profile ||--o{ Avatar : "has avatar history"
User ||--o{ Photo : "uploads"
User ||--o{ Brewery : "posts"
User ||--o{ Beer : "posts"
@@ -38,16 +42,3 @@ erDiagram
uniqueidentifier UserAccountID "FK, UK"
datetime VerificationDateTime
}
Profile {
uniqueidentifier UserProfileID PK
uniqueidentifier UserAccountID "FK, UK"
nvarchar Biography
}
Follow {
uniqueidentifier UserFollowID PK
uniqueidentifier UserAccountID FK
uniqueidentifier FollowingID FK
datetime CreatedAt
}

View File

@@ -1,12 +1,18 @@
---
config:
layout: elk
---
erDiagram
BeerStyle ||--o{ Beer : "categorizes"
Beer ||--o{ BeerPhoto : "has photos"
Beer ||--o{ BeerComment : "has comments"
%% Cross-schema: defined in full in identity.mmd / brewery.mmd / media.mmd
%% Cross-schema: defined in full in auth.mmd / brewery.mmd / media.mmd
User ||--o{ Beer : "posts"
Brewery ||--o{ Beer : "brews"
User ||--o{ BeerComment : "comments"
BeerPhoto }o--|| Photo : "uses photo"
BeerStyle {
uniqueidentifier BeerStyleID PK
@@ -36,3 +42,10 @@ erDiagram
datetime CreatedAt
datetime UpdatedAt "nullable"
}
BeerPhoto {
uniqueidentifier BeerPostPhotoID PK
uniqueidentifier BeerPostID FK
uniqueidentifier PhotoID FK
datetime LinkedAt
}

View File

@@ -1,10 +1,18 @@
---
config:
layout: elk
---
erDiagram
Brewery ||--o| BreweryLoc : "has location"
Brewery ||--o| BreweryLocation : "has location"
Brewery ||--o{ BreweryPhoto : "has photos"
Brewery ||--o{ Beer : "brews"
%% Cross-schema: defined in full in identity.mmd / location.mmd / media.mmd / beer.mmd
%% Cross-schema: defined in full in auth.mmd / geolocation.mmd / media.mmd / beer.mmd
User ||--o{ Brewery : "posts"
BreweryLocation }o--|| City : "located in"
BreweryPhoto }o--|| Photo : "uses photo"
Brewery {
uniqueidentifier BreweryPostID PK
@@ -14,3 +22,20 @@ erDiagram
datetime CreatedAt
datetime UpdatedAt "nullable"
}
BreweryLocation {
uniqueidentifier BreweryPostLocationID PK
uniqueidentifier BreweryPostID "FK, UK"
nvarchar AddressLine1
nvarchar AddressLine2 "nullable"
nvarchar PostalCode
uniqueidentifier CityID FK
geography Coordinates "nullable"
}
BreweryPhoto {
uniqueidentifier BreweryPostPhotoID PK
uniqueidentifier BreweryPostID FK
uniqueidentifier PhotoID FK
datetime LinkedAt
}

View File

@@ -1,10 +1,9 @@
erDiagram
Country ||--o{ StateProvince : "has"
StateProvince ||--o{ City : "has"
City ||--o{ BreweryLoc : "located in"
%% Cross-schema: defined in full in brewery.mmd
Brewery ||--o| BreweryLoc : "has location"
City ||--o{ BreweryLocation : "located in"
Country {
uniqueidentifier CountryID PK
@@ -19,18 +18,9 @@ erDiagram
uniqueidentifier CountryID FK
}
%% CityName + StateProvinceID form a composite unique constraint (AK_CityStateProvince)
City {
uniqueidentifier CityID PK
nvarchar CityName
uniqueidentifier StateProvinceID FK
}
BreweryLoc {
uniqueidentifier BreweryPostLocationID PK
uniqueidentifier BreweryPostID "FK, UK"
nvarchar AddressLine1
nvarchar AddressLine2 "nullable"
nvarchar PostalCode
uniqueidentifier CityID FK
geography Coordinates "nullable"
nvarchar CityName UK
uniqueidentifier StateProvinceID FK,UK
}

View File

@@ -1,39 +1,19 @@
---
config:
layout: elk
---
erDiagram
User ||--o{ Photo : "uploads"
%% Cross-schema: defined in full in auth.mmd / social.mmd / brewery.mmd / beer.mmd
Avatar }o--|| Photo : "uses photo"
Photo ||--o{ BreweryPhoto : "used in"
Photo ||--o{ BeerPhoto : "used in"
%% Cross-schema: defined in full in identity.mmd / brewery.mmd / beer.mmd
Profile ||--o{ Avatar : "has avatar history"
User ||--o{ Photo : "uploads"
Brewery ||--o{ BreweryPhoto : "has photos"
Beer ||--o{ BeerPhoto : "has photos"
Photo {
uniqueidentifier PhotoID PK
nvarchar Hyperlink "nullable"
uniqueidentifier UploadedByID FK
datetime UploadedAt
}
Avatar {
uniqueidentifier UserAvatarID PK
uniqueidentifier UserProfileID FK
uniqueidentifier PhotoID FK
datetime2 ValidFrom
datetime2 ValidTo "nullable; at most one row per UserProfileID has ValidTo IS NULL (active avatar)"
}
BreweryPhoto {
uniqueidentifier BreweryPostPhotoID PK
uniqueidentifier BreweryPostID FK
uniqueidentifier PhotoID FK
datetime LinkedAt
}
BeerPhoto {
uniqueidentifier BeerPostPhotoID PK
uniqueidentifier BeerPostID FK
uniqueidentifier PhotoID FK
datetime LinkedAt
}

View File

@@ -0,0 +1,34 @@
---
config:
layout: elk
---
erDiagram
User ||--o| Profile : "has profile"
User ||--o{ Follow : "follows"
User ||--o{ Follow : "followed by"
Profile ||--o{ Avatar : "has avatar history"
%% Cross-schema: defined in full in auth.mmd / media.mmd
Avatar }o--|| Photo : "uses photo"
Profile {
uniqueidentifier UserProfileID PK
uniqueidentifier UserAccountID "FK, UK"
nvarchar Biography
}
Follow {
uniqueidentifier UserFollowID PK
uniqueidentifier UserAccountID FK
uniqueidentifier FollowingID FK
datetime CreatedAt
}
Avatar {
uniqueidentifier UserAvatarID PK
uniqueidentifier UserProfileID FK
uniqueidentifier PhotoID FK
datetime2 ValidFrom
datetime2 ValidTo "nullable; at most one row per UserProfileID has ValidTo IS NULL (active avatar)"
}

View File

@@ -41,7 +41,7 @@ no data flowing over them.
| ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Dev network** (`devnet`, bridge) | Internal DNS resolves service names such as `sqlserver` and `api.core`. Volumes: `sqlserverdata-dev`, `nuget-cache-dev`, `seaweedfsdata-dev`. Startup order: SQL Server (health check) → migrations (run-once) → seed (run-once, depends on `seaweedfs`) → API (long-running, depends on seed). |
| **Test network** (`testnet`, bridge) | All test components are isolated; fresh DB instance each run (`CLEAR_DATABASE=true`, ephemeral `sqlserverdata-test` / `seaweedfsdata-test` volumes). `api.specs`, `unit.tests`, and `frontend.tests` all run as separate containers, in parallel once seeding completes; results are aggregated. |
| **Prod network** (`prodnet`, bridge) | Isolated from dev/test networks. Volumes: `sqlserverdata-prod`, `nuget-cache-prod`. No seed step in production. |
| **Prod network** (`prodnet`, bridge, named `biergarten-prodnet`) | Isolated from dev/test networks. Volumes: `biergartendata-prod` and `seaweedfsdata-prod`, both external, so `down -v` keeps them. Startup order: SeaweedFS (health check) → API (health check) → frontend, with `frontend` the only service publishing a host port, bound to `127.0.0.1`. Migrating and seeding run on demand as their own run-once jobs joining `biergarten-prodnet`, so an `up` or a reboot replays neither. |
| **Database-only environment** | Same devnet volumes/images as `docker-compose.dev.yaml`, minus `api.core`, `frontend`, and `mailpit` — for working against the database (and object storage, since `seaweedfs` is still included) without running the API or website. |
| **Minimal environment** | Database + migrations + seed + `seaweedfs` + mailpit, no API or frontend container — for frontend development against an `API.Core` process run outside Docker. |
| `unit.tests` | Builds `Dockerfile.tests`, which restores/builds against `Biergarten.API.slnx` and then runs `dotnet test` for every `Features/*.Tests` project in turn (`Features.Users.Tests`, `Features.Breweries.Tests`, `Features.Emails.Tests`, `Features.PhotoUpload.Tests`), mocking each handler's repository/service dependencies with Moq — no real database needed. |

View File

@@ -1,11 +1,13 @@
sequenceDiagram
box Production Environment (docker-compose.prod.yaml)
participant ProdDB as SQL Server 2022<br/>Biergarten Database<br/>no host port published
participant ProdMig as Migrations (run-once)
participant ProdS3 as SeaweedFS<br/>S3 gateway :8333<br/>no host port published
participant ProdAPI as API Container<br/>ASP.NET Core 10<br/>:8080 HTTP / :8081 HTTPS
participant ProdWeb as Frontend Container<br/>Express + React Router<br/>127.0.0.1:5656
end
ProdMig-->>ProdDB: depends_on
ProdMig->>ProdDB: Run migrations
ProdAPI-->>ProdDB: depends_on: sql-server healthy (not migrations/seed)
ProdAPI-->>ProdS3: depends_on: seaweedfs healthy
ProdWeb-->>ProdAPI: depends_on: api.core healthy
ProdAPI->>ProdDB: Connect and serve
ProdAPI->>ProdS3: Store and read photos
Note over ProdDB: Migrating and seeding are separate run-once jobs,<br/>run at deploy time rather than by the stack

View File

@@ -16,13 +16,14 @@ doesn't wire up any slice; it applies schema directly.
## Project reference dependencies
Solid arrows are compile-time project references. Dashed arrows are the two
places slices talk to each other without a direct reference: the email MediatR
contract routed through `Shared.Application`, and the one place that pattern is
broken outright. Every DB-backed slice depends on the same three foundation
projects (`Shared.Contracts`, `Domain.Entities`, `Database.Connection`) — drawn
as one box instead of fifteen separate arrows; see the notes for what else each
of those foundation projects pulls in.
Solid arrows are compile-time project references — every slice-to-slice
dependency is one now that the email MediatR contract has moved off
`Shared.Application`: `Features.Users` on `Features.PhotoUpload` for avatar
uploads, and `Features.Emails` on `Features.Users` for the registration and
resend-confirmation notifications. Every DB-backed slice depends on the same
three foundation projects (`Shared.Contracts`, `Domain.Entities`,
`Database.Connection`) — drawn as one box instead of fifteen separate arrows;
see the notes for what else each of those foundation projects pulls in.
```mermaid
--8<-- "web/diagrams/vertical-slice/project-references.mmd"
@@ -44,8 +45,6 @@ of those foundation projects pulls in.
commands/queries + handlers, validators, and Dapper repository
- `Features.Users` covers auth (`Commands/Authentication`), account management
(`Commands/Account`), and profile/avatar (`Commands/Profile`)
- internally namespaced `Features.Auth`, despite project name
`Features.Users`
- `Features.Emails` and `Features.PhotoUpload` have no controller — invoked
only via MediatR commands sent from other slices
- `Features.Locations` has no controller; one MediatR handler
@@ -54,17 +53,20 @@ of those foundation projects pulls in.
- `Features.Beers` is scaffolded (project + references only, no source files
yet)
- **The one exception to slice isolation**: `Features.Users` takes a direct
project reference to `Features.PhotoUpload`
- sends its `UploadPhotoCommand` via MediatR from `UploadAvatarHandler`
- unlike the email flow, the command type lives in the target slice itself,
not in `Shared.Application`
- **The exceptions to slice isolation**:
- `Features.Users` takes a direct project reference to `Features.PhotoUpload`
- sends its `UploadPhotoCommand` via MediatR from `UploadAvatarHandler`
- the command type lives in the target slice itself, not in
`Shared.Application`
- `Features.Emails` takes a direct project reference to `Features.Users`
- handles `UserRegisteredNotification` (published from
`RegisterUserHandler`) and `ConfirmationEmailResendRequestedNotification`
(published from `ResendConfirmationEmailHandler`)
- both notification types live in `Features.Users`
(`Features.Users.Notifications`), not in `Shared.Application`
- **Shared.Application**:
- `ValidationBehavior` (MediatR pipeline)
- Cross-slice email commands (`SendRegistrationEmailCommand`,
`SendResendConfirmationEmailCommand`)
- MediatR command contract (not project reference)
- Every slice (including `Features.Emails`) references it for the pipeline
behavior alone
@@ -95,9 +97,9 @@ of those foundation projects pulls in.
- **Omitted from the diagram**:
- `Domain.Exceptions` (referenced by nearly every project directly, including
all of `Shared.Contracts`, `Infrastructure.Jwt`, and each feature slice)
- `Infrastructure.Configuration` (the shared options-binding project
referenced by `Database.Connection`, `Infrastructure.Email`,
`Infrastructure.FileUpload`, and `Features.Emails` directly)
all of `Shared.Contracts` and each feature slice)
- `Configuration` (the shared options-binding project
referenced by `Database.Connection`, `Features.PhotoUpload`,
and `Features.Emails` directly)
- both are plumbing-level dependencies of nearly everything above, and drawing
them would just add a second copy of the same fan-in

View File

@@ -1,8 +1,6 @@
---
config:
flowchart:
curve: stepAfter
layout: elk
layout: elk
---
flowchart TB

View File

@@ -1,7 +1,6 @@
---
config:
flowchart: {}
layout: fixed
layout: elk
---
flowchart TB
@@ -24,20 +23,16 @@ end
subgraph INFRA["Slice-specific Infrastructure"]
direction LR
JWT["Infrastructure.Jwt"]
PwdHash["Infrastructure.PasswordHashing"]
FileUpload["Infrastructure.FileUpload"]
Email["Infrastructure.Email"]
EmailTemplates["Infrastructure.Email.Templates"]
end
UsersSlice == project ref, sends UploadPhotoCommand ==> PhotoSlice
UsersSlice -. sends email commands .-> SharedApp["Shared.Application<br>(email command contract)"]
EmailsSlice -. handles email commands .-> SharedApp
EmailsSlice == project ref, handles UserRegisteredNotification & ConfirmationEmailResendRequestedNotification ==> UsersSlice
BrewerySlice --> FOUNDATION
LocationsSlice --> FOUNDATION
BeersSlice --> FOUNDATION
PhotoSlice --> FOUNDATION & FileUpload
UsersSlice --> FOUNDATION & JWT & PwdHash
EmailsSlice --> Email & EmailTemplates
PhotoSlice --> FOUNDATION
UsersSlice --> FOUNDATION & PwdHash
EmailsSlice --> EmailTemplates
DBConn -- Dapper SQL, no ORM --> Tables[("SQL Server<br>Tables")]

View File

@@ -98,7 +98,7 @@ sqlserver # Test database
database.migrations # Fresh schema
database.seed # Test data
api.specs # Reqnroll BDD tests
unit.tests # All Features.*.Tests unit test projects
unit.tests # All Features.*.Tests and Shared.*.Tests unit test projects
frontend.tests # Storybook Vitest + Playwright suites (own Playwright image)
```
@@ -134,27 +134,136 @@ containers, which would end the run prematurely. See
- Production logging levels
- No database clearing
- Optimized build configurations
- Health checks enabled
- Restart policies (unless-stopped)
- Health checks on every long-running service
- Restart policies that survive a reboot (see
[Restart tolerance](#restart-tolerance))
- Security hardening
- Only `frontend` publishes a port to the host; `sqlserver` and `api.core` are
reachable only from other containers on `prodnet`
- Only `frontend` publishes a port to the host, bound to `127.0.0.1` so a reverse
proxy can sit in front of it; `sqlserver`, `api.core` and `seaweedfs` are
reachable only from other containers on `prodnet` (named `biergarten-prodnet`
so the seed job can join it from its own Compose project)
- Seeding is a separate, explicitly run compose file
(`docker-compose.prod.seed.yaml`), so an `up` or a restart leaves the existing
catalogue as it is. See [Production data](#production-data) below.
**Services**:
```yaml
sqlserver # Production SQL Server (internal only)
database.migrations # Schema updates only
sqlserver # Production SQL Server (internal only)
api.core # Production API (internal only, no published ports)
frontend # Production website (port 3000, the only public binding)
seaweedfs # S3-compatible object storage (internal only)
frontend # Production website (127.0.0.1:5656, the only host binding)
```
Migrating and seeding are run-once jobs kept outside this file, so an `up` or a
restart touches neither the schema nor the catalogue. Run them explicitly at
deploy time: see [Migrating production](#migrating-production) and
[Seeding production](#seeding-production-docker-composeprodseedyaml).
**Deploy Production**:
```bash
# One time, before the first `up`: the data volumes are external, so Compose
# expects them to exist already.
docker volume create biergartendata-prod
docker volume create seaweedfsdata-prod
docker compose --env-file web/.env.prod -f web/docker-compose.prod.yaml up -d
```
Docker seeds each volume with the ownership the image expects and labels it for
SELinux, so the host needs no `chown` and no `:z`/`:Z` mount options on
enforcing distributions such as RHEL, AlmaLinux and Fedora.
#### Migrating production
`database.migrations` is a run-once job rather than a service in the prod stack,
so the schema is migrated when an operator asks for it instead of on every boot.
Build the image and run it against the network the prod stack creates:
```bash
docker build -t database.migrations \
-f web/backend/Database/Database.Migrations/Dockerfile \
--build-arg BUILD_CONFIGURATION=Release --build-arg APP_UID=1000 \
web/backend
docker run --rm --env-file web/.env.prod --network biergarten-prodnet \
-e DOTNET_RUNNING_IN_CONTAINER=true database.migrations
```
DbUp records every script it has applied, so a re-run applies only what is new.
Run this with `sqlserver` already up and healthy, and before the seed job.
#### Restart tolerance
`sqlserver`, `api.core`, `seaweedfs` and `frontend` run under
`restart: unless-stopped`, so the stack returns on its own after a container
crash, a Docker daemon restart or a host reboot, provided Docker itself starts at
boot (`systemctl enable docker`). The migration and seed jobs stay out of the
stack, so a reboot replays neither.
The daemon replays restart policies without replaying the `depends_on` graph, so
after a reboot the containers come back in arbitrary order and each one tolerates
a dependency that arrives late. `api.core` opens its database and S3 connections
per request rather than at startup, and `frontend` answers with its own error
states while `api.core` is still coming up.
Health checks report when the stack has converged:
| Service | Probe |
| --- | --- |
| `sqlserver` | `sqlcmd -Q 'SELECT 1'`, with a 30s start period and 12 retries |
| `api.core` | `GET /health` spoken over bash's `/dev/tcp` — the .NET runtime image carries bash and no HTTP client |
| `seaweedfs` | `curl http://localhost:8333/status`, the S3 gateway, which serves once the master, volume and filer servers are up |
| `frontend` | `wget --spider http://127.0.0.1:5656/healthz`, answered by Express alone and so independent of the API |
`sqlserver` also carries `stop_grace_period: 60s`, giving a checkpoint time to
finish on shutdown instead of being recovered on the next start.
Deploy and wait for the stack to report healthy, or check convergence after a
reboot:
```bash
docker compose --env-file web/.env.prod -f web/docker-compose.prod.yaml up -d --wait
docker compose --env-file web/.env.prod -f web/docker-compose.prod.yaml ps
```
#### Seeding production (`docker-compose.prod.seed.yaml`)
`database.seed` lives in its own compose file, run on demand once the prod stack
is up, `sqlserver` is healthy, and the schema is migrated:
```bash
docker compose --env-file web/.env.prod -f web/docker-compose.prod.seed.yaml \
run --rm --build database.seed
```
The job runs as the `biergarten-prod-seed` Compose project and attaches to the
external `biergarten-prodnet` network, which the main prod stack creates, so it
reaches `sqlserver` and `seaweedfs` under the same hostnames the API uses. It
exits when seeding finishes; `--rm` removes the container. Bring the prod stack
up first, because the seed project has no visibility into the other project's
health checks, so a run started before SQL Server is accepting connections fails.
#### Production data
A production deployment seeded this way serves the AI-generated fixture data
produced by the pipeline. Per
[Pipeline ethics, bias, and known issues](../pipeline/ETHICS-AND-KNOWN-ISSUES.md),
anyone interacting with an application seeded from it has to be told upfront that
the content is AI-generated.
The website meets that obligation with `AiDisclosureDialog`
(`web/frontend/app/features/home/components/AiDisclosureDialog.tsx`), which
the root route renders on every full page load, whichever route the visitor lands
on. It is part of the server-rendered HTML rather than mounted after hydration, so
the disclosure is on screen with the first paint. Acknowledging it hides the
dialog for the remainder of that page load; a new load shows it again.
Keep the seed job and the dialog together: any deployment that runs
`docker-compose.prod.seed.yaml` needs the disclosure in place to satisfy the
ethics documentation.
### 4. Database only (`docker-compose.db.yaml`)
**Purpose**: Run just the database for local backend development outside Docker
@@ -215,6 +324,12 @@ graph TD
In development, `api.core` also depends on `seaweedfs`
(`condition: service_started`, not a health check) alongside `database.seed`.
Production has a shorter chain, because the migration and seed jobs run outside
the stack: `api.core` waits for `seaweedfs` to pass its health check, and
`frontend` waits for `api.core` to report healthy. This ordering applies to
`docker compose up`; see [Restart tolerance](#restart-tolerance) for what happens
on a host reboot.
**Health Check Example** (SQL Server):
```yaml
@@ -255,8 +370,10 @@ api.core:
**Production**:
- `sqlserverdata-prod` - Production database files
- `nuget-cache-prod` - Production NuGet cache
- `biergartendata-prod` - Database files, external; survives `down -v`
- `seaweedfsdata-prod` - SeaweedFS object storage, external; survives `down -v`
See [Production data volumes](#production-data-volumes).
### Mounted volumes
@@ -269,6 +386,41 @@ volumes:
Test results are written to host filesystem for CI/CD integration.
### Production data volumes
`biergartendata-prod` and `seaweedfsdata-prod` are declared `external: true`.
Compose removes only the volumes it owns, so `docker compose down -v` tears the
stack down and leaves the database and the uploaded photos in place. Deleting
them takes an explicit `docker volume rm`.
The trade-off is that Compose creates neither one, and `up` fails with a clear
error until both exist, hence the `docker volume create` step in
[Deploy Production](#3-production-docker-composeprodyaml). External volumes also
carry their literal name rather than a `<project>_` prefix, so `docker volume ls`
shows `biergartendata-prod` and `seaweedfsdata-prod` unprefixed, unlike the
`web_`-prefixed volumes of the dev and test stacks.
Both live under `/var/lib/docker/volumes`. To put them on a specific disk, point
the daemon's `data-root` at it in `/etc/docker/daemon.json`, or mount the disk at
`/var/lib/docker`.
Back up the database through SQL Server rather than by copying its files, since a
file copy taken while the engine is running can be torn:
```bash
docker exec prod-env-sqlserver /opt/mssql-tools18/bin/sqlcmd \
-S localhost -U sa -P '<db-password>' -C \
-Q "BACKUP DATABASE [<db-name>] TO DISK = '/var/opt/mssql/data/backup.bak'"
docker cp prod-env-sqlserver:/var/opt/mssql/data/backup.bak .
```
Object storage can be archived directly, with the stack stopped:
```bash
docker run --rm -v seaweedfsdata-prod:/data -v "$PWD:/backup" \
alpine tar czf /backup/seaweedfs.tar.gz -C /data .
```
## Networks
Each environment uses isolated bridge networks:

View File

@@ -233,7 +233,7 @@ file (`development` in dev, `production` in prod).
### SMTP configuration (backend)
Read by `Infrastructure.Email/SmtpEmailProvider.cs` for sending confirmation and
Read by `Features.Emails/Services/SmtpEmailProvider.cs` for sending confirmation and
account emails.
```bash
@@ -246,7 +246,7 @@ SMTP_FROM_EMAIL=noreply@thebiergarten.app # Required, no default
SMTP_FROM_NAME=The Biergarten App # Optional, defaults to "The Biergarten"
```
- **Implementation**: `Infrastructure.Email/SmtpEmailProvider.cs` throws on
- **Implementation**: `Features.Emails/Services/SmtpEmailProvider.cs` throws on
startup if `SMTP_HOST` or `SMTP_FROM_EMAIL` is missing
- **Local dev**: point at the `mailpit` Docker service (SMTP on port 1025, web
UI on http://localhost:8025)
@@ -255,22 +255,30 @@ SMTP_FROM_NAME=The Biergarten App # Optional, defaults to "The Biergarten
### File storage configuration (backend)
Read by `Infrastructure.FileUpload/S3FileStorageProvider.cs` for uploading and
retrieving photos via an S3-compatible object store.
Read by `Features.PhotoUpload/Services/S3FileStorageProvider.cs` for uploading
and retrieving photos via an S3-compatible object store.
```bash
SEAWEEDFS_SERVICE_URL=http://seaweedfs:8333 # Required, no default
SEAWEEDFS_PUBLIC_URL=http://localhost:8333 # Optional, defaults to SEAWEEDFS_SERVICE_URL
SEAWEEDFS_ACCESS_KEY_ID=admin # Required, no default
SEAWEEDFS_SECRET_ACCESS_KEY=secret # Required, no default
SEAWEEDFS_BUCKET=my-bucket # Required, no default
```
- **Implementation**: `S3FileStorageProvider` throws on construction if any of
these four values is missing
the four required values is missing
- **Local dev**: point at the `seaweedfs` Docker service (S3 API on port 8333)
- **Production**: point at any S3-compatible endpoint (AWS S3, a hosted
SeaweedFS cluster, and so on); `ForcePathStyle` is always enabled, which
SeaweedFS requires and AWS S3 also accepts
- **`SEAWEEDFS_PUBLIC_URL`**: the endpoint download URLs are signed against,
used by `GetPresignedUrl` and reaching the API response as
`PublicUserProfileDto.AvatarUrl`. A presigned URL is signed over its host, so
this has to be the address the browser uses (`http://localhost:8333` with the
dev compose file, which publishes the S3 API port), separate from the
in-network `SEAWEEDFS_SERVICE_URL` the API uploads through. The two can be the
same value wherever one address serves both
## Docker-specific variables
@@ -317,6 +325,7 @@ from the template in place; edit them manually if you go that route.
- `web/docker-compose.dev.yaml` → `web/.env.dev`
- `web/docker-compose.test.yaml` → `web/.env.test`
- `web/docker-compose.prod.yaml` → `web/.env.prod`
- `web/docker-compose.prod.seed.yaml` → `web/.env.prod`
## Variable reference table
@@ -340,6 +349,7 @@ from the template in place; edit them manually if you go that route.
| `SMTP_FROM_EMAIL` | ✓ | | ✓ | Yes | Email sender address |
| `SMTP_FROM_NAME` | ✓ | | ✓ | No | Defaults to `The Biergarten` |
| `SEAWEEDFS_SERVICE_URL` | ✓ | | ✓ | Yes | S3-compatible endpoint URL |
| `SEAWEEDFS_PUBLIC_URL` | ✓ | | ✓ | No | Endpoint download URLs are signed against; defaults to `SEAWEEDFS_SERVICE_URL` |
| `SEAWEEDFS_ACCESS_KEY_ID` | ✓ | | ✓ | Yes | S3 access key |
| `SEAWEEDFS_SECRET_ACCESS_KEY` | ✓ | | ✓ | Yes | S3 secret key |
| `SEAWEEDFS_BUCKET` | ✓ | | ✓ | Yes | S3 bucket name |
@@ -414,6 +424,7 @@ SMTP_FROM_NAME=The Biergarten App
# SeaweedFS (S3-compatible storage)
SEAWEEDFS_SERVICE_URL=http://seaweedfs:8333
SEAWEEDFS_PUBLIC_URL=http://localhost:8333
SEAWEEDFS_ACCESS_KEY_ID=<generated-with-openssl>
SEAWEEDFS_SECRET_ACCESS_KEY=<generated-with-openssl>
SEAWEEDFS_BUCKET=my-bucket

View File

@@ -76,10 +76,11 @@ docker compose --env-file web/.env.test -f web/docker-compose.test.yaml down -v
You can run individual test projects locally without Docker:
### Feature slice unit tests
### Feature slice and shared unit tests
Each feature slice has its own test project, covering its command/query
handlers:
handlers. Shared cross-cutting code (e.g. MediatR pipeline behaviors) has
its own test project under `Shared/`:
```bash
cd web/backend
@@ -87,9 +88,10 @@ dotnet test Features/Features.Users.Tests/Features.Users.Tests.csproj
dotnet test Features/Features.Breweries.Tests/Features.Breweries.Tests.csproj
dotnet test Features/Features.Emails.Tests/Features.Emails.Tests.csproj
dotnet test Features/Features.PhotoUpload.Tests/Features.PhotoUpload.Tests.csproj
dotnet test Shared/Shared.Application.Tests/Shared.Application.Tests.csproj
# Or run all of them at once via the solution:
for proj in Features/*.Tests; do dotnet test "$proj"; done
for proj in Features/*.Tests Shared/*.Tests; do dotnet test "$proj"; done
```
**Requirements**:
@@ -247,13 +249,16 @@ API.Specs/
│ ├── ResendConfirmation.feature # Resend-confirmation scenarios
│ ├── TokenRefresh.feature # Refresh token scenarios
│ ├── AccessTokenValidation.feature # Protected endpoint access scenarios
│ └── NotFound.feature # 404 handling
│ ├── NotFound.feature # 404 handling
│ └── PublicUserProfile.feature # Public profile & authenticated account scenarios
├── Steps/
│ ├── AuthSteps.cs # Step definitions for the Auth features
│ ├── UserSteps.cs # Step definitions for the public profile & user-account features
│ └── ApiGeneralSteps.cs # Shared/general step definitions
├── Mocks/
│ ├── MockEmailDispatcher.cs # Substitutes Features.Emails' IEmailDispatcher
│ └── MockEmailProvider.cs # Substitutes Infrastructure.Email's IEmailProvider
│ ├── MockEmailProvider.cs # Substitutes Features.Emails' IEmailProvider
│ └── MockFileStorageProvider.cs # Substitutes Features.ImageUploads' IFileStorageProvider
└── TestApiFactory.cs # Test server setup (swaps in the mocks above)
```
@@ -278,17 +283,25 @@ Scenario: Successful user registration
Features.Users.Tests/
├── Commands/
│ ├── RegisterUserHandlerTests.cs
│ ├── RegisterUserValidatorTests.cs
│ ├── ConfirmUserHandlerTests.cs
│ ├── ResendConfirmationEmailHandlerTests.cs
│ ├── RefreshTokenHandlerTests.cs
│ ├── RefreshTokenValidatorTests.cs
│ ├── LoginValidatorTests.cs # tests LoginCommand's validator
│ ├── UpdateUsernameHandlerTests.cs
│ ├── UpdateUsernameValidatorTests.cs
│ ├── UpdateEmailHandlerTests.cs
│ ├── UpdateEmailValidatorTests.cs
│ ├── UpdatePasswordHandlerTests.cs
│ ├── UpdatePasswordValidatorTests.cs
│ ├── UpdateProfileHandlerTests.cs
│ ├── UpdateProfileValidatorTests.cs
│ └── DeleteAccountHandlerTests.cs
├── Queries/
│ ├── LoginHandlerTests.cs # tests LoginCommand, despite the folder name
│ ├── GetAllUsersHandlerTests.cs
│ ├── GetPublicUserProfileByIdHandlerTests.cs
│ └── GetUserByIdHandlerTests.cs
├── Services/
│ ├── TokenServiceRefreshTests.cs
@@ -296,10 +309,13 @@ Features.Users.Tests/
└── TestSupport/ # shared test fixtures/helpers
```
Each of the other slices (`Features.Breweries.Tests`, `Features.Emails.Tests`,
`Features.PhotoUpload.Tests`) follows the same shape: a `Commands/`/`Queries/`
folder with one test file per handler (`Features.PhotoUpload.Tests` also adds a
validator test file alongside its handler test).
`Features.Breweries.Tests` and `Features.PhotoUpload.Tests` follow the same
shape: a `Commands/`/`Queries/` folder with one test file per handler, plus a
`*ValidatorTests.cs` file beside each handler whose command or query has a
FluentValidation validator (`Features.Breweries.Tests` has one of these in
`Queries/` as well, for the nearby-search query). `Features.Emails.Tests`
differs: its handlers respond to MediatR notifications, so its test files live
under `Notifications/`.
## Writing tests

View File

@@ -22,7 +22,7 @@ The Biergarten API validates JSON Web Tokens (JWTs) across three token types:
### Infrastructure layer
#### [ITokenInfrastructure](../../web/backend/Infrastructure/Infrastructure.Jwt/ITokenInfrastructure.cs)
#### [ITokenInfrastructure](../../web/backend/Features/Features.Users/Services/ITokenInfrastructure.cs)
Low-level JWT operations.
@@ -32,7 +32,7 @@ Low-level JWT operations.
- `ValidateJwtAsync()` - Validates token signature, expiration, and format
**Implementation:**
[JwtInfrastructure.cs](../../web/backend/Infrastructure/Infrastructure.Jwt/JwtInfrastructure.cs)
[JwtInfrastructure.cs](../../web/backend/Features/Features.Users/Services/JwtInfrastructure.cs)
- Uses Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler
- Algorithm: HS256 (HMAC-SHA256)
@@ -76,11 +76,11 @@ directly, bypassing the `Features.Users` slice entirely.
- Extracts and validates claims (Sub, UniqueName)
- Throws `UnauthorizedException` on validation failure
`TokenService` is registered by `Features.Users`' own `AddFeaturesUsers()`
extension method, except for the lower-level `ITokenInfrastructure` (JWT
signing/verification) it depends on, which is registered by the host
(`API.Core/Program.cs`) since `JwtAuthenticationHandler` (host-level auth
middleware) also depends on it directly.
`TokenService` and the lower-level `ITokenInfrastructure` (JWT
signing/verification) it depends on are both registered by `Features.Users`'
own `AddFeaturesUsers()` extension method. `JwtAuthenticationHandler`
(host-level auth middleware) also depends on `ITokenInfrastructure` directly,
resolving it from the same DI container.
### Integration points

View File

@@ -68,8 +68,12 @@ WEBSITE_BASE_URL=http://localhost:3000
# ======================
# SeaweedFS (S3) Configuration
# ======================
# Credentials and default bucket for the local SeaweedFS S3-compatible storage
# Credentials and default bucket for the local SeaweedFS S3-compatible storage.
# SEAWEEDFS_SERVICE_URL is the in-network endpoint the API uploads through;
# SEAWEEDFS_PUBLIC_URL is the endpoint download URLs are signed against, so it has to be
# reachable from the browser. It defaults to SEAWEEDFS_SERVICE_URL when left blank.
SEAWEEDFS_SERVICE_URL=http://seaweedfs:8333
SEAWEEDFS_PUBLIC_URL=http://localhost:8333
SEAWEEDFS_ACCESS_KEY_ID=admin
SEAWEEDFS_SECRET_ACCESS_KEY=secret
SEAWEEDFS_BUCKET=my-bucket

View File

@@ -7,24 +7,27 @@
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="API.Specs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.11" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
<PackageReference Include="MediatR" Version="12.4.1" />
<PackageReference Include="MediatR" Version="12.5.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Domain\Domain.Entities\Domain.Entities.csproj" />
<ProjectReference Include="..\..\Domain\Domain.Exceptions\Domain.Exceptions.csproj" />
<ProjectReference Include="..\..\Database\Database.Connection\Database.Connection.csproj" />
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Configuration\Infrastructure.Configuration.csproj" />
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Jwt\Infrastructure.Jwt.csproj" />
<ProjectReference Include="..\..\Infrastructure\Infrastructure.FileUpload\Infrastructure.FileUpload.csproj" />
<ProjectReference Include="..\..\Configuration\Configuration.csproj" />
<ProjectReference Include="..\..\Features\Features.Breweries\Features.Breweries.csproj" />
<ProjectReference Include="..\..\Features\Features.Users\Features.Users.csproj" />
<ProjectReference Include="..\..\Features\Features.Emails\Features.Emails.csproj" />
<ProjectReference Include="..\..\Features\Features.PhotoUpload\Features.PhotoUpload.csproj" />
<ProjectReference Include="..\..\Features\Features.Locations\Features.Locations.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Application\Shared.Application.csproj" />
</ItemGroup>

View File

@@ -1,7 +1,7 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using Infrastructure.Configuration;
using Infrastructure.Jwt;
using Features.Users.Services;
using Configuration;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
@@ -25,17 +25,13 @@ public class JwtAuthenticationHandler(
/// Validates the incoming request's bearer JWT access token and produces an authentication result.
/// </summary>
/// <remarks>
/// The signing secret is resolved first from the <c>ACCESS_TOKEN_SECRET</c> environment variable, falling
/// back to the <c>Jwt:SecretKey</c> configuration value, to stay consistent with the secret source used
/// when tokens are issued. Fails if the secret is not configured, the <c>Authorization</c> header is
/// The signing secret is resolved first from the <c>ACCESS_TOKEN_SECRET</c> environment variable.
/// Fails if the secret is not configured, the <c>Authorization</c> header is
/// missing or not <c>Bearer</c>-scheme, or the token fails validation.
/// </remarks>
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Use the same access-token secret source as TokenService to avoid mismatched validation.
string? secret = configuration[ConfigurationKeys.AccessTokenSecret];
if (string.IsNullOrWhiteSpace(secret))
secret = configuration[ConfigurationKeys.JwtSecretKeyFallback];
if (string.IsNullOrWhiteSpace(secret))
return AuthenticateResult.Fail("JWT secret is not configured");

View File

@@ -1,25 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace API.Core.Controllers;
/// <summary>
/// Handles requests that do not match any other route, used as the application's fallback controller.
/// </summary>
/// <remarks>
/// Wired up as the fallback target via <c>app.MapFallbackToController("Handle404", "NotFound")</c> in
/// <c>Program.cs</c>.
/// </remarks>
[ApiController]
[ApiExplorerSettings(IgnoreApi = true)]
[Route("error")]
public class NotFoundController : ControllerBase
{
/// <summary>
/// Returns a 404 response for any request that did not match a route.
/// </summary>
[HttpGet("404")]
public IActionResult Handle404()
{
return NotFound(new { message = "Route not found." });
}
}

View File

@@ -1,34 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Shared.Contracts;
using JwtRegisteredClaimNames = System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames;
namespace API.Core.Controllers;
/// <summary>
/// Sample controller demonstrating an endpoint that requires JWT authentication.
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = "JWT")]
public class ProtectedController : ControllerBase
{
/// <summary>
/// Returns the authenticated caller's user ID and username extracted from the JWT claims.
/// </summary>
/// <returns><c>userId</c> and <c>username</c> may be <c>null</c> if not present in the token.</returns>
[HttpGet]
public ActionResult<ResponseBody<object>> Get()
{
string? userId = User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value;
string? username = User.FindFirst(JwtRegisteredClaimNames.UniqueName)?.Value;
return Ok(
new ResponseBody<object>
{
Message = "Protected endpoint accessed successfully",
Payload = new { userId, username },
}
);
}
}

View File

@@ -25,6 +25,7 @@ COPY ["Domain/Domain.Exceptions/Domain.Exceptions.csproj", "Domain/Domain.Except
COPY ["Features/Features.Breweries/Features.Breweries.csproj", "Features/Features.Breweries/"]
COPY ["Features/Features.Breweries.Tests/Features.Breweries.Tests.csproj", "Features/Features.Breweries.Tests/"]
COPY ["Features/Features.Emails/Features.Emails.csproj", "Features/Features.Emails/"]
COPY ["Features/Features.Emails.Templates/Features.Emails.Templates.csproj", "Features/Features.Emails.Templates/"]
COPY ["Features/Features.Emails.Tests/Features.Emails.Tests.csproj", "Features/Features.Emails.Tests/"]
COPY ["Features/Features.Locations/Features.Locations.csproj", "Features/Features.Locations/"]
COPY ["Features/Features.Locations.Tests/Features.Locations.Tests.csproj", "Features/Features.Locations.Tests/"]
@@ -32,13 +33,9 @@ COPY ["Features/Features.PhotoUpload/Features.PhotoUpload.csproj", "Features/Fea
COPY ["Features/Features.PhotoUpload.Tests/Features.PhotoUpload.Tests.csproj", "Features/Features.PhotoUpload.Tests/"]
COPY ["Features/Features.Users/Features.Users.csproj", "Features/Features.Users/"]
COPY ["Features/Features.Users.Tests/Features.Users.Tests.csproj", "Features/Features.Users.Tests/"]
COPY ["Infrastructure/Infrastructure.Configuration/Infrastructure.Configuration.csproj", "Infrastructure/Infrastructure.Configuration/"]
COPY ["Infrastructure/Infrastructure.Email/Infrastructure.Email.csproj", "Infrastructure/Infrastructure.Email/"]
COPY ["Infrastructure/Infrastructure.Email.Templates/Infrastructure.Email.Templates.csproj", "Infrastructure/Infrastructure.Email.Templates/"]
COPY ["Infrastructure/Infrastructure.FileUpload/Infrastructure.FileUpload.csproj", "Infrastructure/Infrastructure.FileUpload/"]
COPY ["Infrastructure/Infrastructure.Jwt/Infrastructure.Jwt.csproj", "Infrastructure/Infrastructure.Jwt/"]
COPY ["Infrastructure/Infrastructure.PasswordHashing/Infrastructure.PasswordHashing.csproj", "Infrastructure/Infrastructure.PasswordHashing/"]
COPY ["Configuration/Configuration.csproj", "Configuration/"]
COPY ["Shared/Shared.Application/Shared.Application.csproj", "Shared/Shared.Application/"]
COPY ["Shared/Shared.Application.Tests/Shared.Application.Tests.csproj", "Shared/Shared.Application.Tests/"]
COPY ["Shared/Shared.Contracts/Shared.Contracts.csproj", "Shared/Shared.Contracts/"]
RUN dotnet restore "Biergarten.API.slnx"
COPY . .

View File

@@ -13,16 +13,16 @@ namespace API.Core;
/// </summary>
public class GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger) : IExceptionFilter
{
/// <summary>
/// Logs the exception and sets <see cref="ExceptionContext.Result" /> to an appropriate error response.
/// </summary>
/// <remarks>
/// Maps <see cref="ValidationException" /> to 400, <see cref="ConflictException" /> to 409,
/// <see cref="NotFoundException" /> to 404, <see cref="UnauthorizedException" /> to 401,
/// <see cref="ForbiddenException" /> to 403, <see cref="SqlException" /> to 503,
/// <see cref="Domain.Exceptions.ValidationException" /> to 400, and anything else to 500.
/// </remarks>
public void OnException(ExceptionContext context)
/// <summary>
/// Logs the exception and sets <see cref="ExceptionContext.Result" /> to an appropriate error response.
/// </summary>
/// <remarks>
/// Maps <see cref="ValidationException" /> to 400, <see cref="ConflictException" /> to 409,
/// <see cref="NotFoundException" /> to 404, <see cref="UnauthorizedException" /> to 401,
/// <see cref="ForbiddenException" /> to 403, <see cref="SqlException" /> to 503,
/// <see cref="Domain.Exceptions.ValidationException" /> to 400, and anything else to 500.
/// </remarks>
public void OnException(ExceptionContext context)
{
logger.LogError(context.Exception, "Unhandled exception occurred");

View File

@@ -1,132 +1,86 @@
using API.Core;
using API.Core.Authentication;
using Database.Connection.DependencyInjection;
using Features.Auth.Controllers;
using Features.Users.DependencyInjection;
using Features.Breweries.Controllers;
using Features.Breweries.DependencyInjection;
using Features.Emails.DependencyInjection;
using Features.Emails.Services;
using Features.ImageUploads.Commands.UploadPhoto;
using Features.ImageUploads.DependencyInjection;
using FluentValidation;
using FluentValidation.AspNetCore;
using Infrastructure.FileUpload;
using Infrastructure.Jwt;
using MediatR;
using Microsoft.OpenApi.Models;
using Shared.Application.Behaviors;
using System.Security.Claims;
using Shared.Contracts;
using JwtRegisteredClaimNames = System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
namespace API.Core;
// Add current controllers to the exception filter
builder
.Services.AddControllers(options => { options.Filters.Add<GlobalExceptionFilter>(); })
.AddApplicationPart(typeof(BreweryController).Assembly)
.AddApplicationPart(typeof(AuthController).Assembly);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
internal class Program
{
options.AddSecurityDefinition(
"Bearer",
new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "Enter a JWT access token.",
}
);
options.AddSecurityRequirement(
new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
public static void Main(string[] args)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders().AddConsole();
if (!builder.Environment.IsProduction())
builder.Logging.AddDebug();
builder
.Services.AddApiControllers()
.AddValidationAndMediatR()
.AddApplicationServices()
.AddFeatureModules()
.AddCoreInfrastructure()
.AddJwtAuthentication();
WebApplication app = builder.Build();
app.UseSwagger()
.UseSwaggerUI()
.UseHttpsRedirection()
.UseAuthentication()
.UseAuthorization();
app.MapOpenApi();
app.MapHealthChecks("/health");
app.MapControllers();
if (app.Environment.IsEnvironment("Testing"))
app.MapGet(
"/api/protected",
(ClaimsPrincipal user) =>
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer",
},
},
[]
},
}
);
});
builder.Services.AddOpenApi();
string? userId = user.FindFirst(JwtRegisteredClaimNames.Sub)?.Value;
string? username = user.FindFirst(JwtRegisteredClaimNames.UniqueName)?.Value;
builder.Services.AddValidatorsFromAssemblyContaining<Program>();
builder.Services.AddValidatorsFromAssembly(typeof(BreweryController).Assembly);
builder.Services.AddValidatorsFromAssembly(typeof(AuthController).Assembly);
builder.Services.AddValidatorsFromAssembly(typeof(UploadPhotoCommand).Assembly);
builder.Services.AddFluentValidationAutoValidation();
return Results.Ok(
new ResponseBody<object>
{
Message = "Protected endpoint accessed successfully",
Payload = new { userId, username },
}
);
}
).RequireAuthorization(policy => policy.AddAuthenticationSchemes("JWT").RequireAuthenticatedUser());
// Add MediatR.
// ValidationBehavior runs FluentValidation validators in the MediatR pipeline for command/query handlers.
builder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<Program>();
cfg.RegisterServicesFromAssembly(typeof(BreweryController).Assembly);
cfg.RegisterServicesFromAssembly(typeof(AuthController).Assembly);
cfg.RegisterServicesFromAssembly(typeof(UploadPhotoCommand).Assembly);
cfg.RegisterServicesFromAssembly(typeof(IEmailDispatcher).Assembly);
cfg.AddOpenBehavior(typeof(ValidationBehavior<,>));
});
// Easter egg, as per tradition with the previous versions of the Biergarten App.
app.Map(
"/teapot",
() =>
Results.Json(
new ResponseBody
{
Message =
"I'm a little teapot, short and stout. Here is my handle, here is my spout!",
},
statusCode: 418
)
)
.ExcludeFromDescription();
builder.Services.AddHealthChecks();
app.MapFallback(() =>
Results.NotFound(
new ResponseBody { Message = "Are you lost? That route does not exist." }
)
)
.ExcludeFromDescription();
// Configure logging for container output
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
if (!builder.Environment.IsProduction())
builder.Logging.AddDebug();
app.Services.GetRequiredService<IHostApplicationLifetime>()
.ApplicationStopping.Register(() =>
{
app.Logger.LogInformation("Application is shutting down gracefully...");
});
builder.Services.AddDatabaseConnection();
builder.Services.AddFeaturesBreweries();
builder.Services.AddFeaturesUsers();
builder.Services.AddFeaturesEmails();
builder.Services.AddFeaturesPhotoUpload();
// ITokenInfrastructure is registered here because JwtAuthenticationHandler depends on it directly.
builder.Services.AddScoped<ITokenInfrastructure, JwtInfrastructure>();
builder.Services.AddSingleton<IFileStorageProvider, S3FileStorageProvider>();
builder.Services.AddScoped<GlobalExceptionFilter>();
builder
.Services.AddAuthentication("JWT")
.AddScheme<JwtAuthenticationOptions, JwtAuthenticationHandler>("JWT", options => { });
builder.Services.AddAuthorization();
WebApplication app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.MapOpenApi();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapHealthChecks("/health");
app.MapControllers();
app.MapFallbackToController("Handle404", "NotFound");
IHostApplicationLifetime lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
lifetime.ApplicationStopping.Register(() =>
{
app.Logger.LogInformation("Application is shutting down gracefully...");
});
app.Run();
app.Run();
}
}

View File

@@ -0,0 +1,121 @@
using API.Core.Authentication;
using Database.Connection.DependencyInjection;
using Features.Breweries.Controllers;
using Features.Breweries.DependencyInjection;
using Features.Emails.DependencyInjection;
using Features.Emails.Services;
using Features.ImageUploads.Commands.UploadPhoto;
using Features.ImageUploads.DependencyInjection;
using Features.Locations.Controllers;
using Features.Locations.DependencyInjection;
using Features.Users.Controllers;
using Features.Users.DependencyInjection;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.OpenApi.Models;
using Shared.Application.Behaviors;
namespace API.Core;
internal static class ServiceCollectionExtensions
{
extension(IServiceCollection services)
{
public IServiceCollection AddApiControllers() =>
services
.AddControllers(options => options.Filters.Add<GlobalExceptionFilter>())
.AddApplicationPart(typeof(BreweryController).Assembly)
.AddApplicationPart(typeof(AuthController).Assembly)
.AddApplicationPart(typeof(CityController).Assembly)
.Services;
public IServiceCollection AddValidationAndMediatR()
{
services
.AddOpenApi()
.AddValidatorsFromAssemblyContaining<Program>()
.AddValidatorsFromAssembly(typeof(BreweryController).Assembly)
.AddValidatorsFromAssembly(typeof(AuthController).Assembly)
.AddValidatorsFromAssembly(typeof(UploadPhotoCommand).Assembly)
.AddFluentValidationAutoValidation()
.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<Program>();
cfg.RegisterServicesFromAssembly(typeof(BreweryController).Assembly);
cfg.RegisterServicesFromAssembly(typeof(AuthController).Assembly);
cfg.RegisterServicesFromAssembly(typeof(UploadPhotoCommand).Assembly);
cfg.RegisterServicesFromAssembly(typeof(IEmailDispatcher).Assembly);
cfg.RegisterServicesFromAssembly(typeof(CityController).Assembly);
cfg.AddOpenBehavior(typeof(UnhandledExceptionLoggingBehavior<,>));
cfg.AddOpenBehavior(typeof(ValidationBehavior<,>));
});
return services;
}
public IServiceCollection AddApplicationServices()
{
services
.AddEndpointsApiExplorer()
.AddSwaggerGen(options =>
{
options.AddSecurityDefinition(
"Bearer",
new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "Enter a JWT access token.",
}
);
options.AddSecurityRequirement(
new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer",
},
},
[]
},
}
);
});
services.AddHealthChecks();
return services;
}
public IServiceCollection AddFeatureModules() =>
services
.AddDatabaseConnection()
.AddFeaturesBreweries()
.AddFeaturesUsers()
.AddFeaturesEmails()
.AddFeaturesPhotoUpload()
.AddFeaturesLocations();
public IServiceCollection AddCoreInfrastructure() =>
services.AddScoped<GlobalExceptionFilter>();
public IServiceCollection AddJwtAuthentication()
{
services
.AddAuthentication("JWT")
.AddScheme<JwtAuthenticationOptions, JwtAuthenticationHandler>(
"JWT",
options => { }
);
services.AddAuthorization();
return services;
}
}
}

View File

@@ -38,8 +38,7 @@
<ItemGroup>
<ProjectReference Include="..\API.Core\API.Core.csproj" />
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Configuration\Infrastructure.Configuration.csproj" />
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Email\Infrastructure.Email.csproj" />
<ProjectReference Include="..\..\Configuration\Configuration.csproj" />
<ProjectReference Include="..\..\Features\Features.Emails\Features.Emails.csproj" />
<ProjectReference Include="..\..\Features\Features.Locations\Features.Locations.csproj" />
<ProjectReference Include="..\..\Database\Database.Connection\Database.Connection.csproj" />

View File

@@ -15,6 +15,7 @@ COPY ["Domain/Domain.Exceptions/Domain.Exceptions.csproj", "Domain/Domain.Except
COPY ["Features/Features.Breweries/Features.Breweries.csproj", "Features/Features.Breweries/"]
COPY ["Features/Features.Breweries.Tests/Features.Breweries.Tests.csproj", "Features/Features.Breweries.Tests/"]
COPY ["Features/Features.Emails/Features.Emails.csproj", "Features/Features.Emails/"]
COPY ["Features/Features.Emails.Templates/Features.Emails.Templates.csproj", "Features/Features.Emails.Templates/"]
COPY ["Features/Features.Emails.Tests/Features.Emails.Tests.csproj", "Features/Features.Emails.Tests/"]
COPY ["Features/Features.Locations/Features.Locations.csproj", "Features/Features.Locations/"]
COPY ["Features/Features.Locations.Tests/Features.Locations.Tests.csproj", "Features/Features.Locations.Tests/"]
@@ -22,13 +23,9 @@ COPY ["Features/Features.PhotoUpload/Features.PhotoUpload.csproj", "Features/Fea
COPY ["Features/Features.PhotoUpload.Tests/Features.PhotoUpload.Tests.csproj", "Features/Features.PhotoUpload.Tests/"]
COPY ["Features/Features.Users/Features.Users.csproj", "Features/Features.Users/"]
COPY ["Features/Features.Users.Tests/Features.Users.Tests.csproj", "Features/Features.Users.Tests/"]
COPY ["Infrastructure/Infrastructure.Configuration/Infrastructure.Configuration.csproj", "Infrastructure/Infrastructure.Configuration/"]
COPY ["Infrastructure/Infrastructure.Email/Infrastructure.Email.csproj", "Infrastructure/Infrastructure.Email/"]
COPY ["Infrastructure/Infrastructure.Email.Templates/Infrastructure.Email.Templates.csproj", "Infrastructure/Infrastructure.Email.Templates/"]
COPY ["Infrastructure/Infrastructure.FileUpload/Infrastructure.FileUpload.csproj", "Infrastructure/Infrastructure.FileUpload/"]
COPY ["Infrastructure/Infrastructure.Jwt/Infrastructure.Jwt.csproj", "Infrastructure/Infrastructure.Jwt/"]
COPY ["Infrastructure/Infrastructure.PasswordHashing/Infrastructure.PasswordHashing.csproj", "Infrastructure/Infrastructure.PasswordHashing/"]
COPY ["Configuration/Configuration.csproj", "Configuration/"]
COPY ["Shared/Shared.Application/Shared.Application.csproj", "Shared/Shared.Application/"]
COPY ["Shared/Shared.Application.Tests/Shared.Application.Tests.csproj", "Shared/Shared.Application.Tests/"]
COPY ["Shared/Shared.Contracts/Shared.Contracts.csproj", "Shared/Shared.Contracts/"]
RUN dotnet restore "Biergarten.API.slnx"
COPY . .

View File

@@ -7,4 +7,4 @@ Scenario: GET request to an invalid route returns 404
Given the API is running
When I send an HTTP request "GET" to "/invalid-route"
Then the response has HTTP status 404
And the response JSON should have "message" equal "Route not found."
And the response JSON should have "message" equal "Are you lost? That route does not exist."

View File

@@ -0,0 +1,130 @@
Feature: Public User Profile
As a client of the API
I want to read a user's public-facing profile
So that a public profile page can render without exposing private account fields
Background:
Given the API is running
Scenario: Public profile exposes only allowlisted fields
Given I have registered a new account
And I have a valid access token for my account
When I retrieve the public profile by ID
Then the response has HTTP status 200
And the public profile response should match the registered account
And the response JSON should have "biography" equal ""
And the response JSON should have "avatarUrl" equal ""
And the response JSON should not contain "email"
And the response JSON should not contain "dateOfBirth"
Scenario: Public profile exposes the uploaded avatar
Given I have registered a new account
And I have a valid access token for my account
And I have uploaded an avatar
When I retrieve the public profile by ID
Then the response has HTTP status 200
And the public profile response should carry my current avatar
Scenario: Public profile exposes the current avatar after it is replaced
Given I have registered a new account
And I have a valid access token for my account
And I have uploaded an avatar
And I have uploaded a new avatar, replacing the previous one
When I retrieve the public profile by ID
Then the response has HTTP status 200
And the public profile response should carry my current avatar
And the public profile response should not carry my previous avatar
Scenario: Fetching the avatar without authentication succeeds
Given I have registered a new account
And I have a valid access token for my account
And I have uploaded an avatar
When I retrieve the public profile by ID without authentication
Then the response has HTTP status 200
And the public profile response should carry my current avatar
Scenario: A different user can read someone else's avatar
Given I have registered a new account
And I have a valid access token for my account
And I have uploaded an avatar
And I am logged in as a different user
When I retrieve the public profile by ID
Then the response has HTTP status 200
And the public profile response should carry my current avatar
Scenario: Listing user accounts exposes each account's avatar
Given I have registered a new account
And I have a valid access token for my account
And I have uploaded an avatar
When I list user accounts
Then the response has HTTP status 200
And my listed account should carry my current avatar
Scenario: Listing user accounts exposes each account's biography
Given I have registered a new account
And I have a valid access token for my account
And I have set my biography to "Drinks lagers."
When I list user accounts
Then the response has HTTP status 200
And my listed account should carry my biography
Scenario: Public profile for a non-existent account returns not found
Given I have registered a new account
And I have a valid access token for my account
When I retrieve the public profile by a non-existent ID
Then the response has HTTP status 404
Scenario: Fetching the public profile without authentication succeeds
Given I have registered a new account
When I retrieve the public profile by ID without authentication
Then the response has HTTP status 200
And the response JSON should have "avatarUrl" equal ""
And the response JSON should not contain "email"
And the response JSON should not contain "dateOfBirth"
Scenario: A different user can read someone else's public profile
Given I have registered a new account
And I am logged in as a different user
When I retrieve the public profile by ID
Then the response has HTTP status 200
And the response JSON should not contain "email"
And the response JSON should not contain "dateOfBirth"
Scenario: Fetching my own account without authentication is rejected
When I retrieve my own account without authentication
Then the response has HTTP status 401
Scenario: Listing user accounts without authentication is rejected
When I list user accounts without authentication
Then the response has HTTP status 401
Scenario: Listing user accounts as an authenticated user excludes private fields
Given I have registered a new account
And I have a valid access token for my account
When I list user accounts
Then the response has HTTP status 200
And the response JSON should contain "avatarUrl"
And the response JSON should not contain "email"
And the response JSON should not contain "dateOfBirth"
Scenario: The caller can fetch their own account
Given I have registered a new account
And I have a valid access token for my account
When I retrieve my own account
Then the response has HTTP status 200
And the public profile response should match the registered account
Scenario: The caller's own account omits the avatar graph
Given I have registered a new account
And I have a valid access token for my account
And I have uploaded an avatar
When I retrieve my own account
Then the response has HTTP status 200
And the response JSON should not contain "userAvatar"
Scenario: The account endpoint serves the caller named by the access token
Given I have registered a new account
And I am logged in as a different user
When I retrieve my own account
Then the response has HTTP status 200
And the account response should be for a different account than the registered one

View File

@@ -1,4 +1,4 @@
using Infrastructure.Email;
using Features.Emails.Services;
namespace API.Specs.Mocks;

View File

@@ -0,0 +1,55 @@
using Features.ImageUploads.Services;
namespace API.Specs.Mocks;
/// <summary>
/// Test double for <see cref="IFileStorageProvider" /> that records uploads in memory, so specs can
/// exercise photo-backed features without object storage.
/// </summary>
public class MockFileStorageProvider : IFileStorageProvider
{
private readonly List<string> _keys = [];
private readonly Dictionary<string, byte[]> _objects = new();
public IReadOnlyCollection<string> UploadedKeys => _keys.ToList();
/// <summary>The key of the most recent upload.</summary>
/// <exception cref="InvalidOperationException">Thrown when nothing has been uploaded yet.</exception>
public string LastUploadedKey =>
_keys.Count > 0
? _keys[^1]
: throw new InvalidOperationException("no file has been uploaded");
public Task UploadAsync(
string key,
Stream content,
string contentType,
CancellationToken cancellationToken = default
)
{
using MemoryStream buffer = new();
content.CopyTo(buffer);
if (!_objects.ContainsKey(key))
_keys.Add(key);
_objects[key] = buffer.ToArray();
return Task.CompletedTask;
}
public Task DeleteAsync(string key, CancellationToken cancellationToken = default)
{
_objects.Remove(key);
_keys.Remove(key);
return Task.CompletedTask;
}
/// <summary>
/// Stands in for a signed download URL: an absolute URL on a host the object store would serve,
/// carrying the key in its path, so specs can assert the shape callers actually receive.
/// </summary>
public string GetPresignedUrl(string key, TimeSpan expiresIn)
{
return $"https://storage.test/{key}?X-Amz-Expires={(int)expiresIn.TotalSeconds}";
}
}

View File

@@ -167,4 +167,86 @@ public class ApiGeneralSteps(ScenarioContext scenario)
actualValue
);
}
[Then("the response JSON should not contain {string}")]
public void ThenTheResponseJsonShouldNotContainString(string field)
{
scenario.TryGetValue<string>(ResponseBodyKey, out string? responseBody).Should().BeTrue();
using JsonDocument doc = JsonDocument.Parse(responseBody!);
JsonElement root = doc.RootElement;
AssertFieldAbsent(root, field);
if (root.ValueKind == JsonValueKind.Object &&
root.TryGetProperty("payload", out JsonElement payloadElem))
AssertFieldAbsent(payloadElem, field);
}
[Then("the response JSON should contain {string}")]
public void ThenTheResponseJsonShouldContainString(string field)
{
scenario.TryGetValue<string>(ResponseBodyKey, out string? responseBody).Should().BeTrue();
using JsonDocument doc = JsonDocument.Parse(responseBody!);
JsonElement root = doc.RootElement;
if (root.ValueKind == JsonValueKind.Object &&
!root.TryGetProperty(field, out _) &&
root.TryGetProperty("payload", out JsonElement payloadElem))
{
AssertFieldPresent(payloadElem, field);
return;
}
AssertFieldPresent(root, field);
}
/// <summary>
/// Recurses into arrays so a listing endpoint's response can be asserted the same way as a
/// single-resource response.
/// </summary>
private static void AssertFieldAbsent(JsonElement element, string field)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
element
.TryGetProperty(field, out _)
.Should()
.BeFalse("Expected field '{0}' to be absent from the response", field);
break;
case JsonValueKind.Array:
foreach (JsonElement item in element.EnumerateArray())
AssertFieldAbsent(item, field);
break;
}
}
/// <summary>
/// Recurses into arrays so every item of a listing endpoint's response must carry the field.
/// </summary>
private static void AssertFieldPresent(JsonElement element, string field)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
element
.TryGetProperty(field, out _)
.Should()
.BeTrue("Expected field '{0}' to be present in the response", field);
break;
case JsonValueKind.Array:
element
.EnumerateArray()
.Should()
.NotBeEmpty(
"Expected at least one item to assert field '{0}' against",
field
);
foreach (JsonElement item in element.EnumerateArray())
AssertFieldPresent(item, field);
break;
}
}
}

View File

@@ -15,7 +15,7 @@ public abstract class ApiStepsBase(ScenarioContext scenario)
protected const string ResponseKey = "response";
protected const string ResponseBodyKey = "responseBody";
protected TestApiFactory GetFactory()
internal TestApiFactory GetFactory()
{
TestApiFactory? factory = Scenario.TryGetValue<TestApiFactory>(
FactoryKey,

View File

@@ -1,8 +1,8 @@
using System.Text;
using System.Text.Json;
using Features.Users.Services;
using FluentAssertions;
using Infrastructure.Configuration;
using Infrastructure.Jwt;
using Configuration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Reqnroll;
@@ -347,6 +347,46 @@ public class AuthSteps(ScenarioContext scenario) : ApiStepsBase(scenario)
Scenario[RegisteredUsernameKey] = ParseRegisteredUsername(root);
}
[Given("I am logged in as a different user")]
public async Task GivenIAmLoggedInAsADifferentUser()
{
HttpClient client = GetClient();
string suffix = Guid.NewGuid().ToString("N")[..8];
var registrationData = new
{
username = $"otheruser-{suffix}",
firstName = "Other",
lastName = "User",
email = $"otheruser-{suffix}@example.com",
dateOfBirth = "1990-01-01",
password = "Password1!",
};
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/register")
{
Content = new StringContent(
JsonSerializer.Serialize(registrationData),
Encoding.UTF8,
"application/json"
),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
using JsonDocument doc = JsonDocument.Parse(responseBody);
JsonElement payload = doc.RootElement.GetProperty("payload");
string accessToken =
(
payload.TryGetProperty("accessToken", out JsonElement tokenElem)
? tokenElem.GetString()
: null
) ?? throw new InvalidOperationException("accessToken missing from registration payload");
Scenario["accessToken"] = accessToken;
}
[Given("I am logged in")]
public async Task GivenIAmLoggedIn()
{

View File

@@ -1,7 +1,6 @@
using System.Text;
using System.Text.Json;
using Database.Connection;
using Features.Locations.Dtos;
using Features.Locations.Repository;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
@@ -23,11 +22,6 @@ public class BrewerySteps(ScenarioContext scenario) : ApiStepsBase(scenario)
private const string FixtureStateProvinceIsoCode = "FX-TS";
private const string FixtureCityName = "Fixture City";
// GetOrCreateCityIdAsync is not fully race-safe under concurrent callers creating the same
// city (see its remarks); scenarios run in parallel across feature classes, so provisioning
// the shared fixture city is serialized the same way AuthSteps serializes its fixture account.
private static readonly SemaphoreSlim CityProvisioningLock = new(1, 1);
private HttpRequestMessage NewAuthenticatedRequest(HttpMethod method, string url)
{
HttpRequestMessage requestMessage = new(method, url);
@@ -53,24 +47,21 @@ public class BrewerySteps(ScenarioContext scenario) : ApiStepsBase(scenario)
.Services.GetRequiredService<ISqlConnectionFactory>();
LocationRepository repository = new(connectionFactory);
CityLocation fixtureCity = new(
FixtureCityName,
FixtureStateProvinceName,
FixtureStateProvinceIsoCode,
FixtureCountryName,
FixtureCountryIsoCode
);
Guid countryId =
await repository.GetCountryIdAsync(FixtureCountryIsoCode)
?? await repository.CreateCountryAsync(FixtureCountryName, FixtureCountryIsoCode);
await CityProvisioningLock.WaitAsync();
Guid cityId;
try
{
cityId = await repository.GetOrCreateCityIdAsync(fixtureCity);
}
finally
{
CityProvisioningLock.Release();
}
Guid stateProvinceId =
await repository.GetStateProvinceIdAsync(FixtureStateProvinceIsoCode)
?? await repository.CreateStateProvinceAsync(
FixtureStateProvinceName,
FixtureStateProvinceIsoCode,
countryId
);
Guid cityId =
await repository.GetCityIdAsync(FixtureCityName, FixtureStateProvinceIsoCode)
?? await repository.CreateCityAsync(FixtureCityName, stateProvinceId);
Scenario[CityIdKey] = cityId;
}
@@ -271,46 +262,6 @@ public class BrewerySteps(ScenarioContext scenario) : ApiStepsBase(scenario)
await SendAsync(requestMessage);
}
[Given("I am logged in as a different user")]
public async Task GivenIAmLoggedInAsADifferentUser()
{
HttpClient client = GetClient();
string suffix = Guid.NewGuid().ToString("N")[..8];
var registrationData = new
{
username = $"otheruser-{suffix}",
firstName = "Other",
lastName = "User",
email = $"otheruser-{suffix}@example.com",
dateOfBirth = "1990-01-01",
password = "Password1!",
};
HttpRequestMessage requestMessage = new(HttpMethod.Post, "/api/auth/register")
{
Content = new StringContent(
JsonSerializer.Serialize(registrationData),
Encoding.UTF8,
"application/json"
),
};
HttpResponseMessage response = await client.SendAsync(requestMessage);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
using JsonDocument doc = JsonDocument.Parse(responseBody);
JsonElement payload = doc.RootElement.GetProperty("payload");
string accessToken =
(
payload.TryGetProperty("accessToken", out JsonElement tokenElem)
? tokenElem.GetString()
: null
) ?? throw new InvalidOperationException("accessToken missing from registration payload");
Scenario[AccessTokenKey] = accessToken;
}
[Then("retrieving the brewery by ID should now return HTTP status {int}")]
public async Task ThenRetrievingTheBreweryByIdShouldNowReturnHttpStatus(int expectedCode)
{

View File

@@ -0,0 +1,290 @@
using System.Text.Json;
using API.Specs.Mocks;
using Features.ImageUploads.Services;
using Features.Users.Commands.Profile.UploadAvatar;
using Features.Users.Repository;
using FluentAssertions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Reqnroll;
namespace API.Specs.Steps;
[Binding]
public class UserSteps(ScenarioContext scenario) : ApiStepsBase(scenario)
{
private const string AccessTokenKey = "accessToken";
private const string RegisteredUserIdKey = "registeredUserId";
private const string RegisteredUsernameKey = "registeredUsername";
private const string CurrentAvatarKeyKey = "currentAvatarKey";
private const string PreviousAvatarKeyKey = "previousAvatarKey";
private const string BiographyKey = "biography";
private static readonly byte[] PngSignature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
private async Task SendAsync(HttpRequestMessage requestMessage)
{
HttpClient client = GetClient();
HttpResponseMessage response = await client.SendAsync(requestMessage);
string responseBody = await response.Content.ReadAsStringAsync();
Scenario[ResponseKey] = response;
Scenario[ResponseBodyKey] = responseBody;
}
private HttpRequestMessage NewAuthenticatedRequest(HttpMethod method, string url)
{
HttpRequestMessage requestMessage = new(method, url);
if (Scenario.TryGetValue<string>(AccessTokenKey, out string? accessToken))
requestMessage.Headers.Add("Authorization", $"Bearer {accessToken}");
return requestMessage;
}
private Guid GetRegisteredUserId()
{
return Scenario.TryGetValue(RegisteredUserIdKey, out Guid id)
? id
: throw new InvalidOperationException("registered user ID not found in scenario");
}
/// <summary>
/// Builds the smallest upload the photo validator accepts: a PNG signature padded out to the
/// 1 KiB minimum.
/// </summary>
private static IFormFile CreateAvatarFile()
{
byte[] content = new byte[2048];
PngSignature.CopyTo(content, 0);
MemoryStream stream = new(content);
return new FormFile(stream, 0, content.Length, "file", "avatar.png")
{
Headers = new HeaderDictionary { ["Content-Type"] = "image/png" },
};
}
/// <summary>
/// Uploads an avatar and records the object key the storage provider actually received, rather
/// than re-deriving the key template the handler uses.
/// </summary>
private async Task UploadAvatarAsync()
{
Guid userId = GetRegisteredUserId();
using IServiceScope scope = GetFactory().Services.CreateScope();
IMediator mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
await mediator.Send(new UploadAvatarCommand(userId, CreateAvatarFile()));
if (Scenario.TryGetValue<string>(CurrentAvatarKeyKey, out string? existing))
Scenario[PreviousAvatarKeyKey] = existing;
Scenario[CurrentAvatarKeyKey] = GetStorageProvider().LastUploadedKey;
}
private MockFileStorageProvider GetStorageProvider()
{
return (MockFileStorageProvider)
GetFactory().Services.GetRequiredService<IFileStorageProvider>();
}
private string GetCurrentAvatarKey()
{
return Scenario.TryGetValue(CurrentAvatarKeyKey, out string? key) && key is not null
? key
: throw new InvalidOperationException("no avatar has been uploaded in this scenario");
}
private string GetPreviousAvatarKey()
{
return Scenario.TryGetValue(PreviousAvatarKeyKey, out string? key) && key is not null
? key
: throw new InvalidOperationException(
"only one avatar has been uploaded in this scenario"
);
}
/// <summary>
/// Asserts that <paramref name="avatarUrl" /> is something a browser can fetch -- an absolute
/// HTTP(S) URL -- pointing at the object stored under <paramref name="expectedKey" />. A bare
/// storage key would resolve against the page's own origin, so the shape is the contract here,
/// not just the value.
/// </summary>
private static Uri AssertFetchableUrl(string? avatarUrl, string expectedKey)
{
avatarUrl.Should().NotBeNullOrWhiteSpace();
Uri.TryCreate(avatarUrl, UriKind.Absolute, out Uri? uri)
.Should()
.BeTrue("avatarUrl must be an absolute URL, but was '{0}'", avatarUrl);
uri!.Scheme.Should().BeOneOf("http", "https");
uri.AbsolutePath.Should().EndWith(expectedKey, "the URL must address the uploaded object");
return uri;
}
private string GetAvatarUrlFromResponse()
{
Scenario.TryGetValue<string>(ResponseBodyKey, out string? responseBody).Should().BeTrue();
using JsonDocument doc = JsonDocument.Parse(responseBody!);
return doc.RootElement.GetProperty("avatarUrl").GetString()!;
}
[Given("I have uploaded an avatar")]
public async Task GivenIHaveUploadedAnAvatar()
{
await UploadAvatarAsync();
}
[Given("I have uploaded a new avatar, replacing the previous one")]
public async Task GivenIHaveUploadedANewAvatarReplacingThePreviousOne()
{
await UploadAvatarAsync();
}
/// <summary>
/// Writes the biography straight through the repository: registration creates the profile row
/// with an empty biography, and no endpoint edits it yet.
/// </summary>
[Given("I have set my biography to {string}")]
public async Task GivenIHaveSetMyBiographyTo(string biography)
{
using IServiceScope scope = GetFactory().Services.CreateScope();
IUserProfileRepository profiles =
scope.ServiceProvider.GetRequiredService<IUserProfileRepository>();
await profiles.UpdateBiographyAsync(
GetRegisteredUserId(),
biography,
CancellationToken.None
);
Scenario[BiographyKey] = biography;
}
[Then("the public profile response should carry my current avatar")]
public void ThenThePublicProfileResponseShouldCarryMyCurrentAvatar()
{
AssertFetchableUrl(GetAvatarUrlFromResponse(), GetCurrentAvatarKey());
}
[Then("the public profile response should not carry my previous avatar")]
public void ThenThePublicProfileResponseShouldNotCarryMyPreviousAvatar()
{
Uri uri = AssertFetchableUrl(GetAvatarUrlFromResponse(), GetCurrentAvatarKey());
uri.AbsolutePath.Should().NotContain(GetPreviousAvatarKey());
}
[Then("my listed account should carry my current avatar")]
public void ThenMyListedAccountShouldCarryMyCurrentAvatar()
{
AssertFetchableUrl(
GetMyListedAccount().GetProperty("avatarUrl").GetString(),
GetCurrentAvatarKey()
);
}
[Then("my listed account should carry my biography")]
public void ThenMyListedAccountShouldCarryMyBiography()
{
string expected =
Scenario.TryGetValue(BiographyKey, out string? biography) && biography is not null
? biography
: throw new InvalidOperationException("no biography was set in this scenario");
GetMyListedAccount().GetProperty("biography").GetString().Should().Be(expected);
}
/// <summary>Finds the registered account in a listing response.</summary>
private JsonElement GetMyListedAccount()
{
Scenario.TryGetValue<string>(ResponseBodyKey, out string? responseBody).Should().BeTrue();
using JsonDocument doc = JsonDocument.Parse(responseBody!);
doc.RootElement.ValueKind.Should().Be(JsonValueKind.Array);
return doc
.RootElement.EnumerateArray()
.Should()
.ContainSingle(item =>
item.GetProperty("userAccountId").GetGuid() == GetRegisteredUserId()
)
.Subject.Clone();
}
[When("I retrieve the public profile by ID")]
public async Task WhenIRetrieveThePublicProfileById()
{
await SendAsync(
NewAuthenticatedRequest(HttpMethod.Get, $"/api/user/{GetRegisteredUserId()}/profile")
);
}
[When("I retrieve the public profile by ID without authentication")]
public async Task WhenIRetrieveThePublicProfileByIdWithoutAuthentication()
{
await SendAsync(
new HttpRequestMessage(HttpMethod.Get, $"/api/user/{GetRegisteredUserId()}/profile")
);
}
[When("I retrieve the public profile by a non-existent ID")]
public async Task WhenIRetrieveThePublicProfileByANonExistentId()
{
await SendAsync(
NewAuthenticatedRequest(HttpMethod.Get, $"/api/user/{Guid.NewGuid()}/profile")
);
}
[When("I retrieve my own account without authentication")]
public async Task WhenIRetrieveMyOwnAccountWithoutAuthentication()
{
await SendAsync(new HttpRequestMessage(HttpMethod.Get, "/api/user/authenticated"));
}
[When("I list user accounts without authentication")]
public async Task WhenIListUserAccountsWithoutAuthentication()
{
await SendAsync(new HttpRequestMessage(HttpMethod.Get, "/api/user"));
}
[When("I list user accounts")]
public async Task WhenIListUserAccounts()
{
await SendAsync(NewAuthenticatedRequest(HttpMethod.Get, "/api/user"));
}
[When("I retrieve my own account")]
public async Task WhenIRetrieveMyOwnAccount()
{
await SendAsync(NewAuthenticatedRequest(HttpMethod.Get, "/api/user/authenticated"));
}
[Then("the public profile response should match the registered account")]
public void ThenThePublicProfileResponseShouldMatchTheRegisteredAccount()
{
Scenario.TryGetValue<string>(ResponseBodyKey, out string? responseBody).Should().BeTrue();
string? username = Scenario.TryGetValue<string>(RegisteredUsernameKey, out string? u)
? u
: throw new InvalidOperationException("registered username not found in scenario");
using JsonDocument doc = JsonDocument.Parse(responseBody!);
JsonElement root = doc.RootElement;
root.GetProperty("userAccountId").GetGuid().Should().Be(GetRegisteredUserId());
root.GetProperty("username").GetString().Should().Be(username);
}
[Then("the account response should be for a different account than the registered one")]
public void ThenTheAccountResponseShouldBeForADifferentAccountThanTheRegisteredOne()
{
Scenario.TryGetValue<string>(ResponseBodyKey, out string? responseBody).Should().BeTrue();
using JsonDocument doc = JsonDocument.Parse(responseBody!);
doc.RootElement.GetProperty("userAccountId")
.GetGuid()
.Should()
.NotBe(GetRegisteredUserId());
}
}

View File

@@ -1,13 +1,14 @@
using API.Core;
using API.Specs.Mocks;
using Features.Emails.Services;
using Infrastructure.Email;
using Features.ImageUploads.Services;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
namespace API.Specs;
public class TestApiFactory : WebApplicationFactory<Program>
internal class TestApiFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
@@ -32,6 +33,15 @@ public class TestApiFactory : WebApplicationFactory<Program>
services.Remove(emailDispatcherDescriptor);
services.AddScoped<IEmailDispatcher, MockEmailDispatcher>();
ServiceDescriptor? fileStorageDescriptor = services.SingleOrDefault(d =>
d.ServiceType == typeof(IFileStorageProvider)
);
if (fileStorageDescriptor != null)
services.Remove(fileStorageDescriptor);
services.AddSingleton<IFileStorageProvider, MockFileStorageProvider>();
});
}
}

View File

@@ -1,4 +1,11 @@
<Solution>
<Folder Name="/Docker/">
<File Path="../docker-compose.db.yaml"/>
<File Path="../docker-compose.min.yaml"/>
<File Path="../docker-compose.dev.yaml"/>
<File Path="../docker-compose.prod.yaml"/>
<File Path="../docker-compose.test.yaml"/>
</Folder>
<Folder Name="/API/">
<Project Path="API/API.Core/API.Core.csproj" />
<Project Path="API/API.Specs/API.Specs.csproj" />
@@ -12,25 +19,21 @@
<Project Path="Domain/Domain.Entities/Domain.Entities.csproj" />
<Project Path="Domain/Domain.Exceptions/Domain.Exceptions.csproj" />
</Folder>
<Folder Name="/Features/Users/">
<Project Path="Features\Features.Users.Tests\Features.Users.Tests.csproj" />
<Project Path="Features\Features.Users\Features.Users.csproj" />
</Folder>
<Folder Name="/Infrastructure/">
<Project Path="Infrastructure/Infrastructure.Configuration/Infrastructure.Configuration.csproj" />
<Project Path="Infrastructure/Infrastructure.Email/Infrastructure.Email.csproj" />
<Project Path="Infrastructure/Infrastructure.Email.Templates/Infrastructure.Email.Templates.csproj" />
<Project Path="Infrastructure/Infrastructure.FileUpload/Infrastructure.FileUpload.csproj" />
<Project Path="Infrastructure/Infrastructure.Jwt/Infrastructure.Jwt.csproj" />
<Project Path="Infrastructure/Infrastructure.PasswordHashing/Infrastructure.PasswordHashing.csproj" />
<Folder Name="/Configuration/">
<Project Path="Configuration/Configuration.csproj" />
</Folder>
<Folder Name="/Features/" />
<Folder Name="/Features/Users/">
<Project Path="Features/Features.Users.Tests/Features.Users.Tests.csproj" />
<Project Path="Features/Features.Users/Features.Users.csproj" />
</Folder>
<Folder Name="/Features/Breweries/">
<Project Path="Features/Features.Breweries/Features.Breweries.csproj" />
<Project Path="Features/Features.Breweries.Tests/Features.Breweries.Tests.csproj" />
</Folder>
<Folder Name="/Features/Emails/">
<Project Path="Features/Features.Emails/Features.Emails.csproj" />
<Project Path="Features/Features.Emails.Templates/Features.Emails.Templates.csproj" />
<Project Path="Features/Features.Emails.Tests/Features.Emails.Tests.csproj" />
</Folder>
<Folder Name="/Features/Locations/">
@@ -44,5 +47,6 @@
<Folder Name="/Shared/">
<Project Path="Shared/Shared.Contracts/Shared.Contracts.csproj" />
<Project Path="Shared/Shared.Application/Shared.Application.csproj" />
<Project Path="Shared/Shared.Application.Tests/Shared.Application.Tests.csproj" />
</Folder>
</Solution>

View File

@@ -3,7 +3,7 @@
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Infrastructure.Configuration</RootNamespace>
<RootNamespace>Configuration</RootNamespace>
</PropertyGroup>
<ItemGroup>

View File

@@ -1,6 +1,6 @@
using Microsoft.Extensions.Configuration;
namespace Infrastructure.Configuration;
namespace Configuration;
public static class ConfigurationHelpers
{

View File

@@ -1,4 +1,4 @@
namespace Infrastructure.Configuration;
namespace Configuration;
public static class ConfigurationKeys
{
@@ -23,6 +23,14 @@ public static class ConfigurationKeys
public const string SmtpFromName = "SMTP_FROM_NAME";
public const string SeaweedFsServiceUrl = "SEAWEEDFS_SERVICE_URL";
/// <summary>
/// The browser-reachable base URL of the object store, used to sign download URLs. Falls back to
/// <see cref="SeaweedFsServiceUrl" /> when unset: SigV4 covers the host, so a URL signed against
/// the container-internal endpoint is only usable by callers that can resolve that host.
/// </summary>
public const string SeaweedFsPublicUrl = "SEAWEEDFS_PUBLIC_URL";
public const string SeaweedFsAccessKeyId = "SEAWEEDFS_ACCESS_KEY_ID";
public const string SeaweedFsSecretAccessKey = "SEAWEEDFS_SECRET_ACCESS_KEY";
public const string SeaweedFsBucket = "SEAWEEDFS_BUCKET";

View File

@@ -21,6 +21,6 @@
/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Configuration\Infrastructure.Configuration.csproj" />
<ProjectReference Include="..\..\Configuration\Configuration.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,4 +1,4 @@
using Infrastructure.Configuration;
using Configuration;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;

View File

@@ -1,4 +1,4 @@
using Infrastructure.Configuration;
using Configuration;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;

View File

@@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Database\Database.Connection\Database.Connection.csproj" />
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Configuration\Infrastructure.Configuration.csproj" />
<ProjectReference Include="..\..\Configuration\Configuration.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="scripts/**/*.sql" />

View File

@@ -1,5 +1,5 @@
using Database.Connection;
using Infrastructure.Configuration;
using Configuration;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;

View File

@@ -0,0 +1,2 @@
IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = 'Auth')
EXEC('CREATE SCHEMA Auth');

View File

@@ -1,4 +1,4 @@
CREATE TABLE dbo.UserAccount
CREATE TABLE Auth.UserAccount
(
UserAccountID UNIQUEIDENTIFIER
CONSTRAINT DF_UserAccountID DEFAULT NEWID(),

View File

@@ -1,4 +1,4 @@
CREATE TABLE UserVerification -- delete verification data when user account is deleted
CREATE TABLE Auth.UserVerification -- delete verification data when user account is deleted
(
UserVerificationID UNIQUEIDENTIFIER
CONSTRAINT DF_UserVerificationID DEFAULT NEWID(),
@@ -15,7 +15,7 @@ CREATE TABLE UserVerification -- delete verification data when user account is d
CONSTRAINT FK_UserVerification_UserAccount
FOREIGN KEY (UserAccountID)
REFERENCES UserAccount (UserAccountID)
REFERENCES Auth.UserAccount (UserAccountID)
ON DELETE CASCADE,
CONSTRAINT AK_UserVerification_UserAccountID
@@ -24,4 +24,4 @@ CREATE TABLE UserVerification -- delete verification data when user account is d
CREATE
NONCLUSTERED INDEX IX_UserVerification_UserAccount
ON UserVerification(UserAccountID);
ON Auth.UserVerification(UserAccountID);

View File

@@ -1,4 +1,4 @@
CREATE TABLE UserCredential -- delete credentials when user account is deleted
CREATE TABLE Auth.UserCredential -- delete credentials when user account is deleted
(
UserCredentialID UNIQUEIDENTIFIER
CONSTRAINT DF_UserCredentialID DEFAULT NEWID(),
@@ -26,15 +26,15 @@ CREATE TABLE UserCredential -- delete credentials when user account is deleted
CONSTRAINT FK_UserCredential_UserAccount
FOREIGN KEY (UserAccountID)
REFERENCES UserAccount (UserAccountID)
REFERENCES Auth.UserAccount (UserAccountID)
ON DELETE CASCADE
);
CREATE
NONCLUSTERED INDEX IX_UserCredential_UserAccount
ON UserCredential(UserAccountID);
ON Auth.UserCredential(UserAccountID);
CREATE
NONCLUSTERED INDEX IX_UserCredential_Account_Active
ON UserCredential(UserAccountID, IsRevoked, Expiry)
ON Auth.UserCredential(UserAccountID, IsRevoked, Expiry)
INCLUDE (Hash);

View File

@@ -0,0 +1,2 @@
IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = 'Geolocation')
EXEC('CREATE SCHEMA Geolocation');

View File

@@ -1,4 +1,4 @@
CREATE TABLE Country
CREATE TABLE Geolocation.Country
(
CountryID UNIQUEIDENTIFIER
CONSTRAINT DF_CountryID DEFAULT NEWID(),

View File

@@ -1,15 +1,15 @@
CREATE TABLE StateProvince
CREATE TABLE Geolocation.StateProvince
(
StateProvinceID UNIQUEIDENTIFIER
CONSTRAINT DF_StateProvinceID DEFAULT NEWID(),
StateProvinceName NVARCHAR(100) NOT NULL,
ISO3166_2 CHAR(6) NOT NULL,
-- eg 'US-CA' for California, 'CA-ON' for Ontario
CountryID UNIQUEIDENTIFIER NOT NULL,
-- eg 'US-CA' for California, 'CA-ON' for Ontario
ISO3166_2 CHAR(6) NOT NULL,
RowVersion ROWVERSION,
CONSTRAINT PK_StateProvince
@@ -18,11 +18,14 @@ CREATE TABLE StateProvince
CONSTRAINT AK_StateProvince_ISO3166_2
UNIQUE (ISO3166_2),
CONSTRAINT AK_StateProvince_Country
UNIQUE (StateProvinceName, CountryID),
CONSTRAINT FK_StateProvince_Country
FOREIGN KEY (CountryID)
REFERENCES Country (CountryID)
REFERENCES Geolocation.Country (CountryID)
);
CREATE
NONCLUSTERED INDEX IX_StateProvince_Country
ON StateProvince(CountryID);
ON Geolocation.StateProvince(CountryID);

View File

@@ -1,4 +1,4 @@
CREATE TABLE City
CREATE TABLE Geolocation.City
(
CityID UNIQUEIDENTIFIER
CONSTRAINT DF_CityID DEFAULT NEWID(),
@@ -14,9 +14,11 @@ CREATE TABLE City
CONSTRAINT FK_City_StateProvince
FOREIGN KEY (StateProvinceID)
REFERENCES StateProvince (StateProvinceID)
REFERENCES Geolocation.StateProvince (StateProvinceID),
CONSTRAINT AK_CityStateProvince UNIQUE (CityName, StateProvinceID)
);
CREATE
NONCLUSTERED INDEX IX_City_StateProvince
ON City(StateProvinceID);
ON Geolocation.City(StateProvinceID);

View File

@@ -0,0 +1,2 @@
IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = 'Media')
EXEC('CREATE SCHEMA Media');

View File

@@ -1,4 +1,4 @@
CREATE TABLE Photo -- All photos must be linked to a user account, you cannot delete a user account if they have uploaded photos
CREATE TABLE Media.Photo -- All photos must be linked to a user account, you cannot delete a user account if they have uploaded photos
(
PhotoID UNIQUEIDENTIFIER
CONSTRAINT DF_PhotoID DEFAULT NEWID(),
@@ -18,10 +18,10 @@ CREATE TABLE Photo -- All photos must be linked to a user account, you cannot de
CONSTRAINT FK_Photo_UploadedBy
FOREIGN KEY (UploadedByID)
REFERENCES UserAccount (UserAccountID)
REFERENCES Auth.UserAccount (UserAccountID)
ON DELETE NO ACTION
);
CREATE
NONCLUSTERED INDEX IX_Photo_UploadedByID
ON Photo(UploadedByID);
ON Media.Photo(UploadedByID);

View File

@@ -0,0 +1,2 @@
IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = 'Brewery')
EXEC('CREATE SCHEMA Brewery');

View File

@@ -1,4 +1,4 @@
CREATE TABLE BreweryPost -- A user cannot be deleted if they have a post
CREATE TABLE Brewery.BreweryPost -- A user cannot be deleted if they have a post
(
BreweryPostID UNIQUEIDENTIFIER
CONSTRAINT DF_BreweryPostID DEFAULT NEWID(),
@@ -21,10 +21,10 @@ CREATE TABLE BreweryPost -- A user cannot be deleted if they have a post
CONSTRAINT FK_BreweryPost_UserAccount
FOREIGN KEY (PostedByID)
REFERENCES UserAccount (UserAccountID)
REFERENCES Auth.UserAccount (UserAccountID)
ON DELETE NO ACTION
);
CREATE
NONCLUSTERED INDEX IX_BreweryPost_PostedByID
ON BreweryPost(PostedByID);
ON Brewery.BreweryPost(PostedByID);

View File

@@ -1,4 +1,4 @@
CREATE TABLE BreweryPostLocation
CREATE TABLE Brewery.BreweryPostLocation
(
BreweryPostLocationID UNIQUEIDENTIFIER
CONSTRAINT DF_BreweryPostLocationID DEFAULT NEWID(),
@@ -25,24 +25,24 @@ CREATE TABLE BreweryPostLocation
CONSTRAINT FK_BreweryPostLocation_BreweryPost
FOREIGN KEY (BreweryPostID)
REFERENCES BreweryPost (BreweryPostID)
REFERENCES Brewery.BreweryPost (BreweryPostID)
ON DELETE CASCADE,
CONSTRAINT FK_BreweryPostLocation_City
FOREIGN KEY (CityID)
REFERENCES City (CityID)
REFERENCES Geolocation.City (CityID)
);
CREATE
NONCLUSTERED INDEX IX_BreweryPostLocation_BreweryPost
ON BreweryPostLocation(BreweryPostID);
ON Brewery.BreweryPostLocation(BreweryPostID);
CREATE
NONCLUSTERED INDEX IX_BreweryPostLocation_City
ON BreweryPostLocation(CityID);
ON Brewery.BreweryPostLocation(CityID);
CREATE SPATIAL INDEX SIDX_BreweryPostLocation_Coordinates
ON BreweryPostLocation(Coordinates)
ON Brewery.BreweryPostLocation(Coordinates)
USING GEOGRAPHY_GRID
WITH (
GRIDS = (LEVEL_1 = MEDIUM, LEVEL_2 = MEDIUM, LEVEL_3 = MEDIUM, LEVEL_4 = MEDIUM),

View File

@@ -1,4 +1,4 @@
CREATE TABLE BreweryPostPhoto -- All photos linked to a post are deleted if the post is deleted
CREATE TABLE Brewery.BreweryPostPhoto -- All photos linked to a post are deleted if the post is deleted
(
BreweryPostPhotoID UNIQUEIDENTIFIER
CONSTRAINT DF_BreweryPostPhotoID DEFAULT NEWID(),
@@ -17,19 +17,19 @@ CREATE TABLE BreweryPostPhoto -- All photos linked to a post are deleted if the
CONSTRAINT FK_BreweryPostPhoto_BreweryPost
FOREIGN KEY (BreweryPostID)
REFERENCES BreweryPost (BreweryPostID)
REFERENCES Brewery.BreweryPost (BreweryPostID)
ON DELETE CASCADE,
CONSTRAINT FK_BreweryPostPhoto_Photo
FOREIGN KEY (PhotoID)
REFERENCES Photo (PhotoID)
REFERENCES Media.Photo (PhotoID)
ON DELETE CASCADE
);
CREATE
NONCLUSTERED INDEX IX_BreweryPostPhoto_Photo_BreweryPost
ON BreweryPostPhoto(PhotoID, BreweryPostID);
ON Brewery.BreweryPostPhoto(PhotoID, BreweryPostID);
CREATE
NONCLUSTERED INDEX IX_BreweryPostPhoto_BreweryPost_Photo
ON BreweryPostPhoto(BreweryPostID, PhotoID);
ON Brewery.BreweryPostPhoto(BreweryPostID, PhotoID);

View File

@@ -0,0 +1,2 @@
IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = 'Beer')
EXEC('CREATE SCHEMA Beer');

View File

@@ -1,4 +1,4 @@
CREATE TABLE BeerStyle
CREATE TABLE Beer.BeerStyle
(
BeerStyleID UNIQUEIDENTIFIER
CONSTRAINT DF_BeerStyleID DEFAULT NEWID(),

View File

@@ -1,4 +1,4 @@
CREATE TABLE BeerPost
CREATE TABLE Beer.BeerPost
(
BeerPostID UNIQUEIDENTIFIER
CONSTRAINT DF_BeerPostID DEFAULT NEWID(),
@@ -31,16 +31,16 @@ CREATE TABLE BeerPost
CONSTRAINT FK_BeerPost_PostedBy
FOREIGN KEY (PostedByID)
REFERENCES UserAccount (UserAccountID)
REFERENCES Auth.UserAccount (UserAccountID)
ON DELETE NO ACTION,
CONSTRAINT FK_BeerPost_BeerStyle
FOREIGN KEY (BeerStyleID)
REFERENCES BeerStyle (BeerStyleID),
REFERENCES Beer.BeerStyle (BeerStyleID),
CONSTRAINT FK_BeerPost_Brewery
FOREIGN KEY (BrewedByID)
REFERENCES BreweryPost (BreweryPostID),
REFERENCES Brewery.BreweryPost (BreweryPostID),
CONSTRAINT CHK_BeerPost_ABV
CHECK (ABV >= 0 AND ABV <= 67),
@@ -51,12 +51,12 @@ CREATE TABLE BeerPost
CREATE
NONCLUSTERED INDEX IX_BeerPost_PostedBy
ON BeerPost(PostedByID);
ON Beer.BeerPost(PostedByID);
CREATE
NONCLUSTERED INDEX IX_BeerPost_BeerStyle
ON BeerPost(BeerStyleID);
ON Beer.BeerPost(BeerStyleID);
CREATE
NONCLUSTERED INDEX IX_BeerPost_BrewedBy
ON BeerPost(BrewedByID);
ON Beer.BeerPost(BrewedByID);

View File

@@ -1,4 +1,4 @@
CREATE TABLE BeerPostPhoto -- All photos linked to a beer post are deleted if the post is deleted
CREATE TABLE Beer.BeerPostPhoto -- All photos linked to a beer post are deleted if the post is deleted
(
BeerPostPhotoID UNIQUEIDENTIFIER
CONSTRAINT DF_BeerPostPhotoID DEFAULT NEWID(),
@@ -17,19 +17,19 @@ CREATE TABLE BeerPostPhoto -- All photos linked to a beer post are deleted if th
CONSTRAINT FK_BeerPostPhoto_BeerPost
FOREIGN KEY (BeerPostID)
REFERENCES BeerPost (BeerPostID)
REFERENCES Beer.BeerPost (BeerPostID)
ON DELETE CASCADE,
CONSTRAINT FK_BeerPostPhoto_Photo
FOREIGN KEY (PhotoID)
REFERENCES Photo (PhotoID)
REFERENCES Media.Photo (PhotoID)
ON DELETE CASCADE
);
CREATE
NONCLUSTERED INDEX IX_BeerPostPhoto_Photo_BeerPost
ON BeerPostPhoto(PhotoID, BeerPostID);
ON Beer.BeerPostPhoto(PhotoID, BeerPostID);
CREATE
NONCLUSTERED INDEX IX_BeerPostPhoto_BeerPost_Photo
ON BeerPostPhoto(BeerPostID, PhotoID);
ON Beer.BeerPostPhoto(BeerPostID, PhotoID);

View File

@@ -1,4 +1,4 @@
CREATE TABLE BeerPostComment
CREATE TABLE Beer.BeerPostComment
(
BeerPostCommentID UNIQUEIDENTIFIER
CONSTRAINT DF_BeerPostComment DEFAULT NEWID(),
@@ -23,11 +23,11 @@ CREATE TABLE BeerPostComment
CONSTRAINT FK_BeerPostComment_BeerPost
FOREIGN KEY (BeerPostID)
REFERENCES BeerPost (BeerPostID),
REFERENCES Beer.BeerPost (BeerPostID),
CONSTRAINT FK_BeerPostComment_UserAccount
FOREIGN KEY (CommentedByID)
REFERENCES UserAccount (UserAccountID)
REFERENCES Auth.UserAccount (UserAccountID)
ON DELETE NO ACTION,
CONSTRAINT CHK_BeerPostComment_Rating
@@ -36,8 +36,8 @@ CREATE TABLE BeerPostComment
CREATE
NONCLUSTERED INDEX IX_BeerPostComment_BeerPost
ON BeerPostComment(BeerPostID);
ON Beer.BeerPostComment(BeerPostID);
CREATE
NONCLUSTERED INDEX IX_BeerPostComment_CommentedBy
ON BeerPostComment(CommentedByID);
ON Beer.BeerPostComment(CommentedByID);

View File

@@ -0,0 +1,2 @@
IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = 'Social')
EXEC('CREATE SCHEMA Social');

View File

@@ -1,4 +1,4 @@
CREATE TABLE UserFollow
CREATE TABLE Social.UserFollow
(
UserFollowID UNIQUEIDENTIFIER
CONSTRAINT DF_UserFollowID DEFAULT NEWID(),
@@ -17,12 +17,12 @@ CREATE TABLE UserFollow
CONSTRAINT FK_UserFollow_UserAccount
FOREIGN KEY (UserAccountID)
REFERENCES UserAccount (UserAccountID)
REFERENCES Auth.UserAccount (UserAccountID)
ON DELETE NO ACTION,
CONSTRAINT FK_UserFollow_UserAccountFollowing
FOREIGN KEY (FollowingID)
REFERENCES UserAccount (UserAccountID)
REFERENCES Auth.UserAccount (UserAccountID)
ON DELETE NO ACTION,
CONSTRAINT CK_CannotFollowOwnAccount
@@ -32,8 +32,8 @@ CREATE TABLE UserFollow
CREATE
NONCLUSTERED INDEX IX_UserFollow_UserAccount_FollowingID
ON UserFollow(UserAccountID, FollowingID);
ON Social.UserFollow(UserAccountID, FollowingID);
CREATE
NONCLUSTERED INDEX IX_UserFollow_FollowingID_UserAccount
ON UserFollow(FollowingID, UserAccountID);
ON Social.UserFollow(FollowingID, UserAccountID);

View File

@@ -1,4 +1,4 @@
CREATE TABLE dbo.UserProfile
CREATE TABLE Social.UserProfile
(
UserProfileID UNIQUEIDENTIFIER
CONSTRAINT DF_UserProfileID DEFAULT NEWID(),
@@ -17,6 +17,6 @@ CREATE TABLE dbo.UserProfile
CONSTRAINT FK_UserProfile_UserAccount
FOREIGN KEY (UserAccountID)
REFERENCES UserAccount (UserAccountID)
REFERENCES Auth.UserAccount (UserAccountID)
ON DELETE CASCADE
);

View File

@@ -1,4 +1,4 @@
CREATE TABLE dbo.UserAvatar
CREATE TABLE Social.UserAvatar
(
UserAvatarID UNIQUEIDENTIFIER
CONSTRAINT DF_UserAvatarID DEFAULT NEWID(),
@@ -18,12 +18,12 @@ CREATE TABLE dbo.UserAvatar
CONSTRAINT FK_UserAvatar_UserProfile
FOREIGN KEY (UserProfileID)
REFERENCES dbo.UserProfile (UserProfileID)
REFERENCES Social.UserProfile (UserProfileID)
ON DELETE CASCADE,
CONSTRAINT FK_UserAvatar_Photo
FOREIGN KEY (PhotoID)
REFERENCES dbo.Photo (PhotoID)
REFERENCES Media.Photo (PhotoID)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
@@ -33,11 +33,11 @@ CREATE TABLE dbo.UserAvatar
-- At most one active avatar per profile
CREATE UNIQUE NONCLUSTERED INDEX UX_UserAvatar_ActiveOne
ON dbo.UserAvatar (UserProfileID)
ON Social.UserAvatar (UserProfileID)
WHERE ValidTo IS NULL;
CREATE NONCLUSTERED INDEX IX_UserAvatar_Photo
ON dbo.UserAvatar (PhotoID);
ON Social.UserAvatar (PhotoID);
CREATE NONCLUSTERED INDEX ix_UserAvatar_Profile
ON dbo.UserAvatar (UserProfileID)
ON Social.UserAvatar (UserProfileID)

View File

@@ -0,0 +1,371 @@
using Database.Seed.DatabaseHelpers;
using Database.Seed.Sqlite;
using Database.Seed.SourceDataModels;
using Domain.Entities;
using Features.Breweries.Commands.CreateBrewery;
using Features.Locations.Commands.CreateCity;
using Features.Locations.Commands.CreateCountry;
using Features.Locations.Commands.CreateStateProvince;
using Features.Locations.Queries.GetCity;
using Features.Locations.Queries.GetCountry;
using Features.Locations.Queries.GetStateProvince;
using Features.Users.Commands.Authentication.RegisterUser;
using Features.Users.Commands.Profile.UpdateBiography;
using Features.Users.Commands.Profile.UploadAvatar;
using Features.Users.Dtos;
using idunno.Password;
using MediatR;
using Microsoft.AspNetCore.Http;
using Spectre.Console;
using City = Database.Seed.SourceDataModels.City;
namespace Database.Seed;
public class BiergartenDataSeeder
{
private readonly IMediator _mediator;
private readonly SeedRepository _reader;
public BiergartenDataSeeder(IMediator mediator, SeedRepository reader)
{
_mediator = mediator;
_reader = reader;
}
public async Task Run(CancellationToken cancellationToken = default)
{
AnsiConsole.Write(new Rule("[bold green]Database Seeder[/]").LeftJustified());
AnsiConsole.MarkupLine("[grey]Connecting to SQLite source and loading seed data...[/]");
AnsiConsole.WriteLine();
SeedData seedData = null!;
IReadOnlyList<Guid> userIds = [];
await AnsiConsole
.Status()
.Spinner(Spinner.Known.Dots)
.SpinnerStyle(Style.Parse("green"))
.StartAsync(
"Loading seed data...",
async ctx =>
{
seedData = await _reader.ReadSeedDataAsync(cancellationToken);
ctx.Status($"Done.");
}
);
AnsiConsole.MarkupLine(
$"[green]✓[/] Loaded [bold]{seedData.Breweries.Count}[/] breweries."
);
AnsiConsole.Write(BuildBreweryDisplayTable(seedData.Breweries));
AnsiConsole.MarkupLine($"[green]✓[/] Loaded [bold]{seedData.Users.Count}[/] users.");
AnsiConsole.Write(BuildUserDisplayTable(seedData.Users));
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine($"[green]✓[/] Loaded [bold]{seedData.Cities.Count}[/] cities.");
AnsiConsole.WriteLine();
AnsiConsole.WriteLine("Seed data loaded successfully.");
AnsiConsole.Write(
new Rule("[bold green]Loading seed data into target database.[/]").LeftJustified()
);
await AnsiConsole
.Status()
.Spinner(Spinner.Known.Dots)
.SpinnerStyle(Style.Parse("green"))
.StartAsync(
"Loading user data into target database...",
async ctx =>
{
userIds = await LoadUsersIntoDatabaseAsync(seedData.Users, cancellationToken);
ctx.Status("User data loaded into target database.");
}
);
await AnsiConsole
.Status()
.Spinner(Spinner.Known.Dots)
.SpinnerStyle(Style.Parse("green"))
.StartAsync(
"Loading avatars into target database...",
async ctx =>
{
await LoadAvatarsIntoDatabaseAsync(
userIds,
seedData.Users,
ctx,
cancellationToken
);
ctx.Status("Avatar data loaded into target database.");
}
);
await AnsiConsole
.Status()
.Spinner(Spinner.Known.Dots)
.SpinnerStyle(Style.Parse("green"))
.StartAsync(
"Loading city data into target database...",
async ctx =>
{
await LoadCitiesIntoDatabaseAsync(seedData.Cities, ctx, cancellationToken);
ctx.Status("City data loaded into target database.");
}
);
await AnsiConsole
.Status()
.Spinner(Spinner.Known.Dots)
.SpinnerStyle(Style.Parse("green"))
.StartAsync(
"Loading brewery data into target database...",
async ctx =>
{
await LoadBreweriesIntoDatabaseAsync(
seedData.Breweries,
userIds,
ctx,
cancellationToken
);
ctx.Status("Brewery data loaded into target database.");
}
);
}
private async Task<IReadOnlyList<Guid>> LoadUsersIntoDatabaseAsync(
IReadOnlyList<UserRecord> users,
CancellationToken cancellationToken
)
{
List<Guid> userAccountIds = [];
foreach (UserRecord userRecord in users)
{
cancellationToken.ThrowIfCancellationRequested();
// allowRepeatedCharacters: true -- 12 unique digits was requested from only 10 possible
// digit characters (0-9)
string password = PasswordGenerator.Generate(
length: 64,
numberOfDigits: 12,
numberOfSymbols: 12,
allowRepeatedCharacters: true
);
RegistrationPayload registration = await _mediator.Send(
new RegisterUserCommand(
userRecord.User.Username,
userRecord.User.FirstName,
userRecord.User.LastName,
userRecord.Email,
DateTime.Parse(userRecord.DateOfBirth),
password
),
cancellationToken
);
userAccountIds.Add(registration.UserAccountId);
}
return userAccountIds;
}
private async Task LoadAvatarsIntoDatabaseAsync(
IReadOnlyList<Guid> userIds,
IReadOnlyList<UserRecord> users,
StatusContext ctx,
CancellationToken cancellationToken
)
{
for (int i = 0; i < userIds.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
ctx.Status($"Loading avatar {i + 1}/{userIds.Count} into target database...");
Guid userId = userIds[i];
await _mediator.Send(
new UpdateBiographyCommand(userId, users[i].User.Bio),
cancellationToken
);
byte[] avatarPng = AvatarGenerator.GeneratePng(userId);
await using MemoryStream stream = new(avatarPng);
IFormFile file = new FormFile(stream, 0, stream.Length, "file", $"{userId}.png")
{
Headers = new HeaderDictionary(),
ContentType = "image/png",
};
await _mediator.Send(new UploadAvatarCommand(userId, file), cancellationToken);
}
}
private async Task LoadCitiesIntoDatabaseAsync(
IReadOnlyList<City> cities,
StatusContext ctx,
CancellationToken cancellationToken
)
{
Dictionary<string, Guid> countryIdsByIso31661 = [];
Dictionary<string, Guid> stateProvinceIdsByIso31662 = [];
foreach (City city in cities)
{
cancellationToken.ThrowIfCancellationRequested();
ctx.Status(
$"Loading city {city.CityName}, {city.StateProvinceName}, {city.CountryName}..."
);
if (!countryIdsByIso31661.TryGetValue(city.ISO_3166_1, out Guid countryId))
{
countryId =
await _mediator.Send(new GetCountryQuery(city.ISO_3166_1), cancellationToken)
?? await _mediator.Send(
new CreateCountryCommand(city.CountryName, city.ISO_3166_1),
cancellationToken
);
countryIdsByIso31661[city.ISO_3166_1] = countryId;
}
if (!stateProvinceIdsByIso31662.TryGetValue(city.ISO_3166_2, out Guid stateProvinceId))
{
stateProvinceId =
await _mediator.Send(
new GetStateProvinceQuery(city.ISO_3166_2),
cancellationToken
)
?? await _mediator.Send(
new CreateStateProvinceCommand(
city.StateProvinceName,
city.ISO_3166_2,
countryId
),
cancellationToken
);
stateProvinceIdsByIso31662[city.ISO_3166_2] = stateProvinceId;
}
await _mediator.Send(
new CreateCityCommand(city.CityName, stateProvinceId),
cancellationToken
);
}
}
private async Task LoadBreweriesIntoDatabaseAsync(
IReadOnlyList<BreweryResult> breweries,
IReadOnlyList<Guid> posterUserIds,
StatusContext ctx,
CancellationToken cancellationToken
)
{
if (posterUserIds.Count == 0)
throw new InvalidOperationException(
"Cannot load breweries without any registered users."
);
for (int i = 0; i < breweries.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
BreweryResult breweryRecord = breweries[i];
BreweryAddress address =
breweryRecord.Address
?? throw new InvalidOperationException("Brewery address was not loaded.");
City city =
address.City ?? throw new InvalidOperationException("Brewery city was not loaded.");
ctx.Status($"Loading brewery {i + 1}/{breweries.Count} into target database...");
Guid cityId =
await _mediator.Send(
new GetCityQuery(city.CityName, city.ISO_3166_2),
cancellationToken
)
?? throw new InvalidOperationException(
$"City '{city.CityName}' "
+ $"({city.ISO_3166_2}) was not found. "
+ "Cities must be loaded before breweries."
);
await _mediator.Send(
new CreateBreweryCommand(
posterUserIds[i % posterUserIds.Count],
breweryRecord.NameEn,
breweryRecord.DescriptionEn,
new CreateBreweryLocation(
cityId,
address.AddressLine1,
null,
address.PostalCode,
new CoordinateData(address.Latitude, address.Longitude)
)
),
cancellationToken
);
}
}
private static Table BuildBreweryDisplayTable(IReadOnlyList<BreweryResult> breweries)
{
Table table = new Table()
.AddColumn("Brewery Name (EN)")
.AddColumn("Brewery Name (Local)")
.AddColumn("City")
.AddColumn("State/Province")
.AddColumn("Country")
.AddColumn("Longitude")
.AddColumn("Latitude");
foreach (BreweryResult brewery in breweries)
{
BreweryAddress address =
brewery.Address
?? throw new InvalidOperationException("Brewery address was not loaded.");
City city =
address.City ?? throw new InvalidOperationException("Brewery city was not loaded.");
table.AddRow(
brewery.NameEn,
brewery.NameLocal,
city.CityName,
city.StateProvinceName,
city.CountryName,
address.Longitude.ToString("F6"),
address.Latitude.ToString("F6")
);
}
return table;
}
private static Table BuildUserDisplayTable(IReadOnlyList<UserRecord> users)
{
Table table = new Table()
.AddColumn("Username")
.AddColumn("First Name")
.AddColumn("Last Name")
.AddColumn("Email")
.AddColumn("Date of Birth");
foreach (UserRecord user in users)
{
table.AddRow(
user.User.Username,
user.User.FirstName,
user.User.LastName,
user.Email,
user.DateOfBirth
);
}
return table;
}
}

View File

@@ -9,7 +9,7 @@
<ItemGroup>
<PackageReference Include="idunno.Password.Generator" Version="2.0.0" />
<PackageReference Include="MediatR" Version="12.4.1" />
<PackageReference Include="MediatR" Version="12.5.0" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="7.0.2" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.11" />
<PackageReference Include="SkiaSharp" Version="4.151.1" />
@@ -24,9 +24,11 @@
<ProjectReference Include="..\..\Features\Features.Users\Features.Users.csproj" />
<ProjectReference Include="..\..\Features\Features.Locations\Features.Locations.csproj" />
<ProjectReference Include="..\..\Features\Features.PhotoUpload\Features.PhotoUpload.csproj" />
<ProjectReference Include="..\..\Infrastructure\Infrastructure.FileUpload\Infrastructure.FileUpload.csproj" />
</ItemGroup>
<ItemGroup>
<None CopyToOutputDirectory="PreserveNewest" Include="SeedData\biergarten_seed_2026-08-25T20-45-50.697244Z.sqlite" />
<None
CopyToOutputDirectory="PreserveNewest"
Include="SeedData\biergarten_seed_2026-08-25T20-45-50.697244Z.sqlite"
/>
</ItemGroup>
</Project>

View File

@@ -1,24 +0,0 @@
#region
using Database.Connection;
using Microsoft.Extensions.Configuration;
#endregion
namespace Database.Seed.DatabaseHelpers;
public static class ConnectionStrings
{
public static string GetSqlServerConnectionString(IConfiguration configuration) =>
SqlConnectionStringHelper.TryGetStandardDbConnectionString(
configuration,
out string connectionString
)
? connectionString
: throw new InvalidOperationException(
"Database connection string not configured. Set DB_SERVER, DB_NAME, DB_USER, DB_PASSWORD env vars."
);
public static string SqliteConnectionString =>
"Data Source=SeedData/biergarten_seed_2026-08-25T20-45-50.697244Z.sqlite";
}

View File

@@ -1,4 +1,4 @@
using Features.Auth.Services;
using Features.Users.Services;
namespace Database.Seed.DatabaseHelpers;

View File

@@ -1,14 +0,0 @@
namespace Database.Seed.PipelineData;
public sealed record BreweryAddress
{
public required City City { get; init; }
public required double Longitude { get; init; }
public required double Latitude { get; init; }
public required string AddressLine1 { get; init; }
public required string PostalCode { get; init; }
}

View File

@@ -1,8 +0,0 @@
namespace Database.Seed.PipelineData;
public sealed record BreweryRecord
{
public required BreweryAddress Address { get; init; }
public required BreweryResult Brewery { get; init; }
}

View File

@@ -1,12 +0,0 @@
namespace Database.Seed.PipelineData;
public sealed record BreweryResult
{
public required string NameEn { get; init; }
public required string DescriptionEn { get; init; }
public required string NameLocal { get; init; }
public required string DescriptionLocal { get; init; }
}

View File

@@ -1,18 +0,0 @@
namespace Database.Seed.PipelineData;
public sealed record City
{
public required string CityName { get; init; }
public required string StateProvince { get; init; }
public required string Iso31662 { get; init; }
public required string Country { get; init; }
public required string Iso31661 { get; init; }
public IReadOnlyList<string> LocalLanguages { get; init; } = [];
public required PostalCodeSpec PostalCode { get; init; }
}

View File

@@ -1,10 +0,0 @@
namespace Database.Seed.PipelineData;
public sealed record PostalCodeSpec
{
public required string CountryFormatRegex { get; init; }
public IReadOnlyList<string> CityRegexes { get; init; } = [];
public IReadOnlyList<string> Examples { get; init; } = [];
}

View File

@@ -1,10 +0,0 @@
namespace Database.Seed.PipelineData;
public sealed record UserAddress
{
public required City City { get; init; }
public required double Longitude { get; init; }
public required double Latitude { get; init; }
}

View File

@@ -1,12 +0,0 @@
namespace Database.Seed.PipelineData;
public sealed record UserRecord
{
public required UserAddress Address { get; init; }
public required UserResult User { get; init; }
public required string Email { get; init; }
public required string DateOfBirth { get; init; }
}

View File

@@ -1,16 +0,0 @@
namespace Database.Seed.PipelineData;
public sealed record UserResult
{
public required string FirstName { get; init; }
public required string LastName { get; init; }
public required string Gender { get; init; }
public required string Username { get; init; }
public required string Bio { get; init; }
public required float ActivityWeight { get; init; }
}

View File

@@ -1,34 +1,25 @@
using Database.Connection.DependencyInjection;
using Database.Seed.DatabaseHelpers;
using Database.Seed.PipelineData;
using Database.Seed.Sqlite;
using Domain.Entities;
using Features.Auth.Commands.Authentication.RegisterUser;
using Features.Auth.Commands.Profile.UpdateBiography;
using Features.Auth.Commands.Profile.UploadAvatar;
using Features.Users.DependencyInjection;
using Features.Auth.Dtos;
using Features.Auth.Services;
using Features.Breweries.Commands.CreateBrewery;
using Features.Breweries.DependencyInjection;
using Features.ImageUploads.Commands.UploadPhoto;
using Features.ImageUploads.DependencyInjection;
using Features.Locations.Commands.GetOrCreateCity;
using Features.Locations.DependencyInjection;
using Features.Locations.Dtos;
using idunno.Password;
using Infrastructure.FileUpload;
using Features.Locations.Queries.GetCountry;
using Features.Users.Commands.Profile.UploadAvatar;
using Features.Users.DependencyInjection;
using Features.Users.Services;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Spectre.Console;
return await RunAsync();
namespace Database.Seed;
static async Task<int> RunAsync()
internal class Program
{
try
private static ServiceProvider BuildServiceProvider()
{
IConfiguration configuration = new ConfigurationBuilder().AddEnvironmentVariables().Build();
@@ -39,264 +30,47 @@ static async Task<int> RunAsync()
.AddFeaturesLocations()
.AddFeaturesUsers()
.AddFeaturesPhotoUpload()
.AddSingleton<IFileStorageProvider, S3FileStorageProvider>()
.AddScoped<ITokenService, NoOpTokenService>()
.AddMediatR(cfg =>
cfg.RegisterServicesFromAssemblyContaining<CreateBreweryCommand>()
.RegisterServicesFromAssemblyContaining<GetOrCreateCityCommand>()
.RegisterServicesFromAssemblyContaining<GetCountryQuery>()
.RegisterServicesFromAssemblyContaining<UploadAvatarCommand>()
.RegisterServicesFromAssemblyContaining<UploadPhotoCommand>()
);
await using ServiceProvider provider = services.BuildServiceProvider();
IMediator mediator = provider.GetRequiredService<IMediator>();
AnsiConsole.Write(new Rule("[bold green]Database Seeder[/]").LeftJustified());
AnsiConsole.MarkupLine("[grey]Connecting to SQLite source and loading seed data...[/]");
AnsiConsole.WriteLine();
PipelineSeedDataReader reader = new(ConnectionStrings.SqliteConnectionString);
SeedData seedData = null!;
IReadOnlyList<Guid> userIds = [];
await AnsiConsole
.Status()
.Spinner(Spinner.Known.Dots)
.SpinnerStyle(Style.Parse("green"))
.StartAsync(
"Loading seed data...",
async ctx =>
{
seedData = await reader.ReadSeedDataAsync();
ctx.Status(
$"Loaded {seedData.Breweries.Count} breweries and {seedData.Users.Count} users."
);
}
);
AnsiConsole.MarkupLine(
$"[green]✓[/] Loaded [bold]{seedData.Breweries.Count}[/] breweries."
);
AnsiConsole.Write(BuildBreweryTable(seedData.Breweries));
AnsiConsole.WriteLine();
AnsiConsole.MarkupLine($"[green]✓[/] Loaded [bold]{seedData.Users.Count}[/] users.");
AnsiConsole.Write(BuildUserTable(seedData.Users));
AnsiConsole.WriteLine();
AnsiConsole.WriteLine("Seed data loaded successfully.");
AnsiConsole.Write(
new Rule("[bold green]Loading seed data into target database.[/]").LeftJustified()
);
await AnsiConsole
.Status()
.Spinner(Spinner.Known.Dots)
.SpinnerStyle(Style.Parse("green"))
.StartAsync(
"Loading user data into target database...",
async ctx =>
{
userIds = await LoadUsersIntoDatabaseAsync(mediator, seedData.Users);
ctx.Status("User data loaded into target database.");
}
);
await AnsiConsole
.Status()
.Spinner(Spinner.Known.Dots)
.SpinnerStyle(Style.Parse("green"))
.StartAsync(
"Loading avatars into target database...",
async ctx =>
{
await LoadAvatarsIntoDatabaseAsync(mediator, userIds, seedData.Users, ctx);
ctx.Status("Avatar data loaded into target database.");
}
);
await AnsiConsole
.Status()
.Spinner(Spinner.Known.Dots)
.SpinnerStyle(Style.Parse("green"))
.StartAsync(
"Loading brewery data into target database...",
async ctx =>
{
await LoadBreweriesIntoDatabaseAsync(
mediator,
seedData.Breweries,
userIds,
ctx
);
ctx.Status("Brewery data loaded into target database.");
}
);
return 0;
}
catch (Exception ex)
{
AnsiConsole.MarkupLine("[red]Seeding failed.[/]");
AnsiConsole.WriteException(ex);
return 1;
}
}
static async Task<IReadOnlyList<Guid>> LoadUsersIntoDatabaseAsync(
IMediator mediator,
IReadOnlyList<UserRecord> users
)
{
List<Guid> userAccountIds = [];
foreach (UserRecord userRecord in users)
{
// allowRepeatedCharacters: true -- 12 unique digits was requested from only 10 possible
// digit characters (0-9), which idunno.Password rejects outright.
string password = PasswordGenerator.Generate(64, 12, 12, allowRepeatedCharacters: true);
RegistrationPayload registration = await mediator.Send(
new RegisterUserCommand(
userRecord.User.Username,
userRecord.User.FirstName,
userRecord.User.LastName,
userRecord.Email,
DateTime.Parse(userRecord.DateOfBirth),
password
)
);
userAccountIds.Add(registration.UserAccountId);
return services.BuildServiceProvider();
}
return userAccountIds;
}
static async Task LoadAvatarsIntoDatabaseAsync(
IMediator mediator,
IReadOnlyList<Guid> userIds,
IReadOnlyList<UserRecord> users,
StatusContext ctx
)
{
for (int i = 0; i < userIds.Count; i++)
public static async Task<int> Main()
{
ctx.Status($"Loading avatar {i + 1}/{userIds.Count} into target database...");
Guid userId = userIds[i];
await mediator.Send(new UpdateBiographyCommand(userId, users[i].User.Bio));
byte[] avatarPng = AvatarGenerator.GeneratePng(userId);
await using MemoryStream stream = new(avatarPng);
IFormFile file = new FormFile(stream, 0, stream.Length, "file", $"{userId}.png")
using CancellationTokenSource cts = new();
Console.CancelKeyPress += (_, e) =>
{
Headers = new HeaderDictionary(),
ContentType = "image/png",
e.Cancel = true;
// ReSharper disable once AccessToDisposedClosure
cts.Cancel();
};
await mediator.Send(new UploadAvatarCommand(userId, file));
try
{
await using ServiceProvider provider = BuildServiceProvider();
IMediator mediator = provider.GetRequiredService<IMediator>();
SeedRepository reader = new SeedRepository(
connectionString: "Data Source=SeedData/biergarten_seed_2026-08-25T20-45-50.697244Z.sqlite"
);
await new BiergartenDataSeeder(mediator, reader).Run(cts.Token);
return 0;
}
catch (OperationCanceledException)
{
AnsiConsole.MarkupLine("[yellow]Seeding cancelled.[/]");
return 1;
}
catch (Exception ex)
{
AnsiConsole.MarkupLine("[red]Seeding failed.[/]");
AnsiConsole.WriteException(ex);
return 1;
}
}
}
static async Task LoadBreweriesIntoDatabaseAsync(
IMediator mediator,
IReadOnlyList<BreweryRecord> breweries,
IReadOnlyList<Guid> posterUserIds,
StatusContext ctx
)
{
if (posterUserIds.Count == 0)
throw new InvalidOperationException("Cannot load breweries without any registered users.");
for (int i = 0; i < breweries.Count; i++)
{
BreweryRecord breweryRecord = breweries[i];
ctx.Status($"Loading brewery {i + 1}/{breweries.Count} into target database...");
Guid cityId = await mediator.Send(
new GetOrCreateCityCommand(
new CityLocation(
breweryRecord.Address.City.CityName,
breweryRecord.Address.City.StateProvince,
breweryRecord.Address.City.Iso31662,
breweryRecord.Address.City.Country,
breweryRecord.Address.City.Iso31661
)
)
);
await mediator.Send(
new CreateBreweryCommand(
posterUserIds[i % posterUserIds.Count],
breweryRecord.Brewery.NameEn,
breweryRecord.Brewery.DescriptionEn,
new CreateBreweryLocation(
cityId,
breweryRecord.Address.AddressLine1,
null,
breweryRecord.Address.PostalCode,
new CoordinateData(
breweryRecord.Address.Latitude,
breweryRecord.Address.Longitude
)
)
)
);
}
}
static Table BuildBreweryTable(IReadOnlyList<BreweryRecord> breweries)
{
Table table = new Table()
.AddColumn("Brewery Name (EN)")
.AddColumn("Brewery Name (Local)")
.AddColumn("City")
.AddColumn("State/Province")
.AddColumn("Country")
.AddColumn("Longitude")
.AddColumn("Latitude");
foreach (BreweryRecord brewery in breweries)
{
table.AddRow(
brewery.Brewery.NameEn,
brewery.Brewery.NameLocal,
brewery.Address.City.CityName,
brewery.Address.City.StateProvince,
brewery.Address.City.Country,
brewery.Address.Longitude.ToString("F6"),
brewery.Address.Latitude.ToString("F6")
);
}
return table;
}
static Table BuildUserTable(IReadOnlyList<UserRecord> users)
{
Table table = new Table()
.AddColumn("Username")
.AddColumn("First Name")
.AddColumn("Last Name")
.AddColumn("Email")
.AddColumn("Date of Birth");
foreach (UserRecord user in users)
{
table.AddRow(
user.User.Username,
user.User.FirstName,
user.User.LastName,
user.Email,
user.DateOfBirth
);
}
return table;
}

View File

@@ -0,0 +1,104 @@
namespace Database.Seed.SourceDataModels;
public sealed record PostalCodeSpec(
string CountryFormatRegex,
IReadOnlyList<string> CityRegexes
);
public sealed class City
{
// Identity
public int Id { get; init; }
// Attributes
public string CityName { get; init; } = string.Empty;
// Resharper disable InconsistentNaming
public string ISO_3166_1 { get; init; } = string.Empty;
public string ISO_3166_2 { get; init; } = string.Empty;
public string CountryName { get; init; } = string.Empty;
public string StateProvinceName { get; init; } = string.Empty;
public double Longitude { get; init; }
public double Latitude { get; init; }
public IReadOnlyList<string> LocalLanguages { get; init; } = [];
public PostalCodeSpec? PostalCode { get; init; }
}
public sealed class BreweryAddress
{
// Identity
public int Id { get; init; }
// FK References
public int CityId { get; init; }
public int BreweryId { get; init; } // FK lives on this side in the DB (brewery_addresses.brewery_id)
// Attributes
public double Longitude { get; init; }
public double Latitude { get; init; }
public string AddressLine1 { get; init; } = string.Empty;
public string PostalCode { get; init; } = string.Empty;
// Navigation properties
public City? City { get; init; }
public BreweryResult? Brewery { get; init; }
}
public sealed class BreweryResult
{
// Identity
public int Id { get; init; }
// Attributes
public string NameEn { get; init; } = string.Empty;
public string DescriptionEn { get; init; } = string.Empty;
public string NameLocal { get; init; } = string.Empty;
public string DescriptionLocal { get; init; } = string.Empty;
// Navigation properties
public BreweryAddress? Address { get; init; }
}
public sealed class UserAddress
{
// Identity
public int Id { get; init; }
// FK References
public int CityId { get; init; }
public int UserId { get; init; }
// Attributes
public double Longitude { get; init; }
public double Latitude { get; init; }
// Navigation properties
public City? City { get; init; }
}
public sealed class UserResult
{
// Identity
public int Id { get; init; }
// Attributes
public string FirstName { get; init; } = string.Empty;
public string LastName { get; init; } = string.Empty;
public string Gender { get; init; } = string.Empty;
public string Username { get; init; } = string.Empty;
public string Bio { get; init; } = string.Empty;
public float ActivityWeight { get; init; }
}
public sealed class UserRecord
{
// Attributes
public string Email { get; init; } = string.Empty;
public string DateOfBirth { get; init; } = string.Empty;
// Navigation properties
public UserAddress Address { get; init; } = new();
public UserResult User { get; init; } = new();
}

View File

@@ -1,215 +1,259 @@
using System.Text.Json;
using Database.Seed.PipelineData;
using Dapper;
using Database.Seed.SourceDataModels;
using Microsoft.Data.Sqlite;
namespace Database.Seed.Sqlite;
public sealed record SeedData(
IReadOnlyList<BreweryRecord> Breweries,
IReadOnlyList<City> Cities,
IReadOnlyList<BreweryResult> Breweries,
IReadOnlyList<UserRecord> Users
);
public sealed class PipelineSeedDataReader
public sealed class SeedRepository : IDisposable
{
private readonly string _connectionString;
public PipelineSeedDataReader(string connectionString)
private readonly SqliteConnection connection;
public SeedRepository(string connectionString)
{
_connectionString = connectionString;
connection = new(connectionString);
}
public void Dispose()
{
connection.Dispose();
}
/// <summary>
/// Reads breweries and users in a single connection, loading the cities
/// lookup only once and sharing it between both reads.
/// </summary>
public async Task<SeedData> ReadSeedDataAsync(CancellationToken cancellationToken = default)
public async Task<SeedData> ReadSeedDataAsync(
CancellationToken cancellationToken = default
)
{
await using SqliteConnection connection = new(_connectionString);
await connection.OpenAsync(cancellationToken);
IReadOnlyDictionary<long, City> cities = await ReadCitiesAsync(
IReadOnlyDictionary<int, City> cities = await ReadCitiesAsync(
connection,
cancellationToken
);
IReadOnlyList<BreweryRecord> breweries = await ReadBreweryRecordsAsync(
IReadOnlyList<BreweryResult> breweries = await ReadBreweryRecordsAsync(
connection,
cities,
cancellationToken
);
IReadOnlyList<UserRecord> users = await ReadUserRecordsAsync(
connection,
cities,
cancellationToken
);
return new SeedData(breweries, users);
return new SeedData([.. cities.Values], breweries, users);
}
private static async Task<IReadOnlyList<BreweryRecord>> ReadBreweryRecordsAsync(
private sealed record BreweryRow(
long Id,
string NameEn,
string DescriptionEn,
string NameLocal,
string DescriptionLocal,
long AddressId,
long CityId,
double Longitude,
double Latitude,
string AddressLine1,
string PostalCode
);
private static async Task<IReadOnlyList<BreweryResult>> ReadBreweryRecordsAsync(
SqliteConnection connection,
IReadOnlyDictionary<long, City> cities,
IReadOnlyDictionary<int, City> cities,
CancellationToken cancellationToken
)
{
const string sql = """
SELECT b.name_en, b.description_en, b.name_local, b.description_local,
ba.city_id, ba.longitude, ba.latitude, ba.address_line1, ba.postal_code
FROM breweries b
JOIN brewery_addresses ba ON ba.brewery_id = b.id;
SELECT
b.id AS Id,
b.name_en AS NameEn,
b.description_en AS DescriptionEn,
b.name_local AS NameLocal,
b.description_local AS DescriptionLocal,
ba.id AS AddressId,
ba.city_id AS CityId,
ba.longitude AS Longitude,
ba.latitude AS Latitude,
ba.address_line1 AS AddressLine1,
ba.postal_code AS PostalCode
FROM
breweries b
INNER JOIN
brewery_addresses ba ON ba.brewery_id = b.id;
""";
await using SqliteCommand command = new(sql, connection);
await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken);
CommandDefinition command = new(sql, cancellationToken: cancellationToken);
IEnumerable<BreweryRow> rows = await connection.QueryAsync<BreweryRow>(command);
const int nameEnIndex = 0;
const int descriptionEnIndex = 1;
const int nameLocalIndex = 2;
const int descriptionLocalIndex = 3;
const int cityIdIndex = 4;
const int longitudeIndex = 5;
const int latitudeIndex = 6;
const int addressLine1Index = 7;
const int postalCodeIndex = 8;
List<BreweryRecord> records = [];
while (await reader.ReadAsync(cancellationToken))
records.Add(
new BreweryRecord
return [.. rows.Select(row => new BreweryResult
{
Id = (int)row.Id,
NameEn = row.NameEn,
DescriptionEn = row.DescriptionEn,
NameLocal = row.NameLocal,
DescriptionLocal = row.DescriptionLocal,
Address = new BreweryAddress
{
Brewery = new BreweryResult
{
NameEn = reader.GetString(nameEnIndex),
DescriptionEn = reader.GetString(descriptionEnIndex),
NameLocal = reader.GetString(nameLocalIndex),
DescriptionLocal = reader.GetString(descriptionLocalIndex),
},
Address = new BreweryAddress
{
City = cities[reader.GetInt64(cityIdIndex)],
Longitude = reader.GetDouble(longitudeIndex),
Latitude = reader.GetDouble(latitudeIndex),
AddressLine1 = reader.GetString(addressLine1Index),
PostalCode = reader.GetString(postalCodeIndex),
},
}
);
return records;
Id = (int)row.AddressId,
CityId = (int)row.CityId,
BreweryId = (int)row.Id,
Longitude = row.Longitude,
Latitude = row.Latitude,
AddressLine1 = row.AddressLine1,
PostalCode = row.PostalCode,
City = cities[(int)row.CityId],
},
})];
}
private sealed record UserRow(
long Id,
string FirstName,
string LastName,
string Gender,
string Username,
string Bio,
double ActivityWeight,
string Email,
string DateOfBirth,
long AddressId,
long CityId,
double Longitude,
double Latitude
);
private static async Task<IReadOnlyList<UserRecord>> ReadUserRecordsAsync(
SqliteConnection connection,
IReadOnlyDictionary<long, City> cities,
IReadOnlyDictionary<int, City> cities,
CancellationToken cancellationToken
)
{
const string sql = """
SELECT u.first_name, u.last_name, u.gender, u.username, u.bio,
u.activity_weight, u.email, u.date_of_birth,
ua.city_id, ua.longitude, ua.latitude
FROM users u
JOIN user_addresses ua ON ua.user_id = u.id;
SELECT
u.id AS Id,
u.first_name AS FirstName,
u.last_name AS LastName,
u.gender AS Gender,
u.username AS Username,
u.bio AS Bio,
u.activity_weight AS ActivityWeight,
u.email AS Email,
u.date_of_birth AS DateOfBirth,
ua.id AS AddressId,
ua.city_id AS CityId,
ua.longitude AS Longitude,
ua.latitude AS Latitude
FROM
users u
INNER JOIN
user_addresses ua ON ua.user_id = u.id;
""";
await using SqliteCommand command = new(sql, connection);
await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken);
CommandDefinition command = new(sql, cancellationToken: cancellationToken);
IEnumerable<UserRow> rows = await connection.QueryAsync<UserRow>(command);
const int firstNameIndex = 0;
const int lastNameIndex = 1;
const int genderIndex = 2;
const int usernameIndex = 3;
const int bioIndex = 4;
const int activityWeightIndex = 5;
const int emailIndex = 6;
const int dateOfBirthIndex = 7;
const int cityIdIndex = 8;
const int longitudeIndex = 9;
const int latitudeIndex = 10;
List<UserRecord> records = [];
while (await reader.ReadAsync(cancellationToken))
records.Add(
new UserRecord
return [.. rows.Select(row => new UserRecord
{
Email = row.Email,
DateOfBirth = row.DateOfBirth,
Address = new UserAddress
{
User = new UserResult
{
FirstName = reader.GetString(firstNameIndex),
LastName = reader.GetString(lastNameIndex),
Gender = reader.GetString(genderIndex),
Username = reader.GetString(usernameIndex),
Bio = reader.GetString(bioIndex),
ActivityWeight = (float)reader.GetDouble(activityWeightIndex),
},
Email = reader.GetString(emailIndex),
DateOfBirth = reader.GetString(dateOfBirthIndex),
Address = new UserAddress
{
City = cities[reader.GetInt64(cityIdIndex)],
Longitude = reader.GetDouble(longitudeIndex),
Latitude = reader.GetDouble(latitudeIndex),
},
}
);
return records;
Id = (int)row.AddressId,
CityId = (int)row.CityId,
UserId = (int)row.Id,
Longitude = row.Longitude,
Latitude = row.Latitude,
City = cities[(int)row.CityId],
},
User = new UserResult
{
Id = (int)row.Id,
FirstName = row.FirstName,
LastName = row.LastName,
Gender = row.Gender,
Username = row.Username,
Bio = row.Bio,
ActivityWeight = (float)row.ActivityWeight,
},
})];
}
private static async Task<IReadOnlyDictionary<long, City>> ReadCitiesAsync(
private sealed record CityRow(
long Id,
string CityName,
string StateProvince,
string Iso31662,
string Country,
string Iso31661,
double Longitude,
double Latitude,
string LocalLanguagesJson,
string PostalCodeCountryFormatRegex,
string PostalCodeCityRegexesJson
);
private static async Task<IReadOnlyDictionary<int, City>> ReadCitiesAsync(
SqliteConnection connection,
CancellationToken cancellationToken
)
{
const string sql = """
SELECT
id,
city,
state_province,
iso3166_2,
country,
iso3166_1,
local_languages_json,
postal_code_country_format_regex,
postal_code_city_regex_json
id AS Id,
city AS CityName,
state_province AS StateProvince,
iso3166_2 AS Iso31662,
country AS Country,
iso3166_1 AS Iso31661,
longitude AS Longitude,
latitude AS Latitude,
local_languages_json AS LocalLanguagesJson,
postal_code_country_format_regex AS PostalCodeCountryFormatRegex,
postal_code_city_regex_json AS PostalCodeCityRegexesJson
FROM cities;
""";
await using SqliteCommand command = new(sql, connection);
await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken);
CommandDefinition command = new(sql, cancellationToken: cancellationToken);
IEnumerable<CityRow> rows = await connection.QueryAsync<CityRow>(command);
Dictionary<long, City> cities = [];
const int idIndex = 0;
const int cityNameIndex = 1;
const int stateProvinceIndex = 2;
const int iso31662Index = 3;
const int countryIndex = 4;
const int iso31661Index = 5;
const int localLanguagesIndex = 6;
const int countryFormatRegexIndex = 7;
const int cityRegexesIndex = 8;
while (await reader.ReadAsync(cancellationToken))
cities[reader.GetInt64(idIndex)] = new City
return rows.ToDictionary(
row => (int)row.Id,
row => new City
{
CityName = reader.GetString(cityNameIndex),
StateProvince = reader.GetString(stateProvinceIndex),
Iso31662 = reader.GetString(iso31662Index),
Country = reader.GetString(countryIndex),
Iso31661 = reader.GetString(iso31661Index),
LocalLanguages = DeserializeStringArray(reader.GetString(localLanguagesIndex)),
PostalCode = new PostalCodeSpec
{
CountryFormatRegex = reader.GetString(countryFormatRegexIndex),
CityRegexes = DeserializeStringArray(reader.GetString(cityRegexesIndex)),
},
};
return cities;
Id = (int)row.Id,
CityName = row.CityName,
StateProvinceName = row.StateProvince,
ISO_3166_2 = row.Iso31662,
CountryName = row.Country,
ISO_3166_1 = row.Iso31661,
Longitude = row.Longitude,
Latitude = row.Latitude,
LocalLanguages = DeserializeStringArray(row.LocalLanguagesJson),
PostalCode = new PostalCodeSpec(
CountryFormatRegex: row.PostalCodeCountryFormatRegex,
CityRegexes: DeserializeStringArray(row.PostalCodeCityRegexesJson)
),
}
);
}
private static IReadOnlyList<string> DeserializeStringArray(string json)
{
return JsonSerializer.Deserialize<List<string>>(json) ?? [];
}
}

View File

@@ -5,11 +5,11 @@ COPY . .
RUN dotnet restore "Biergarten.API.slnx"
RUN dotnet build "Biergarten.API.slnx" -c $BUILD_CONFIGURATION
# Runs every Features.*.Tests project (unit + DbMocker-backed repository tests). API.Specs is
# excluded here since it's a separate BDD/integration suite, run by its own compose service
# against the live, seeded database.
# Runs every Features.*.Tests and Shared.*.Tests project (unit + DbMocker-backed repository
# tests). API.Specs is excluded here since it's a separate BDD/integration suite, run by its own
# compose service against the live, seeded database.
FROM build AS final
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
RUN mkdir -p /app/test-results
ENTRYPOINT ["sh", "-c", "set -e; for proj in Features/*.Tests; do dotnet test \"$proj\" -c ${BUILD_CONFIGURATION:-Release} --logger \"trx;LogFileName=/app/test-results/$(basename \"$proj\").trx\"; done"]
ENTRYPOINT ["sh", "-c", "set -e; for proj in Features/*.Tests Shared/*.Tests; do dotnet test \"$proj\" -c ${BUILD_CONFIGURATION:-Release} --logger \"trx;LogFileName=/app/test-results/$(basename \"$proj\").trx\"; done"]

View File

@@ -1,3 +1,5 @@
using System.Text.Json.Serialization;
namespace Domain.Entities;
public sealed class UserAccount
@@ -19,4 +21,11 @@ public sealed class UserAccount
// Navigation properties
public UserCredential? UserCredential { get; set; }
public UserProfile? UserProfile { get; set; }
// GET /api/user/authenticated serializes this entity directly, and the avatar graph carries the
// storage key and uploader of the underlying Photo. Clients read the avatar from
// PublicUserProfileDto.AvatarUrl, which is a signed URL, so keep this one out of the response.
[JsonIgnore]
public UserAvatar? UserAvatar { get; set; }
}

View File

@@ -17,10 +17,8 @@ public class CreateBreweryHandlerTests
_handler = new CreateBreweryHandler(_repoMock.Object);
}
private static CreateBreweryLocation ValidLocation()
{
return new CreateBreweryLocation(Guid.NewGuid(), "123 Main St", null, "12345", null);
}
private static CreateBreweryLocation ValidLocation() =>
new(Guid.NewGuid(), "123 Main St", null, "12345", null);
[Fact]
public async Task Handle_PersistsEntity_WithNewIdsAndCreatedAt()

View File

@@ -0,0 +1,171 @@
using Features.Breweries.Commands.CreateBrewery;
using FluentValidation.TestHelper;
namespace Features.Breweries.Tests.Commands;
public class CreateBreweryValidatorTests
{
private readonly CreateBreweryValidator _validator = new();
private static CreateBreweryLocation ValidLocation() =>
new(Guid.NewGuid(), "123 Main St", null, "12345", null);
private static CreateBreweryCommand ValidCommand() =>
new(Guid.NewGuid(), "Valid Brewery", "A valid description.", ValidLocation());
[Fact]
public void Validate_ValidCommand_HasNoValidationErrors()
{
TestValidationResult<CreateBreweryCommand> result = _validator.TestValidate(ValidCommand());
result.ShouldNotHaveAnyValidationErrors();
}
[Fact]
public void Validate_EmptyPostedById_HasErrorForPostedById()
{
CreateBreweryCommand command = ValidCommand() with { PostedById = Guid.Empty };
TestValidationResult<CreateBreweryCommand> result = _validator.TestValidate(command);
result
.ShouldHaveValidationErrorFor(x => x.PostedById)
.WithErrorMessage("PostedById is required.");
}
[Fact]
public void Validate_EmptyBreweryName_HasErrorForBreweryName()
{
CreateBreweryCommand command = ValidCommand() with { BreweryName = "" };
TestValidationResult<CreateBreweryCommand> result = _validator.TestValidate(command);
result
.ShouldHaveValidationErrorFor(x => x.BreweryName)
.WithErrorMessage("Brewery name is required.");
}
[Fact]
public void Validate_BreweryNameTooLong_HasErrorForBreweryName()
{
CreateBreweryCommand command = ValidCommand() with { BreweryName = new string('a', 257) };
TestValidationResult<CreateBreweryCommand> result = _validator.TestValidate(command);
result
.ShouldHaveValidationErrorFor(x => x.BreweryName)
.WithErrorMessage("Brewery name cannot exceed 256 characters.");
}
[Fact]
public void Validate_EmptyDescription_HasErrorForDescription()
{
CreateBreweryCommand command = ValidCommand() with { Description = "" };
TestValidationResult<CreateBreweryCommand> result = _validator.TestValidate(command);
result
.ShouldHaveValidationErrorFor(x => x.Description)
.WithErrorMessage("Description is required.");
}
[Fact]
public void Validate_DescriptionTooLong_HasErrorForDescription()
{
CreateBreweryCommand command = ValidCommand() with { Description = new string('a', 513) };
TestValidationResult<CreateBreweryCommand> result = _validator.TestValidate(command);
result
.ShouldHaveValidationErrorFor(x => x.Description)
.WithErrorMessage("Description cannot exceed 512 characters.");
}
[Fact]
public void Validate_NullLocation_HasErrorForLocationOnly()
{
CreateBreweryCommand command = ValidCommand() with { Location = null! };
TestValidationResult<CreateBreweryCommand> result = _validator.TestValidate(command);
result.ShouldHaveValidationErrorFor(x => x.Location).WithErrorMessage("Location is required.");
result.ShouldNotHaveValidationErrorFor("Location.CityId");
result.ShouldNotHaveValidationErrorFor("Location.AddressLine1");
result.ShouldNotHaveValidationErrorFor("Location.PostalCode");
}
[Fact]
public void Validate_EmptyCityId_HasErrorForCityId()
{
CreateBreweryCommand command = ValidCommand() with
{
Location = ValidLocation() with { CityId = Guid.Empty }
};
TestValidationResult<CreateBreweryCommand> result = _validator.TestValidate(command);
result
.ShouldHaveValidationErrorFor(x => x.Location.CityId)
.WithErrorMessage("CityId is required.");
}
[Fact]
public void Validate_EmptyAddressLine1_HasErrorForAddressLine1()
{
CreateBreweryCommand command = ValidCommand() with
{
Location = ValidLocation() with { AddressLine1 = "" }
};
TestValidationResult<CreateBreweryCommand> result = _validator.TestValidate(command);
result
.ShouldHaveValidationErrorFor(x => x.Location.AddressLine1)
.WithErrorMessage("Address line 1 is required.");
}
[Fact]
public void Validate_AddressLine1TooLong_HasErrorForAddressLine1()
{
CreateBreweryCommand command = ValidCommand() with
{
Location = ValidLocation() with { AddressLine1 = new string('a', 257) }
};
TestValidationResult<CreateBreweryCommand> result = _validator.TestValidate(command);
result
.ShouldHaveValidationErrorFor(x => x.Location.AddressLine1)
.WithErrorMessage("Address line 1 cannot exceed 256 characters.");
}
[Fact]
public void Validate_EmptyPostalCode_HasErrorForPostalCode()
{
CreateBreweryCommand command = ValidCommand() with
{
Location = ValidLocation() with { PostalCode = "" }
};
TestValidationResult<CreateBreweryCommand> result = _validator.TestValidate(command);
result
.ShouldHaveValidationErrorFor(x => x.Location.PostalCode)
.WithErrorMessage("Postal code is required.");
}
[Fact]
public void Validate_PostalCodeTooLong_HasErrorForPostalCode()
{
CreateBreweryCommand command = ValidCommand() with
{
Location = ValidLocation() with { PostalCode = new string('1', 21) }
};
TestValidationResult<CreateBreweryCommand> result = _validator.TestValidate(command);
result
.ShouldHaveValidationErrorFor(x => x.Location.PostalCode)
.WithErrorMessage("Postal code cannot exceed 20 characters.");
}
}

View File

@@ -0,0 +1,32 @@
using Features.Breweries.Commands.UpdateBrewery;
using FluentValidation.TestHelper;
namespace Features.Breweries.Tests.Commands;
public class UpdateBreweryValidatorTests
{
private readonly UpdateBreweryValidator _validator = new();
private static UpdateBreweryCommand ValidCommand() =>
new(Guid.NewGuid(), Guid.NewGuid(), [0x01, 0x02], "Name", "Description", null);
[Fact]
public void Validate_ValidCommand_HasNoValidationErrors()
{
TestValidationResult<UpdateBreweryCommand> result = _validator.TestValidate(ValidCommand());
result.ShouldNotHaveAnyValidationErrors();
}
[Fact]
public void Validate_EmptyRowVersion_HasErrorForRowVersion()
{
UpdateBreweryCommand command = ValidCommand() with { RowVersion = [] };
TestValidationResult<UpdateBreweryCommand> result = _validator.TestValidate(command);
result
.ShouldHaveValidationErrorFor(x => x.RowVersion)
.WithErrorMessage("RowVersion is required to detect conflicting concurrent updates.");
}
}

View File

@@ -8,18 +8,19 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="FluentAssertions" Version="7.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0.1"/>
<PackageReference Include="xunit" Version="2.9.2"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2"/>
<PackageReference Include="Moq" Version="4.20.72"/>
<PackageReference Include="FluentAssertions" Version="7.2.0"/>
<PackageReference Include="FluentValidation" Version="11.3.0"/>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
<Using Include="Xunit"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Features.Breweries\Features.Breweries.csproj" />
<ProjectReference Include="..\Features.Breweries\Features.Breweries.csproj"/>
</ItemGroup>
</Project>

Some files were not shown because too many files have changed in this diff Show More