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.
| Files | Change |
|---|---|
features/projects/schemas.ts and infra/db/schema/projects.ts | Add the owner field |
features/projects/ports.ts and infra/projects/*-project-repository.ts | Assign owners and filter lists |
features/projects/policy.ts, ports/index.ts, and infra/port-wiring.ts | Define and register the ownership rule |
features/projects/use-cases/ and contracts.ts | Enforce 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:
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.
| Caller | List | Read, update, or delete an existing project |
|---|---|---|
| Signed out | 401 | 401 |
| Owner | Their own projects | Allowed |
| Another user | Their own projects | 403 |
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.
4 unmodified lines5678997 unmodified lines1071081091101114 unmodified lines name: z.string().min(1), description: z.string().nullable(), userId: z.string().nullable(), version: z.number().int().min(1), createdAt: z.string().datetime(),97 unmodified linesexport const UpdateProjectBodySchema = z.object({ name: z.string().trim().min(1).max(120), description: z.string().max(500).optional(), version: z.number().int().min(1),});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.
21 unmodified lines222324252625262728293021 unmodified lines};
export type NewProject = CreateProjectInput & { userId: string };
export interface ProjectRepository { list(query: ListProjectsQuery): Promise<ListProjectsResult>; create(input: CreateProjectInput): Promise<Project>; list(query: ListProjectsQuery, userId: string): Promise<ListProjectsResult>; create(input: NewProject): Promise<Project>; findById(id: string): Promise<Project | null>; update(input: UpdateProjectInput): Promise<Project | null>;Update both implementations of that port. Keep the generated cursor, sort, and version checks; add ownership to create and list, and description to update.
18 unmodified lines192021222327 unmodified lines515252535354555657585926 unmodified lines868784858889909118 unmodified lines11011111211311422 unmodified lines13713813914014118 unmodified lines name: row.name, description: row.description, userId: row.userId, version: row.version, createdAt: row.createdAt,27 unmodified lines}
function projectListWhere(query: ListProjectsQuery): SQL<unknown> | undefined { const filters: SQL<unknown>[] = [];function projectListWhere( query: ListProjectsQuery, userId: string,): SQL<unknown> | undefined { const filters: SQL<unknown>[] = [eq(schema.projects.userId, userId)]; const cursor = projectCursorFilter(query);
26 unmodified lines): ProjectRepository { return { async list(query) { const where = projectListWhere(query); async list(query, userId) { const where = projectListWhere(query, userId); const rows = await db .select()18 unmodified lines name: input.name, description: input.description ?? null, userId: input.userId, version: 1, createdAt: now,22 unmodified lines .set({ name: input.name, description: input.description, version: input.version + 1, updatedAt: new Date().toISOString(),Define the ownership rule
Replace the generated features/projects/policy.ts with this ownership policy:
1234567891011import { definePolicy, deny } from "@beignet/core/ports";import type { AuthSession } from "@/ports/auth";import type { Project } from "./schemas";
export const projectPolicy = definePolicy({ "projects.access": (ctx: { auth: AuthSession | null }, project: Project) => { if (ctx.auth && project.userId === ctx.auth.user.id) return true; return deny("Only the owner can access this project."); },});
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).
6 unmodified lines78910117 unmodified lines1920202122232425252627282930316 unmodified lines UnitOfWorkPort,} from "@beignet/core/ports";import type { projectPolicy } from "@/features/projects/policy";import type { AuthorizationContext, todoPolicy } from "@/features/todos/policy";import type { TodoRepository } from "@/features/todos/ports";7 unmodified lines};
export type AppGate = BoundGate<[typeof todoPolicy]>;export type AppGate = BoundGate<[typeof todoPolicy, typeof projectPolicy]>;
export type AppPorts = { auth: AuthPort; errorReporter: ErrorReporterPort; gate: GatePort<AuthorizationContext, [typeof todoPolicy]>; gate: GatePort< AuthorizationContext, [typeof todoPolicy, typeof projectPolicy] >; idempotency: IdempotencyPort; logger: LoggerPort;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.
12344 unmodified lines9101110121314import "@beignet/core/server-only";import { requireUserId } from "@beignet/core/ports";import { useCase } from "../../../lib/use-case";import { CreateProjectInputSchema, ProjectSchema } from "../schemas";4 unmodified lines .output(ProjectSchema) .run(async ({ ctx, input }) => { const userId = requireUserId(ctx); const project = await ctx.ports.projects.create(input); const project = await ctx.ports.projects.create({ ...input, userId });
return project;Declare the authentication requirement and expected errors on the contract group:
20 unmodified lines212223242526232425272829303120 unmodified lines});
const projects = defineContractGroup() .namespace("projects") .meta({ auth: "required" }) .errors({ Unauthorized: errors.Unauthorized, Forbidden: errors.Forbidden })const projects = defineContractGroup().namespace("projects").responses({ 500: ErrorResponseSchema,}); .responses({ 500: ErrorResponseSchema, });
export const listProjects = projectsThe 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.
2 unmodified lines3455678927 unmodified lines37383940414 unmodified lines46474849504 unmodified lines55565758596 unmodified lines66676869667071727374757677787912 unmodified lines9282931 unmodified line95969798992 unmodified linesimport { defineRoutes } from "@beignet/core/server";import { createTestAnonymousActor, createTestContextFactory, createTestPorts, createTestUserActor,} from "@beignet/core/testing";import { createInMemoryDevtools } from "@beignet/devtools";27 unmodified lines name: "Alpha Project", description: null, userId: "user_test", version: 1, createdAt: "2024-01-01T00:00:00.000Z",4 unmodified lines name: "Beta Project", description: null, userId: "user_test", version: 1, createdAt: "2024-01-02T00:00:00.000Z",4 unmodified lines name: "Gamma Project", description: null, userId: "user_test", version: 1, createdAt: "2024-01-03T00:00:00.000Z",6 unmodified lines overrides: { projects, gate: initialPorts.gate, auth: { getSession: async () => null, getSession: async () => ({ user: { id: "user_test", name: "Test User", email: "test@example.com", }, session: { id: "session_test" }, }), }, devtools: createInMemoryDevtools(),12 unmodified lines ports: testFixture.ports, actor: createTestAnonymousActor(), actor: createTestUserActor("user_test"),1 unmodified line auth: await testFixture.ports.auth.getSession( new Request("http://localhost"), ), }); const tester = createUseCaseTester<AppContext>(createTestContext);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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162import { createStaticAuth } from "@beignet/core/ports";import { defineRoutes } from "@beignet/core/server";import { createTestAnonymousActor, createTestContextFactory, createTestPorts, createTestUserActor,} from "@beignet/core/testing";import { createInMemoryDevtools } from "@beignet/devtools";import { createTestApp } from "@beignet/web/testing";import type { AppContext } from "@/app-context";import { createTestDatabase } from "@/infra/db/test-database";import { initialPorts } from "@/infra/port-wiring";import { createInMemoryProjectRepository } from "@/infra/projects/in-memory-project-repository";import { describe, expect, it } from "@/lib/beignet-test";import type { AuthRequest, AuthSessionMetadata, AuthUser } from "@/ports/auth";import { appContext } from "@/server/context";import { createProject, deleteProject, getProject, listProjects, updateProject,} from "../contracts";import type { ProjectRepository } from "../ports";import { projectRoutes } from "../routes";import { createProjectUseCase, deleteProjectUseCase, getProjectUseCase, listProjectsUseCase, updateProjectUseCase,} from "../use-cases";
async function userContext(projects: ProjectRepository, userId: string | null) { const auth = userId ? { user: { id: userId, name: userId, email: `${userId}@example.com` }, session: { id: `session_${userId}` }, } : null; const fixture = createTestPorts<AppContext["ports"]>({ base: initialPorts, overrides: { projects, gate: initialPorts.gate, auth: createStaticAuth<AuthUser, AuthSessionMetadata, AuthRequest>(auth), devtools: createInMemoryDevtools(), }, }); return createTestContextFactory<AppContext, AppContext["ports"]>({ ports: fixture.ports, auth, actor: userId ? createTestUserActor(userId) : createTestAnonymousActor(), })();}
for (const adapter of ["memory", "sqlite"]) { describe(`${adapter} project ownership`, () => { it("protects reads and writes through use cases and HTTP", async () => { const database = adapter === "sqlite" ? await createTestDatabase() : undefined; const projects = database?.repositories.projects ?? createInMemoryProjectRepository(); try { const alice = await userContext(projects, "alice"); const bob = await userContext(projects, "bob"); const anonymous = await userContext(projects, null); const project = await createProjectUseCase.run({ ctx: alice, input: { name: "Private", description: "Alice's project" }, }); expect(project.userId).toBe("alice"); expect( (await listProjectsUseCase.run({ ctx: alice, input: {} })).items, ).toEqual([project]); expect( (await listProjectsUseCase.run({ ctx: bob, input: {} })).items, ).toEqual([]); await expect( createProjectUseCase.run({ ctx: anonymous, input: { name: "Anonymous" }, }), ).rejects.toMatchObject({ code: "UNAUTHORIZED" }); await expect( listProjectsUseCase.run({ ctx: anonymous, input: {} }), ).rejects.toMatchObject({ code: "UNAUTHORIZED" }); await expect( getProjectUseCase.run({ ctx: bob, input: { id: project.id } }), ).rejects.toMatchObject({ code: "FORBIDDEN" }); await expect( updateProjectUseCase.run({ ctx: bob, input: { id: project.id, name: "Stolen", version: project.version }, }), ).rejects.toMatchObject({ code: "FORBIDDEN" }); await expect( deleteProjectUseCase.run({ ctx: bob, input: { id: project.id } }), ).rejects.toMatchObject({ code: "FORBIDDEN" }); expect(await projects.findById(project.id)).toEqual(project); const saved = await updateProjectUseCase.run({ ctx: alice, input: { id: project.id, name: "Updated", description: "Saved", version: project.version, }, }); expect(saved.description).toBe("Saved"); await expect( updateProjectUseCase.run({ ctx: alice, input: { id: project.id, name: "Stale", version: project.version }, }), ).rejects.toMatchObject({ code: "PROJECT_CONFLICT" });
for (const ctx of [bob, anonymous]) { const app = await createTestApp({ ports: ctx.ports, context: appContext, routes: defineRoutes<AppContext>([projectRoutes]), }); try { const code = ctx.auth ? "FORBIDDEN" : "UNAUTHORIZED"; await expect( app.request(getProject, { path: { id: project.id } }), ).rejects.toMatchObject({ code }); await expect( app.request(updateProject, { path: { id: project.id }, body: { name: "Blocked", version: saved.version }, }), ).rejects.toMatchObject({ code }); await expect( app.request(deleteProject, { path: { id: project.id } }), ).rejects.toMatchObject({ code }); if (!ctx.auth) { await expect( app.request(listProjects, { query: {} }), ).rejects.toMatchObject({ code }); await expect( app.request(createProject, { body: { name: "Blocked" } }), ).rejects.toMatchObject({ code }); } } finally { await app.stop(); } } await deleteProjectUseCase.run({ ctx: alice, input: { id: project.id }, }); expect(await projects.findById(project.id)).toBeNull(); } finally { await database?.close(); } }); });}
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:
bun beignet db generate
bun beignet db migrate
bun beignet db status
bun run format
bun run test
bun run typecheckExpect both memory project ownership and sqlite project ownership to pass,
along with the existing tests. They cover these outcomes:
| Action | Expected result |
|---|---|
| Owner creates, lists, reads, updates, or deletes a project | Allowed |
| Another account lists projects | The owner's project is absent |
| Another account reads, updates, or deletes the owner's project | FORBIDDEN; stored data is unchanged |
| A signed-out caller uses a Projects operation | UNAUTHORIZED |
| Owner saves with an outdated version | PROJECT_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:
bun beignet checkThe 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:
curl -s -i http://localhost:3000/api/projectsExpect 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.