Skip to content

Build your first feature: ownership

Chapter 2 of 3. Give each project an owner. Signed-out callers will be rejected, and each account will be able to read and change only its own projects. You will verify those rules through use-case and HTTP tests before adding screens in 3. Connect the UI.

Before you start

Finish the checkpoint in 1. Build the API: descriptions are stored in SQLite and the app checks pass. Continue in that app directory with the same database and rows. Keep the starter's authentication setup. Do not rerun the Projects generator over your changes.

Work through every explorer below in order. Choose each file to review its changes or copy its complete source. Types and tests can fail while the ownership changes are incomplete; run the full checks after updating the schemas, adapters, policies, use cases, and tests.

FilesChange
features/projects/schemas.ts and infra/db/schema/projects.tsAdd the owner field
features/projects/ports.ts and infra/projects/*-project-repository.tsAssign owners and filter lists
features/projects/policy.ts, ports/index.ts, and infra/port-wiring.tsDefine and register the ownership rule
features/projects/use-cases/ and contracts.tsEnforce identity and declare authorization errors
features/projects/tests/Verify access through both adapters and HTTP
drizzle/Generate and apply the owner-column migration

Give projects an owner

Format the files and organize imports from the previous chapter before applying these edits:

bash
bunx @biomejs/biome check --write .

Authentication identifies the signed-in user. Authorization decides what that user may do. The starter already supplies the session; you will use it to assign ownership and enforce access.

Clients send a name and description. The server chooses the owner from the session, so clients cannot assign or transfer ownership.

CallerListRead, update, or delete an existing project
Signed out401401
OwnerTheir own projectsAllowed
Another userTheir own projects403

This tutorial returns 403 for a known project owned by someone else and 404 for a missing ID. The 403 response contains no project fields, but the different status lets callers distinguish an existing ID from a missing one. Use the same 404 for both cases if your product needs to hide existence.

Add userId to the response schema and database table. It is nullable because projects created while trying the API do not have owners yet. Those old rows stay in the database, appear in nobody's list, and fail ownership checks. New projects always get the signed-in user's ID. Assigning legacy rows to accounts would be a separate, deliberate data migration.

Also finish support for editing descriptions before building the UI. Add an optional description to the update body. Omitting it preserves the stored description; sending an empty string clears its text.

Return the owner ID and accept description edits.

Pass ownership through the port

NewProject is an internal repository input. The HTTP create schema still has no userId. The list method requires the user's ID separately from client-supplied filters, so the repository filters by owner before applying pagination.

features/projects/ports.ts
Require an owner when creating projects and filtering lists.

Update both implementations of that port. Keep the generated cursor, sort, and version checks; add ownership to create and list, and description to update.

Save owners, filter before pagination, and persist description edits in SQLite.

Define the ownership rule

Replace the generated features/projects/policy.ts with this ownership policy:

features/projects/policy.ts
Allow access only when the signed-in user owns the project. Replace the generated policy with this file.

Register the policy in both the gate's type and runtime configuration. Keep the existing todo policy and the gate's onDeny handler, which maps denied decisions to the app's Forbidden catalog error.

The type tells TypeScript which abilities the app can call. Runtime registration gives the gate the policy to evaluate when a use case calls ctx.gate.authorize("projects.access", project).

Add the project policy to the app's gate types.

Enforce it in every use case

Require a session inside all five use cases, so direct calls from scripts or tests have the same requirement as HTTP calls. requireUserId(ctx) throws a framework 401 when there is no session.

Create attaches that ID to the repository input. List passes it to the owner filter. Read, update, and delete load the project and authorize access before returning fields or writing anything. Update checks ownership before reporting version conflicts.

Assign the signed-in user's ID when creating a project.

Declare the authentication requirement and expected errors on the contract group:

features/projects/contracts.ts
Describe the authentication requirement and expected errors for all Projects routes.

The existing route group and server/routes.ts registrations stay in place. The authenticated Next layout protects the screens; the use cases protect the data even when someone calls the API directly.

The metadata describes the authentication requirement. The requireUserId and gate calls inside the use cases enforce it, including outside HTTP.

Verify access before adding UI

The generated CRUD test used anonymous callers. Give its seed rows an owner, provide a signed-in session, and use the real registered gate. Keep its existing CRUD, pagination, conflict, and route assertions.

features/projects/tests/projects.test.ts
Give seed rows an owner, provide a signed-in session, and use the registered gate.

Add features/projects/tests/access.test.ts. It runs the access checks against both the in-memory adapter and a temporary SQLite database created from your checked-in migrations. It also calls HTTP routes so a route cannot accidentally skip the use-case rules.

features/projects/tests/access.test.ts
Test anonymous callers, another account, and the owner against memory and SQLite adapters.

Apply the migration and run the tests

The access tests use your migrations to create their temporary SQLite database. Generate the owner-column migration before running them, and apply it to your local app database too:

bash
bun beignet db generate
bun beignet db migrate
bun beignet db status
bun run format
bun run test
bun run typecheck

Expect both memory project ownership and sqlite project ownership to pass, along with the existing tests. They cover these outcomes:

ActionExpected result
Owner creates, lists, reads, updates, or deletes a projectAllowed
Another account lists projectsThe owner's project is absent
Another account reads, updates, or deletes the owner's projectFORBIDDEN; stored data is unchanged
A signed-out caller uses a Projects operationUNAUTHORIZED
Owner saves with an outdated versionPROJECT_CONFLICT

If a test reports a missing user_id column, check the generated migration. If TypeScript does not recognize projects.access, check both policy entries in ports/index.ts and the registration in infra/port-wiring.ts.

Checkpoint: an authorized feature

Run the complete app checks:

bash
bun beignet check

The access tests cover the rules above, and the app checks should pass. You can also repeat the terminal list request from chapter one while the app is running:

bash
curl -s -i http://localhost:3000/api/projects

Expect 401 with code UNAUTHORIZED: this terminal request has no session cookie, even if you are signed in through the browser. The unowned records from chapter one stay in the database but appear in nobody's list.

Keep working in this app. Next, 3. Connect the UI adds screens that send requests with the browser's session and lets you try these rules with two accounts.