From 0ee1fc2e126dd6fac0313d4bd16a1efdb489a728 Mon Sep 17 00:00:00 2001 From: Hasan Mohammad Fawzi Date: Thu, 8 Oct 2026 14:33:37 +0200 Subject: [PATCH 1/4] feat(auth): add database authentication and persistent sessions --- apps/api/migrations/0001_familiar_shocker.sql | 16 + apps/api/migrations/meta/0001_snapshot.json | 149 ++++++++ apps/api/migrations/meta/_journal.json | 7 + apps/api/package.json | 3 +- apps/api/src/app.ts | 12 +- apps/api/src/db/schema.ts | 30 +- apps/api/src/features/auth/authRepository.ts | 141 ++++++++ apps/api/src/features/auth/authResolvers.ts | 30 ++ .../api/src/features/auth/authService.test.ts | 144 ++++++++ apps/api/src/features/auth/authService.ts | 133 ++++++++ apps/api/src/generated.ts | 108 +++++- apps/api/src/schema.graphql | 18 + apps/web/src/App.tsx | 9 + .../shell/SiteHeader/SiteHeader.test.tsx | 117 +++++++ .../shell/SiteHeader/SiteHeader.tsx | 4 +- apps/web/src/features/auth/AuthPages.test.tsx | 95 +++++- apps/web/src/features/auth/LoginPage.tsx | 4 +- apps/web/src/features/auth/RegisterPage.tsx | 4 +- apps/web/src/features/auth/authApi.ts | 160 +++++++++ apps/web/src/store.test.ts | 93 +++++ apps/web/src/store.ts | 86 +++-- contracts/generated.ts | 321 ++++++++++++++++++ contracts/operations.graphql | 30 ++ package-lock.json | 75 +++- 24 files changed, 1740 insertions(+), 49 deletions(-) create mode 100644 apps/api/migrations/0001_familiar_shocker.sql create mode 100644 apps/api/migrations/meta/0001_snapshot.json create mode 100644 apps/api/src/features/auth/authRepository.ts create mode 100644 apps/api/src/features/auth/authResolvers.ts create mode 100644 apps/api/src/features/auth/authService.test.ts create mode 100644 apps/api/src/features/auth/authService.ts create mode 100644 apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx create mode 100644 apps/web/src/features/auth/authApi.ts create mode 100644 apps/web/src/store.test.ts diff --git a/apps/api/migrations/0001_familiar_shocker.sql b/apps/api/migrations/0001_familiar_shocker.sql new file mode 100644 index 0000000..a46fbef --- /dev/null +++ b/apps/api/migrations/0001_familiar_shocker.sql @@ -0,0 +1,16 @@ +CREATE TABLE "project2"."sessions" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "user_id" uuid NOT NULL, + "expires_at" timestamp with time zone NOT NULL +); +--> statement-breakpoint +CREATE TABLE "project2"."users" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "name" text NOT NULL, + "email" text NOT NULL, + "password_hash" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "project2"."sessions" ADD CONSTRAINT "sessions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "project2"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "users_email_unique" ON "project2"."users" USING btree ("email"); \ No newline at end of file diff --git a/apps/api/migrations/meta/0001_snapshot.json b/apps/api/migrations/meta/0001_snapshot.json new file mode 100644 index 0000000..dd8ec84 --- /dev/null +++ b/apps/api/migrations/meta/0001_snapshot.json @@ -0,0 +1,149 @@ +{ + "id": "8106c561-4f83-4ec4-9119-840e77bd557d", + "prevId": "fa9889d1-8b19-437d-8360-333cd24d5aea", + "version": "7", + "dialect": "postgresql", + "tables": { + "project2.recipes": { + "name": "recipes", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.sessions": { + "name": "sessions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.users": { + "name": "users", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/apps/api/migrations/meta/_journal.json b/apps/api/migrations/meta/_journal.json index 5e9ab2c..ebc2b8a 100644 --- a/apps/api/migrations/meta/_journal.json +++ b/apps/api/migrations/meta/_journal.json @@ -8,6 +8,13 @@ "when": 1790582041612, "tag": "0000_glorious_squadron_sinister", "breakpoints": true + }, + { + "idx": 1, + "version": "7", + "when": 1791418622259, + "tag": "0001_familiar_shocker", + "breakpoints": true } ] } diff --git a/apps/api/package.json b/apps/api/package.json index 0869dd7..8755d13 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -3,11 +3,12 @@ "private": true, "type": "module", "scripts": { - "dev": "tsx --env-file-if-exists=../../.env watch src/server.ts", + "dev": "tsx watch --env-file-if-exists=../../.env src/server.ts", "build": "tsc && cp src/schema.graphql dist/schema.graphql", "start": "node --env-file-if-exists=../../.env dist/server.js" }, "dependencies": { + "argon2": "0.45.1", "drizzle-orm": "0.45.2", "graphql": "16.12.0", "graphql-yoga": "5.16.2", diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 1100b34..0294e69 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -1,6 +1,8 @@ import { readFileSync } from 'node:fs'; import { createSchema, createYoga } from 'graphql-yoga'; + import type { Resolvers } from './generated.js'; +import { authResolvers } from './features/auth/authResolvers.js'; export const app = createYoga({ schema: createSchema({ @@ -8,7 +10,15 @@ export const app = createYoga({ new URL('./schema.graphql', import.meta.url), 'utf8', ), - resolvers: { Query: { health: () => 'ok' } } satisfies Resolvers, + resolvers: { + Query: { + health: () => 'ok', + ...authResolvers.Query, + }, + Mutation: { + ...authResolvers.Mutation, + }, + } satisfies Resolvers, }), graphqlEndpoint: '/graphql', }); diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts index 5c8837c..01f90f1 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -1,4 +1,10 @@ -import { pgSchema, text, uuid } from 'drizzle-orm/pg-core'; +import { + pgSchema, + text, + timestamp, + uniqueIndex, + uuid, +} from 'drizzle-orm/pg-core'; const project2 = pgSchema('project2'); @@ -6,3 +12,25 @@ export const recipes = project2.table('recipes', { id: uuid().primaryKey().defaultRandom(), title: text().notNull(), }); + +export const users = project2.table( + 'users', + { + id: uuid().primaryKey().defaultRandom(), + name: text().notNull(), + email: text().notNull(), + passwordHash: text('password_hash').notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [uniqueIndex('users_email_unique').on(table.email)], +); + +export const sessions = project2.table('sessions', { + id: uuid().primaryKey().defaultRandom(), + userId: uuid('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(), +}); diff --git a/apps/api/src/features/auth/authRepository.ts b/apps/api/src/features/auth/authRepository.ts new file mode 100644 index 0000000..2fcda81 --- /dev/null +++ b/apps/api/src/features/auth/authRepository.ts @@ -0,0 +1,141 @@ +import type { Pool } from 'pg'; + +import { db } from '../../db/client.js'; + +export interface AuthUserRecord { + id: string; + name: string; + email: string; + passwordHash: string; +} + +export interface PublicUser { + id: string; + name: string; + email: string; +} + +interface UserRow { + id: string; + name: string; + email: string; + password_hash: string; +} + +interface SessionUserRow { + id: string; + name: string; + email: string; +} + +export interface AuthRepository { + findUserByEmail(email: string): Promise; + + createUser( + name: string, + email: string, + passwordHash: string, + ): Promise; + + createSession(userId: string, expiresAt: Date): Promise; + + findUserBySession(sessionToken: string): Promise; + + deleteSession(sessionToken: string): Promise; +} + +export function createAuthRepository(pool: Pool = db): AuthRepository { + return { + async findUserByEmail(email) { + const result = await pool.query( + ` + SELECT id, name, email, password_hash + FROM project2.users + WHERE email = $1 + LIMIT 1 + `, + [email], + ); + + const user = result.rows[0]; + + if (!user) { + return null; + } + + return { + id: user.id, + name: user.name, + email: user.email, + passwordHash: user.password_hash, + }; + }, + + async createUser(name, email, passwordHash) { + const result = await pool.query( + ` + INSERT INTO project2.users (name, email, password_hash) + VALUES ($1, $2, $3) + RETURNING id, name, email + `, + [name, email, passwordHash], + ); + + const user = result.rows[0]; + + if (!user) { + throw new Error('User could not be created.'); + } + + return user; + }, + + async createSession(userId, expiresAt) { + const result = await pool.query<{ id: string }>( + ` + INSERT INTO project2.sessions (user_id, expires_at) + VALUES ($1, $2) + RETURNING id + `, + [userId, expiresAt], + ); + + const session = result.rows[0]; + + if (!session) { + throw new Error('Session could not be created.'); + } + + return session.id; + }, + + async findUserBySession(sessionToken) { + const result = await pool.query( + ` + SELECT users.id, users.name, users.email + FROM project2.sessions AS sessions + JOIN project2.users AS users + ON users.id = sessions.user_id + WHERE sessions.id = $1 + AND sessions.expires_at > now() + LIMIT 1 + `, + [sessionToken], + ); + + return result.rows[0] ?? null; + }, + + async deleteSession(sessionToken) { + await pool.query( + ` + DELETE FROM project2.sessions + WHERE id = $1 + `, + [sessionToken], + ); + }, + }; +} + +export const authRepository = createAuthRepository(); diff --git a/apps/api/src/features/auth/authResolvers.ts b/apps/api/src/features/auth/authResolvers.ts new file mode 100644 index 0000000..97452d0 --- /dev/null +++ b/apps/api/src/features/auth/authResolvers.ts @@ -0,0 +1,30 @@ +import { authService } from './authService.js'; + +export const authResolvers = { + Query: { + currentUser: (_parent: unknown, args: { sessionToken: string }) => + authService.currentUser(args.sessionToken), + }, + + Mutation: { + register: ( + _parent: unknown, + args: { + name: string; + email: string; + password: string; + }, + ) => authService.register(args.name, args.email, args.password), + + login: ( + _parent: unknown, + args: { + email: string; + password: string; + }, + ) => authService.login(args.email, args.password), + + signOut: (_parent: unknown, args: { sessionToken: string }) => + authService.signOut(args.sessionToken), + }, +}; diff --git a/apps/api/src/features/auth/authService.test.ts b/apps/api/src/features/auth/authService.test.ts new file mode 100644 index 0000000..ede6527 --- /dev/null +++ b/apps/api/src/features/auth/authService.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { createAuthService, type PasswordHasher } from './authService.js'; + +import type { + AuthRepository, + AuthUserRecord, + PublicUser, +} from './authRepository.js'; + +const publicUser: PublicUser = { + id: 'user-123', + name: 'Hasan', + email: 'hasan@example.com', +}; + +const storedUser: AuthUserRecord = { + ...publicUser, + passwordHash: 'hashed:secret123', +}; + +function createRepository( + overrides: Partial = {}, +): AuthRepository { + return { + findUserByEmail: vi.fn(async () => null), + createUser: vi.fn(async () => publicUser), + createSession: vi.fn(async () => 'session-123'), + findUserBySession: vi.fn(async () => null), + deleteSession: vi.fn(async () => undefined), + ...overrides, + }; +} + +function createPasswordHasher(): PasswordHasher { + return { + hash: vi.fn(async (password) => `hashed:${password}`), + + verify: vi.fn( + async (passwordHash, password) => passwordHash === `hashed:${password}`, + ), + }; +} + +describe('authService', () => { + it('registers a user and returns a session', async () => { + const repository = createRepository(); + const passwordHasher = createPasswordHasher(); + + const service = createAuthService(repository, passwordHasher); + + const result = await service.register( + ' Hasan ', + ' HASAN@EXAMPLE.COM ', + 'secret123', + ); + + expect(result).toEqual({ + user: publicUser, + sessionToken: 'session-123', + }); + + expect(repository.createUser).toHaveBeenCalledWith( + 'Hasan', + 'hasan@example.com', + 'hashed:secret123', + ); + + expect(repository.createSession).toHaveBeenCalledWith( + publicUser.id, + expect.any(Date), + ); + }); + + it('rejects registration when the email already exists', async () => { + const repository = createRepository({ + findUserByEmail: vi.fn(async () => storedUser), + }); + + const service = createAuthService(repository, createPasswordHasher()); + + await expect( + service.register('Hasan', 'hasan@example.com', 'secret123'), + ).rejects.toThrow('An account with this email already exists.'); + + expect(repository.createUser).not.toHaveBeenCalled(); + expect(repository.createSession).not.toHaveBeenCalled(); + }); + + it('logs in with the correct password', async () => { + const repository = createRepository({ + findUserByEmail: vi.fn(async () => storedUser), + }); + + const service = createAuthService(repository, createPasswordHasher()); + + const result = await service.login('HASAN@EXAMPLE.COM', 'secret123'); + + expect(result).toEqual({ + user: publicUser, + sessionToken: 'session-123', + }); + + expect(repository.createSession).toHaveBeenCalled(); + }); + + it('rejects login with an incorrect password', async () => { + const repository = createRepository({ + findUserByEmail: vi.fn(async () => storedUser), + }); + + const service = createAuthService(repository, createPasswordHasher()); + + await expect( + service.login('hasan@example.com', 'wrong-password'), + ).rejects.toThrow('Invalid email or password.'); + + expect(repository.createSession).not.toHaveBeenCalled(); + }); + + it('restores the current user from a session', async () => { + const repository = createRepository({ + findUserBySession: vi.fn(async () => publicUser), + }); + + const service = createAuthService(repository, createPasswordHasher()); + + await expect(service.currentUser('session-123')).resolves.toEqual( + publicUser, + ); + + expect(repository.findUserBySession).toHaveBeenCalledWith('session-123'); + }); + + it('deletes the session when signing out', async () => { + const repository = createRepository(); + + const service = createAuthService(repository, createPasswordHasher()); + + await expect(service.signOut('session-123')).resolves.toBe(true); + + expect(repository.deleteSession).toHaveBeenCalledWith('session-123'); + }); +}); diff --git a/apps/api/src/features/auth/authService.ts b/apps/api/src/features/auth/authService.ts new file mode 100644 index 0000000..d2a437a --- /dev/null +++ b/apps/api/src/features/auth/authService.ts @@ -0,0 +1,133 @@ +import { hash, verify } from 'argon2'; + +import { + authRepository, + type AuthRepository, + type PublicUser, +} from './authRepository.js'; + +const SESSION_DURATION_MS = 7 * 24 * 60 * 60 * 1000; + +export interface AuthPayload { + user: PublicUser; + sessionToken: string; +} + +export interface PasswordHasher { + hash(password: string): Promise; + verify(passwordHash: string, password: string): Promise; +} + +const argonPasswordHasher: PasswordHasher = { + hash, + verify, +}; + +export interface AuthService { + register(name: string, email: string, password: string): Promise; + + login(email: string, password: string): Promise; + + currentUser(sessionToken: string): Promise; + + signOut(sessionToken: string): Promise; +} + +export function createAuthService( + repository: AuthRepository = authRepository, + passwordHasher: PasswordHasher = argonPasswordHasher, +): AuthService { + return { + async register(name, email, password) { + const normalizedName = name.trim(); + const normalizedEmail = email.trim().toLowerCase(); + + if (normalizedName.length < 2) { + throw new Error('Name must contain at least 2 characters.'); + } + + if (!normalizedEmail.includes('@')) { + throw new Error('Enter a valid email address.'); + } + + if (password.length < 6) { + throw new Error('Password must contain at least 6 characters.'); + } + + const existingUser = await repository.findUserByEmail(normalizedEmail); + + if (existingUser) { + throw new Error('An account with this email already exists.'); + } + + const passwordHash = await passwordHasher.hash(password); + + const user = await repository.createUser( + normalizedName, + normalizedEmail, + passwordHash, + ); + + const expiresAt = new Date(Date.now() + SESSION_DURATION_MS); + + const sessionToken = await repository.createSession(user.id, expiresAt); + + return { + user, + sessionToken, + }; + }, + + async login(email, password) { + const normalizedEmail = email.trim().toLowerCase(); + + const user = await repository.findUserByEmail(normalizedEmail); + + if (!user) { + throw new Error('Invalid email or password.'); + } + + const passwordIsCorrect = await passwordHasher.verify( + user.passwordHash, + password, + ); + + if (!passwordIsCorrect) { + throw new Error('Invalid email or password.'); + } + + const expiresAt = new Date(Date.now() + SESSION_DURATION_MS); + + const sessionToken = await repository.createSession(user.id, expiresAt); + + return { + user: { + id: user.id, + name: user.name, + email: user.email, + }, + sessionToken, + }; + }, + + async currentUser(sessionToken) { + if (!sessionToken.trim()) { + return null; + } + + return repository.findUserBySession(sessionToken); + }, + + async signOut(sessionToken) { + if (!sessionToken.trim()) { + return false; + } + + await repository.deleteSession(sessionToken); + + return true; + }, + }; +} + +export const authService = createAuthService(); diff --git a/apps/api/src/generated.ts b/apps/api/src/generated.ts index f8645bc..8d4e30c 100644 --- a/apps/api/src/generated.ts +++ b/apps/api/src/generated.ts @@ -2,6 +2,9 @@ import type { GraphQLResolveInfo } from 'graphql'; export type Maybe = T | null; export type InputMaybe = Maybe; +export type RequireFields = Omit & { + [P in K]-?: NonNullable; +}; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: { input: string; output: string }; @@ -11,9 +14,49 @@ export type Scalars = { Float: { input: number; output: number }; }; +export type User = { + __typename?: 'User'; + id: Scalars['ID']['output']; + name: Scalars['String']['output']; + email: Scalars['String']['output']; +}; + +export type AuthPayload = { + __typename?: 'AuthPayload'; + user: User; + sessionToken: Scalars['String']['output']; +}; + export type Query = { __typename?: 'Query'; health: Scalars['String']['output']; + currentUser?: Maybe; +}; + +export type QueryCurrentUserArgs = { + sessionToken: Scalars['String']['input']; +}; + +export type Mutation = { + __typename?: 'Mutation'; + register: AuthPayload; + login: AuthPayload; + signOut: Scalars['Boolean']['output']; +}; + +export type MutationRegisterArgs = { + name: Scalars['String']['input']; + email: Scalars['String']['input']; + password: Scalars['String']['input']; +}; + +export type MutationLoginArgs = { + email: Scalars['String']['input']; + password: Scalars['String']['input']; +}; + +export type MutationSignOutArgs = { + sessionToken: Scalars['String']['input']; }; export type ResolverTypeWrapper = Promise | T; @@ -135,26 +178,87 @@ export type DirectiveResolverFn< /** Mapping between all available schema types and the resolvers types */ export type ResolversTypes = { - Query: ResolverTypeWrapper>; + User: ResolverTypeWrapper; + ID: ResolverTypeWrapper; String: ResolverTypeWrapper; + AuthPayload: ResolverTypeWrapper; + Query: ResolverTypeWrapper>; + Mutation: ResolverTypeWrapper>; Boolean: ResolverTypeWrapper; }; /** Mapping between all available schema types and the resolvers parents */ export type ResolversParentTypes = { - Query: Record; + User: User; + ID: Scalars['ID']['output']; String: Scalars['String']['output']; + AuthPayload: AuthPayload; + Query: Record; + Mutation: Record; Boolean: Scalars['Boolean']['output']; }; +export type UserResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['User'] = ResolversParentTypes['User'], +> = { + id?: Resolver; + name?: Resolver; + email?: Resolver; +}; + +export type AuthPayloadResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['AuthPayload'] = ResolversParentTypes['AuthPayload'], +> = { + user?: Resolver; + sessionToken?: Resolver; +}; + export type QueryResolvers< ContextType = any, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query'], > = { health?: Resolver; + currentUser?: Resolver< + Maybe, + ParentType, + ContextType, + RequireFields + >; +}; + +export type MutationResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation'], +> = { + register?: Resolver< + ResolversTypes['AuthPayload'], + ParentType, + ContextType, + RequireFields + >; + login?: Resolver< + ResolversTypes['AuthPayload'], + ParentType, + ContextType, + RequireFields + >; + signOut?: Resolver< + ResolversTypes['Boolean'], + ParentType, + ContextType, + RequireFields + >; }; export type Resolvers = { + User?: UserResolvers; + AuthPayload?: AuthPayloadResolvers; Query?: QueryResolvers; + Mutation?: MutationResolvers; }; diff --git a/apps/api/src/schema.graphql b/apps/api/src/schema.graphql index 6cf08a8..c2cb462 100644 --- a/apps/api/src/schema.graphql +++ b/apps/api/src/schema.graphql @@ -1,3 +1,21 @@ +type User { + id: ID! + name: String! + email: String! +} + +type AuthPayload { + user: User! + sessionToken: String! +} + type Query { health: String! + currentUser(sessionToken: String!): User +} + +type Mutation { + register(name: String!, email: String!, password: String!): AuthPayload! + login(email: String!, password: String!): AuthPayload! + signOut(sessionToken: String!): Boolean! } diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index acd747d..f78990c 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -1,3 +1,6 @@ +import { useEffect } from 'react'; +import { useAppStore } from './store'; + import { Route, Routes } from 'react-router-dom'; import AppShell from './components/shell/AppShell/AppShell'; @@ -14,6 +17,12 @@ const pages = [ ] as const; export function App() { + const restoreSession = useAppStore((state) => state.restoreSession); + + useEffect(() => { + void restoreSession(); + }, [restoreSession]); + return ( }> diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx new file mode 100644 index 0000000..37844c4 --- /dev/null +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx @@ -0,0 +1,117 @@ +import '@testing-library/jest-dom/vitest'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { MemoryRouter } from 'react-router-dom'; + +import { signOutUser } from '../../../features/auth/authApi'; +import { useAppStore } from '../../../store'; +import SiteHeader from './SiteHeader'; + +vi.mock('../../../features/auth/authApi', () => ({ + loginUser: vi.fn(), + registerUser: vi.fn(), + getCurrentUser: vi.fn(), + signOutUser: vi.fn(), +})); + +const authenticatedUser = { + id: 'user-123', + name: 'Hasan', + email: 'hasan@example.com', +}; + +function renderHeader() { + return render( + + + , + ); +} + +describe('SiteHeader authentication', () => { + beforeEach(() => { + vi.clearAllMocks(); + localStorage.clear(); + + useAppStore.setState({ + currentUser: null, + }); + }); + + it('shows login and registration links when signed out', () => { + renderHeader(); + + expect( + screen.getByRole('link', { + name: 'Log in', + }), + ).toBeInTheDocument(); + + expect( + screen.getByRole('link', { + name: 'Register', + }), + ).toBeInTheDocument(); + + expect( + screen.queryByRole('button', { + name: 'Sign out', + }), + ).not.toBeInTheDocument(); + }); + + it('shows the current user when signed in', () => { + useAppStore.setState({ + currentUser: authenticatedUser, + }); + + renderHeader(); + + expect(screen.getByText('Hasan')).toBeInTheDocument(); + + expect( + screen.getByRole('button', { + name: 'Sign out', + }), + ).toBeInTheDocument(); + + expect( + screen.queryByRole('link', { + name: 'Log in', + }), + ).not.toBeInTheDocument(); + }); + + it('updates the header after signing out', async () => { + localStorage.setItem('recipe-platform-session-token', 'session-123'); + + useAppStore.setState({ + currentUser: authenticatedUser, + }); + + vi.mocked(signOutUser).mockResolvedValue(true); + + const user = userEvent.setup(); + + renderHeader(); + + await user.click( + screen.getByRole('button', { + name: 'Sign out', + }), + ); + + await waitFor(() => { + expect( + screen.getByRole('link', { + name: 'Log in', + }), + ).toBeInTheDocument(); + }); + + expect(signOutUser).toHaveBeenCalledWith('session-123'); + + expect(useAppStore.getState().currentUser).toBeNull(); + }); +}); diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx index d32c1b4..639ac08 100644 --- a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx +++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx @@ -28,8 +28,8 @@ function SiteHeader() { const closeMenu = () => setMenuOpen(false); - const handleSignOut = () => { - signOut(); + const handleSignOut = async () => { + await signOut(); closeMenu(); navigate('/'); }; diff --git a/apps/web/src/features/auth/AuthPages.test.tsx b/apps/web/src/features/auth/AuthPages.test.tsx index 61e8628..99c5a9a 100644 --- a/apps/web/src/features/auth/AuthPages.test.tsx +++ b/apps/web/src/features/auth/AuthPages.test.tsx @@ -1,19 +1,35 @@ import '@testing-library/jest-dom/vitest'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { beforeEach, describe, expect, it } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { loginUser, registerUser } from './authApi'; import { useAppStore } from '../../store'; import LoginPage from './LoginPage'; import RegisterPage from './RegisterPage'; +vi.mock('./authApi', () => ({ + loginUser: vi.fn(), + registerUser: vi.fn(), + getCurrentUser: vi.fn(), + signOutUser: vi.fn(), +})); + +const authenticatedUser = { + id: 'user-123', + name: 'Hasan', + email: 'hasan@example.com', +}; + function renderAuthPage(initialEntry: '/login' | '/register') { return render( } /> + } /> + Explore} /> , @@ -22,6 +38,9 @@ function renderAuthPage(initialEntry: '/login' | '/register') { describe('authentication pages', () => { beforeEach(() => { + vi.clearAllMocks(); + localStorage.clear(); + useAppStore.setState({ search: '', currentUser: null, @@ -33,10 +52,16 @@ describe('authentication pages', () => { renderAuthPage('/login'); - await user.click(screen.getByRole('button', { name: 'Log in' })); + await user.click( + screen.getByRole('button', { + name: 'Log in', + }), + ); expect(screen.getByText('Enter your email address.')).toBeInTheDocument(); + expect(screen.getByText('Enter your password.')).toBeInTheDocument(); + expect(screen.getByLabelText(/^Email/)).toHaveAttribute( 'aria-invalid', 'true', @@ -46,29 +71,81 @@ describe('authentication pages', () => { 'aria-invalid', 'true', ); + + expect(loginUser).not.toHaveBeenCalled(); }); - it('registers a mock user and navigates to Explore', async () => { + it('registers a user and navigates to Explore', async () => { + vi.mocked(registerUser).mockResolvedValue({ + user: authenticatedUser, + sessionToken: 'session-123', + }); + const user = userEvent.setup(); renderAuthPage('/register'); await user.type(screen.getByLabelText(/^Name/), 'Hasan'); + await user.type(screen.getByLabelText(/^Email/), 'hasan@example.com'); + await user.type(screen.getByLabelText(/^Password/i), 'secret123'); await user.type(screen.getByLabelText(/^Confirm password/), 'secret123'); - await user.click(screen.getByRole('button', { name: 'Register' })); + await user.click( + screen.getByRole('button', { + name: 'Register', + }), + ); expect( - screen.getByRole('heading', { name: 'Explore' }), + await screen.findByRole('heading', { + name: 'Explore', + }), ).toBeInTheDocument(); - expect(useAppStore.getState().currentUser).toEqual({ - id: 'mock-current-user', - name: 'Hasan', - email: 'hasan@example.com', + expect(registerUser).toHaveBeenCalledWith( + 'Hasan', + 'hasan@example.com', + 'secret123', + ); + + expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); + + expect(localStorage.getItem('recipe-platform-session-token')).toBe( + 'session-123', + ); + }); + + it('logs in and navigates to Explore', async () => { + vi.mocked(loginUser).mockResolvedValue({ + user: authenticatedUser, + sessionToken: 'session-456', }); + + const user = userEvent.setup(); + + renderAuthPage('/login'); + + await user.type(screen.getByLabelText(/^Email/), 'hasan@example.com'); + + await user.type(screen.getByLabelText(/^Password/), 'secret123'); + + await user.click( + screen.getByRole('button', { + name: 'Log in', + }), + ); + + expect( + await screen.findByRole('heading', { + name: 'Explore', + }), + ).toBeInTheDocument(); + + expect(loginUser).toHaveBeenCalledWith('hasan@example.com', 'secret123'); + + expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); }); }); diff --git a/apps/web/src/features/auth/LoginPage.tsx b/apps/web/src/features/auth/LoginPage.tsx index 1bca16d..e5044c2 100644 --- a/apps/web/src/features/auth/LoginPage.tsx +++ b/apps/web/src/features/auth/LoginPage.tsx @@ -19,7 +19,7 @@ function LoginPage() { const [password, setPassword] = useState(''); const [errors, setErrors] = useState({}); - const handleSubmit = (event: FormEvent) => { + const handleSubmit = async (event: FormEvent) => { event.preventDefault(); const nextErrors: LoginErrors = {}; @@ -42,7 +42,7 @@ function LoginPage() { return; } - login(email.trim()); + await login(email.trim(), password); navigate('/'); }; diff --git a/apps/web/src/features/auth/RegisterPage.tsx b/apps/web/src/features/auth/RegisterPage.tsx index 74e9d00..0e651e7 100644 --- a/apps/web/src/features/auth/RegisterPage.tsx +++ b/apps/web/src/features/auth/RegisterPage.tsx @@ -23,7 +23,7 @@ function RegisterPage() { const [confirmPassword, setConfirmPassword] = useState(''); const [errors, setErrors] = useState({}); - const handleSubmit = (event: FormEvent) => { + const handleSubmit = async (event: FormEvent) => { event.preventDefault(); const nextErrors: RegisterErrors = {}; @@ -56,7 +56,7 @@ function RegisterPage() { return; } - register(name.trim(), email.trim()); + await register(name.trim(), email.trim(), password); navigate('/'); }; diff --git a/apps/web/src/features/auth/authApi.ts b/apps/web/src/features/auth/authApi.ts new file mode 100644 index 0000000..a309e1e --- /dev/null +++ b/apps/web/src/features/auth/authApi.ts @@ -0,0 +1,160 @@ +import type { User } from '../../types/user'; + +const GRAPHQL_URL = import.meta.env.DEV ? '/graphql' : '/project2/api/graphql'; + +interface GraphQLResponse { + data?: TData; + errors?: Array<{ + message: string; + }>; +} + +interface AuthPayload { + user: User; + sessionToken: string; +} + +async function graphqlRequest( + query: string, + variables: Record, +): Promise { + const response = await fetch(GRAPHQL_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query, + variables, + }), + }); + + if (!response.ok) { + throw new Error( + `Authentication request failed with HTTP ${response.status}.`, + ); + } + + const result = (await response.json()) as GraphQLResponse; + + const error = result.errors?.[0]; + + if (error) { + throw new Error(error.message); + } + + if (!result.data) { + throw new Error('Authentication response did not contain data.'); + } + + return result.data; +} + +export async function registerUser( + name: string, + email: string, + password: string, +): Promise { + const data = await graphqlRequest<{ + register: AuthPayload; + }>( + ` + mutation Register( + $name: String! + $email: String! + $password: String! + ) { + register( + name: $name + email: $email + password: $password + ) { + sessionToken + user { + id + name + email + } + } + } + `, + { + name, + email, + password, + }, + ); + + return data.register; +} + +export async function loginUser( + email: string, + password: string, +): Promise { + const data = await graphqlRequest<{ + login: AuthPayload; + }>( + ` + mutation Login( + $email: String! + $password: String! + ) { + login(email: $email, password: $password) { + sessionToken + user { + id + name + email + } + } + } + `, + { + email, + password, + }, + ); + + return data.login; +} + +export async function getCurrentUser( + sessionToken: string, +): Promise { + const data = await graphqlRequest<{ + currentUser: User | null; + }>( + ` + query CurrentUser($sessionToken: String!) { + currentUser(sessionToken: $sessionToken) { + id + name + email + } + } + `, + { + sessionToken, + }, + ); + + return data.currentUser; +} + +export async function signOutUser(sessionToken: string): Promise { + const data = await graphqlRequest<{ + signOut: boolean; + }>( + ` + mutation SignOut($sessionToken: String!) { + signOut(sessionToken: $sessionToken) + } + `, + { + sessionToken, + }, + ); + + return data.signOut; +} diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts new file mode 100644 index 0000000..90f5908 --- /dev/null +++ b/apps/web/src/store.test.ts @@ -0,0 +1,93 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { getCurrentUser, signOutUser } from './features/auth/authApi'; +import { useAppStore } from './store'; + +vi.mock('./features/auth/authApi', () => ({ + loginUser: vi.fn(), + registerUser: vi.fn(), + getCurrentUser: vi.fn(), + signOutUser: vi.fn(), +})); + +const authenticatedUser = { + id: 'user-123', + name: 'Hasan', + email: 'hasan@example.com', +}; + +const SESSION_TOKEN_KEY = 'recipe-platform-session-token'; + +describe('authentication store', () => { + beforeEach(() => { + vi.clearAllMocks(); + localStorage.clear(); + + useAppStore.setState({ + search: '', + currentUser: null, + }); + }); + + it('restores the current user from a stored session', async () => { + localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); + + vi.mocked(getCurrentUser).mockResolvedValue(authenticatedUser); + + await useAppStore.getState().restoreSession(); + + expect(getCurrentUser).toHaveBeenCalledWith('session-123'); + + expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); + + expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBe('session-123'); + }); + + it('removes an invalid session', async () => { + localStorage.setItem(SESSION_TOKEN_KEY, 'expired-session'); + + vi.mocked(getCurrentUser).mockResolvedValue(null); + + await useAppStore.getState().restoreSession(); + + expect(useAppStore.getState().currentUser).toBeNull(); + + expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBeNull(); + }); + + it('signs out and removes the session', async () => { + localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); + + useAppStore.setState({ + currentUser: authenticatedUser, + }); + + vi.mocked(signOutUser).mockResolvedValue(true); + + await useAppStore.getState().signOut(); + + expect(signOutUser).toHaveBeenCalledWith('session-123'); + + expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBeNull(); + + expect(useAppStore.getState().currentUser).toBeNull(); + }); + + it('clears local authentication even when sign-out fails', async () => { + localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); + + useAppStore.setState({ + currentUser: authenticatedUser, + }); + + vi.mocked(signOutUser).mockRejectedValue(new Error('Network error')); + + await expect(useAppStore.getState().signOut()).rejects.toThrow( + 'Network error', + ); + + expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBeNull(); + + expect(useAppStore.getState().currentUser).toBeNull(); + }); +}); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index f771f46..fa7b803 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -1,14 +1,15 @@ import { create } from 'zustand'; import { recipes } from './data/recipes'; -import { mockUser } from './data/users'; +import { + getCurrentUser, + loginUser, + registerUser, + signOutUser, +} from './features/auth/authApi'; import type { User } from './types/user'; -export interface CurrentUser { - id: string; - name: string; - email: string; -} +const SESSION_TOKEN_KEY = 'recipe-platform-session-token'; export const INITIAL_SAVED_RECIPE_IDS = recipes .filter((recipe) => recipe.isSaved) @@ -18,9 +19,13 @@ interface AppState { search: string; currentUser: User | null; setSearch: (search: string) => void; - login: (email: string) => void; - register: (name: string, email: string) => void; - signOut: () => void; + + login: (email: string, password: string) => Promise; + + register: (name: string, email: string, password: string) => Promise; + + restoreSession: () => Promise; + signOut: () => Promise; savedRecipeIds: string[]; setRecipeSaved: (recipeId: string, saved: boolean) => void; @@ -33,24 +38,59 @@ export const useAppStore = create((set) => ({ setSearch: (search) => set({ search }), - login: (email) => + login: async (email, password) => { + const result = await loginUser(email, password); + + localStorage.setItem(SESSION_TOKEN_KEY, result.sessionToken); + set({ - currentUser: { - ...mockUser, - email, - }, - }), + currentUser: result.user, + }); + }, + + register: async (name, email, password) => { + const result = await registerUser(name, email, password); + + localStorage.setItem(SESSION_TOKEN_KEY, result.sessionToken); - register: (name, email) => set({ - currentUser: { - ...mockUser, - name, - email, - }, - }), + currentUser: result.user, + }); + }, + + restoreSession: async () => { + const sessionToken = localStorage.getItem(SESSION_TOKEN_KEY); + + if (!sessionToken) { + set({ currentUser: null }); + return; + } - signOut: () => set({ currentUser: null }), + try { + const currentUser = await getCurrentUser(sessionToken); + + if (!currentUser) { + localStorage.removeItem(SESSION_TOKEN_KEY); + } + + set({ currentUser }); + } catch { + localStorage.removeItem(SESSION_TOKEN_KEY); + } + }, + + signOut: async () => { + const sessionToken = localStorage.getItem(SESSION_TOKEN_KEY); + + try { + if (sessionToken) { + await signOutUser(sessionToken); + } + } finally { + localStorage.removeItem(SESSION_TOKEN_KEY); + set({ currentUser: null }); + } + }, setRecipeSaved: (recipeId, saved) => set((state) => { diff --git a/contracts/generated.ts b/contracts/generated.ts index 2d016ef..2583ea2 100644 --- a/contracts/generated.ts +++ b/contracts/generated.ts @@ -19,15 +19,88 @@ export type Scalars = { Float: { input: number; output: number }; }; +export type User = { + __typename?: 'User'; + id: Scalars['ID']['output']; + name: Scalars['String']['output']; + email: Scalars['String']['output']; +}; + +export type AuthPayload = { + __typename?: 'AuthPayload'; + user: User; + sessionToken: Scalars['String']['output']; +}; + export type Query = { __typename?: 'Query'; health: Scalars['String']['output']; + currentUser?: Maybe; +}; + +export type QueryCurrentUserArgs = { + sessionToken: Scalars['String']['input']; +}; + +export type Mutation = { + __typename?: 'Mutation'; + register: AuthPayload; + login: AuthPayload; + signOut: Scalars['Boolean']['output']; +}; + +export type MutationRegisterArgs = { + name: Scalars['String']['input']; + email: Scalars['String']['input']; + password: Scalars['String']['input']; +}; + +export type MutationLoginArgs = { + email: Scalars['String']['input']; + password: Scalars['String']['input']; +}; + +export type MutationSignOutArgs = { + sessionToken: Scalars['String']['input']; }; export type HealthQueryVariables = Exact<{ [key: string]: never }>; export type HealthQuery = { health: string }; +export type RegisterMutationVariables = Exact<{ + name: string; + email: string; + password: string; +}>; + +export type RegisterMutation = { + register: { + sessionToken: string; + user: { id: string; name: string; email: string }; + }; +}; + +export type LoginMutationVariables = Exact<{ + email: string; + password: string; +}>; + +export type LoginMutation = { + login: { + sessionToken: string; + user: { id: string; name: string; email: string }; + }; +}; + +export type CurrentUserQueryVariables = Exact<{ + sessionToken: string; +}>; + +export type CurrentUserQuery = { + currentUser: { id: string; name: string; email: string } | null; +}; + export const HealthDocument = { kind: 'Document', definitions: [ @@ -44,3 +117,251 @@ export const HealthDocument = { }, ], } as unknown as DocumentNode; +export const RegisterDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'Register' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'name' } }, + type: { + kind: 'NonNullType', + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'String' }, + }, + }, + }, + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'email' }, + }, + type: { + kind: 'NonNullType', + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'String' }, + }, + }, + }, + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'password' }, + }, + type: { + kind: 'NonNullType', + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'String' }, + }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'register' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'name' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'name' }, + }, + }, + { + kind: 'Argument', + name: { kind: 'Name', value: 'email' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'email' }, + }, + }, + { + kind: 'Argument', + name: { kind: 'Name', value: 'password' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'password' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'sessionToken' }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'user' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'email' } }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; +export const LoginDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'Login' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'email' }, + }, + type: { + kind: 'NonNullType', + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'String' }, + }, + }, + }, + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'password' }, + }, + type: { + kind: 'NonNullType', + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'String' }, + }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'login' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'email' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'email' }, + }, + }, + { + kind: 'Argument', + name: { kind: 'Name', value: 'password' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'password' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'sessionToken' }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'user' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'email' } }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; +export const CurrentUserDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'query', + name: { kind: 'Name', value: 'CurrentUser' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'sessionToken' }, + }, + type: { + kind: 'NonNullType', + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'String' }, + }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'currentUser' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'sessionToken' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'sessionToken' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'email' } }, + ], + }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; diff --git a/contracts/operations.graphql b/contracts/operations.graphql index d983283..da05170 100644 --- a/contracts/operations.graphql +++ b/contracts/operations.graphql @@ -1,3 +1,33 @@ query Health { health } + +mutation Register($name: String!, $email: String!, $password: String!) { + register(name: $name, email: $email, password: $password) { + sessionToken + user { + id + name + email + } + } +} + +mutation Login($email: String!, $password: String!) { + login(email: $email, password: $password) { + sessionToken + user { + id + name + email + } + } +} + +query CurrentUser($sessionToken: String!) { + currentUser(sessionToken: $sessionToken) { + id + name + email + } +} diff --git a/package-lock.json b/package-lock.json index b7c4552..d2459a8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,6 +44,7 @@ "apps/api": { "name": "@t31/api", "dependencies": { + "argon2": "0.45.1", "drizzle-orm": "0.45.2", "graphql": "16.12.0", "graphql-yoga": "5.16.2", @@ -586,6 +587,12 @@ "node": ">=18.0.0" } }, + "node_modules/@epic-web/invariant": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz", + "integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==", + "license": "MIT" + }, "node_modules/@esbuild-kit/core-utils": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/@esbuild-kit/core-utils/-/core-utils-3.3.2.tgz", @@ -2258,6 +2265,15 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@phc/format": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@phc/format/-/format-1.0.0.tgz", + "integrity": "sha512-m7X9U6BG2+J+R1lSOdCiITLLrxm+cWlNI3HUFA92oLO77ObGNzaKdh8pMLqdZcshtkKuV84olNNXDfMc4FezBQ==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/@playwright/test": { "version": "1.63.0", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz", @@ -3729,6 +3745,22 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/argon2": { + "version": "0.45.1", + "resolved": "https://registry.npmjs.org/argon2/-/argon2-0.45.1.tgz", + "integrity": "sha512-skm+/WCjkGqCQxF7FG1LuZXM5yvbFjgbfiCGsud2oLgaDhh6b6dbH0b1EkghbM+xx4Bj8Ape+KKgixoIlWZicQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@phc/format": "^1.0.0", + "cross-env": "^10.1.0", + "node-addon-api": "^8.9.0", + "node-gyp-build": "^4.8.4" + }, + "engines": { + "node": ">=16.17.0" + } + }, "node_modules/argparse": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", @@ -4242,6 +4274,23 @@ "url": "https://opencollective.com/express" } }, + "node_modules/cross-env": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz", + "integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==", + "license": "MIT", + "dependencies": { + "@epic-web/invariant": "^1.0.0", + "cross-spawn": "^7.0.6" + }, + "bin": { + "cross-env": "dist/bin/cross-env.js", + "cross-env-shell": "dist/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/cross-inspect": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/cross-inspect/-/cross-inspect-1.0.1.tgz", @@ -4258,7 +4307,6 @@ "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, "license": "MIT", "dependencies": { "path-key": "^3.1.0", @@ -7295,7 +7343,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, "license": "ISC" }, "node_modules/js-tokens": { @@ -7910,6 +7957,26 @@ "dev": true, "license": "MIT" }, + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", + "license": "MIT", + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, + "node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "license": "MIT", + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, "node_modules/node-releases": { "version": "2.0.57", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.57.tgz", @@ -8140,7 +8207,6 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -8872,7 +8938,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -8885,7 +8950,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -10393,7 +10457,6 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" From 3003872b22345201b7895021bbbf1f0b3f74c62c Mon Sep 17 00:00:00 2001 From: Hasan Mohammad Fawzi Date: Sun, 11 Oct 2026 09:28:27 +0200 Subject: [PATCH 2/4] fix(auth): address review feedback --- README.md | 14 +++- .../src/features/auth/authRepository.test.ts | 74 +++++++++++++++++ apps/api/src/features/auth/authRepository.ts | 50 ++++++++++-- .../api/src/features/auth/authService.test.ts | 12 +-- apps/api/src/features/auth/authService.ts | 21 +++-- apps/web/src/features/auth/AuthPage.css | 8 +- apps/web/src/features/auth/AuthPages.test.tsx | 79 +++++++++++++++++++ apps/web/src/features/auth/LoginPage.tsx | 38 +++++++-- apps/web/src/features/auth/RegisterPage.tsx | 40 +++++++--- apps/web/src/features/auth/authApi.test.ts | 66 ++++++++++++++++ apps/web/src/features/auth/authApi.ts | 40 +++++++--- apps/web/src/store.test.ts | 14 ++++ apps/web/src/store.ts | 3 +- 13 files changed, 396 insertions(+), 63 deletions(-) create mode 100644 apps/api/src/features/auth/authRepository.test.ts create mode 100644 apps/web/src/features/auth/authApi.test.ts diff --git a/README.md b/README.md index 298ffa8..a3d67cf 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ nvm install nvm use ``` -For første leveranse kan frontend kjøres alene fordi oppskrifter og autentisering foreløpig er mocket: +Oppskriftsvisningen kan kjøres med frontend alene. Innlogging og registrering krever API og PostgreSQL: ```bash npm run dev:web @@ -59,6 +59,14 @@ Copy-Item .env.example .env Ikke legg `.env`, passord, tokens eller andre hemmeligheter i Git. +## Authentication + +Registration, login and logout use GraphQL and PostgreSQL. Both the API and database must be running; recipe browsing still uses mock data. Configure DATABASE_URL in .env and run `npm run db:migrate` before starting the API. User and session creation run in one transaction, so a failed session insert rolls back the new user. + +Session tokens are bearer credentials stored in localStorage to restore login after refresh or reopening the browser. They expire after seven days and are deleted server-side on successful logout. Temporary API or network errors preserve the local token for a later restoration attempt; only a confirmed invalid or expired session clears it. + +Security trade-off: localStorage is readable by JavaScript on the same origin. An XSS vulnerability could steal a token and let an attacker impersonate its owner until expiry or revocation. This prototype accepts that limitation; production deployment should use HTTPS and consider Secure, HttpOnly, SameSite cookies with appropriate CSRF protection. HttpOnly cookies prevent JavaScript from reading the session credential. + ## Nyttige kommandoer | Kommando | Bruk | @@ -103,8 +111,8 @@ Oppskrifter kan være offentlige eller private. Offentlige oppskrifter finnes gj | `/cookbook` | My Cookbook: lagrede og egenproduserte oppskrifter | | `/recipes/:id` | Detaljvisning av én oppskrift | | `/recipes/new` | Skjema for å opprette en oppskrift | -| `/login` | Mock innlogging | -| `/register` | Mock registrering | +| `/login` | Innlogging via GraphQL | +| `/register` | Registrering via GraphQL | ### Viktige brukerreiser diff --git a/apps/api/src/features/auth/authRepository.test.ts b/apps/api/src/features/auth/authRepository.test.ts new file mode 100644 index 0000000..9697703 --- /dev/null +++ b/apps/api/src/features/auth/authRepository.test.ts @@ -0,0 +1,74 @@ +import type { Pool, PoolClient } from 'pg'; +import { describe, expect, it, vi } from 'vitest'; +import { createAuthRepository } from './authRepository.js'; + +const user = { id: 'user-123', name: 'Hasan', email: 'hasan@example.com' }; + +function setup(failure?: Error | { code: string; constraint: string }) { + let persistedUser = false; + const query = vi.fn(async (sql: string) => { + if (sql.includes('INSERT INTO project2.users')) { + if (failure && 'code' in failure) throw failure; + persistedUser = true; + return { rows: [user] }; + } + if (sql.includes('INSERT INTO project2.sessions')) { + if (failure) throw failure; + return { rows: [{ id: 'session-123' }] }; + } + if (sql === 'ROLLBACK') persistedUser = false; + return { rows: [] }; + }); + const release = vi.fn(); + const client = { query, release } as unknown as PoolClient; + const pool = { + connect: vi.fn(async () => client), + query: vi.fn(), + } as unknown as Pool; + return { + repository: createAuthRepository(pool), + query, + release, + pool, + hasUser: () => persistedUser, + }; +} + +describe('atomic registration', () => { + it('commits user and session on the same connection', async () => { + const { repository, query, release, pool } = setup(); + const expiresAt = new Date(); + await expect( + repository.createUserWithSession('Hasan', user.email, 'hash', expiresAt), + ).resolves.toEqual({ user, sessionToken: 'session-123' }); + expect(query.mock.calls.map(([sql]) => sql.trim().split(/\s+/)[0])).toEqual( + ['BEGIN', 'INSERT', 'INSERT', 'COMMIT'], + ); + expect(pool.query).not.toHaveBeenCalled(); + expect(release).toHaveBeenCalledOnce(); + }); + + it('rolls back and releases the connection when session creation fails', async () => { + const failure = new Error('Session insert failed'); + const { repository, query, release, hasUser } = setup(failure); + await expect( + repository.createUserWithSession('Hasan', user.email, 'hash', new Date()), + ).rejects.toBe(failure); + expect(query).toHaveBeenLastCalledWith('ROLLBACK'); + expect(query).not.toHaveBeenCalledWith('COMMIT'); + expect(hasUser()).toBe(false); + expect(release).toHaveBeenCalledOnce(); + }); + + it('handles concurrent registration of the same email', async () => { + const { repository, query, release } = setup({ + code: '23505', + constraint: 'users_email_unique', + }); + await expect( + repository.createUserWithSession('Hasan', user.email, 'hash', new Date()), + ).rejects.toThrow('An account with this email already exists.'); + expect(query).toHaveBeenLastCalledWith('ROLLBACK'); + expect(release).toHaveBeenCalledOnce(); + }); +}); diff --git a/apps/api/src/features/auth/authRepository.ts b/apps/api/src/features/auth/authRepository.ts index 2fcda81..67ce794 100644 --- a/apps/api/src/features/auth/authRepository.ts +++ b/apps/api/src/features/auth/authRepository.ts @@ -1,3 +1,4 @@ +import { GraphQLError } from 'graphql'; import type { Pool } from 'pg'; import { db } from '../../db/client.js'; @@ -37,6 +38,13 @@ export interface AuthRepository { passwordHash: string, ): Promise; + createUserWithSession( + name: string, + email: string, + passwordHash: string, + expiresAt: Date, + ): Promise<{ user: PublicUser; sessionToken: string }>; + createSession(userId: string, expiresAt: Date): Promise; findUserBySession(sessionToken: string): Promise; @@ -44,10 +52,13 @@ export interface AuthRepository { deleteSession(sessionToken: string): Promise; } -export function createAuthRepository(pool: Pool = db): AuthRepository { +export function createAuthRepository( + pool: Pool = db, + executor: Pick = pool, +): AuthRepository { return { async findUserByEmail(email) { - const result = await pool.query( + const result = await executor.query( ` SELECT id, name, email, password_hash FROM project2.users @@ -72,7 +83,7 @@ export function createAuthRepository(pool: Pool = db): AuthRepository { }, async createUser(name, email, passwordHash) { - const result = await pool.query( + const result = await executor.query( ` INSERT INTO project2.users (name, email, password_hash) VALUES ($1, $2, $3) @@ -90,8 +101,35 @@ export function createAuthRepository(pool: Pool = db): AuthRepository { return user; }, + async createUserWithSession(name, email, passwordHash, expiresAt) { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + const repository = createAuthRepository(pool, client); + const user = await repository.createUser(name, email, passwordHash); + const sessionToken = await repository.createSession(user.id, expiresAt); + await client.query('COMMIT'); + return { user, sessionToken }; + } catch (error) { + await client.query('ROLLBACK'); + if ( + typeof error === 'object' && + error !== null && + 'code' in error && + error.code === '23505' && + 'constraint' in error && + error.constraint === 'users_email_unique' + ) { + throw new GraphQLError('An account with this email already exists.'); + } + throw error; + } finally { + client.release(); + } + }, + async createSession(userId, expiresAt) { - const result = await pool.query<{ id: string }>( + const result = await executor.query<{ id: string }>( ` INSERT INTO project2.sessions (user_id, expires_at) VALUES ($1, $2) @@ -110,7 +148,7 @@ export function createAuthRepository(pool: Pool = db): AuthRepository { }, async findUserBySession(sessionToken) { - const result = await pool.query( + const result = await executor.query( ` SELECT users.id, users.name, users.email FROM project2.sessions AS sessions @@ -127,7 +165,7 @@ export function createAuthRepository(pool: Pool = db): AuthRepository { }, async deleteSession(sessionToken) { - await pool.query( + await executor.query( ` DELETE FROM project2.sessions WHERE id = $1 diff --git a/apps/api/src/features/auth/authService.test.ts b/apps/api/src/features/auth/authService.test.ts index ede6527..7f5c456 100644 --- a/apps/api/src/features/auth/authService.test.ts +++ b/apps/api/src/features/auth/authService.test.ts @@ -24,6 +24,10 @@ function createRepository( ): AuthRepository { return { findUserByEmail: vi.fn(async () => null), + createUserWithSession: vi.fn(async () => ({ + user: publicUser, + sessionToken: 'session-123', + })), createUser: vi.fn(async () => publicUser), createSession: vi.fn(async () => 'session-123'), findUserBySession: vi.fn(async () => null), @@ -60,14 +64,10 @@ describe('authService', () => { sessionToken: 'session-123', }); - expect(repository.createUser).toHaveBeenCalledWith( + expect(repository.createUserWithSession).toHaveBeenCalledWith( 'Hasan', 'hasan@example.com', 'hashed:secret123', - ); - - expect(repository.createSession).toHaveBeenCalledWith( - publicUser.id, expect.any(Date), ); }); @@ -83,7 +83,7 @@ describe('authService', () => { service.register('Hasan', 'hasan@example.com', 'secret123'), ).rejects.toThrow('An account with this email already exists.'); - expect(repository.createUser).not.toHaveBeenCalled(); + expect(repository.createUserWithSession).not.toHaveBeenCalled(); expect(repository.createSession).not.toHaveBeenCalled(); }); diff --git a/apps/api/src/features/auth/authService.ts b/apps/api/src/features/auth/authService.ts index d2a437a..f151da2 100644 --- a/apps/api/src/features/auth/authService.ts +++ b/apps/api/src/features/auth/authService.ts @@ -1,3 +1,4 @@ +import { GraphQLError } from 'graphql'; import { hash, verify } from 'argon2'; import { @@ -43,35 +44,33 @@ export function createAuthService( const normalizedEmail = email.trim().toLowerCase(); if (normalizedName.length < 2) { - throw new Error('Name must contain at least 2 characters.'); + throw new GraphQLError('Name must contain at least 2 characters.'); } if (!normalizedEmail.includes('@')) { - throw new Error('Enter a valid email address.'); + throw new GraphQLError('Enter a valid email address.'); } if (password.length < 6) { - throw new Error('Password must contain at least 6 characters.'); + throw new GraphQLError('Password must contain at least 6 characters.'); } const existingUser = await repository.findUserByEmail(normalizedEmail); if (existingUser) { - throw new Error('An account with this email already exists.'); + throw new GraphQLError('An account with this email already exists.'); } const passwordHash = await passwordHasher.hash(password); - const user = await repository.createUser( + const expiresAt = new Date(Date.now() + SESSION_DURATION_MS); + const { user, sessionToken } = await repository.createUserWithSession( normalizedName, normalizedEmail, passwordHash, + expiresAt, ); - const expiresAt = new Date(Date.now() + SESSION_DURATION_MS); - - const sessionToken = await repository.createSession(user.id, expiresAt); - return { user, sessionToken, @@ -84,7 +83,7 @@ export function createAuthService( const user = await repository.findUserByEmail(normalizedEmail); if (!user) { - throw new Error('Invalid email or password.'); + throw new GraphQLError('Invalid email or password.'); } const passwordIsCorrect = await passwordHasher.verify( @@ -93,7 +92,7 @@ export function createAuthService( ); if (!passwordIsCorrect) { - throw new Error('Invalid email or password.'); + throw new GraphQLError('Invalid email or password.'); } const expiresAt = new Date(Date.now() + SESSION_DURATION_MS); diff --git a/apps/web/src/features/auth/AuthPage.css b/apps/web/src/features/auth/AuthPage.css index f1ab45f..b4123a8 100644 --- a/apps/web/src/features/auth/AuthPage.css +++ b/apps/web/src/features/auth/AuthPage.css @@ -24,8 +24,7 @@ } .auth-card__intro, -.auth-card__alternative, -.auth-card__mock-note { +.auth-card__alternative { color: var(--color-text-muted); } @@ -39,11 +38,6 @@ text-align: center; } -.auth-card__mock-note { - margin-top: var(--space-4); - font-size: 0.875rem; -} - @media (max-width: 40rem) { .auth-page { padding: var(--space-4); diff --git a/apps/web/src/features/auth/AuthPages.test.tsx b/apps/web/src/features/auth/AuthPages.test.tsx index 99c5a9a..3a21616 100644 --- a/apps/web/src/features/auth/AuthPages.test.tsx +++ b/apps/web/src/features/auth/AuthPages.test.tsx @@ -148,4 +148,83 @@ describe('authentication pages', () => { expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); }); + it.each([ + ['/login', 'Invalid email or password.'], + ['/register', 'An account with this email already exists.'], + ['/login', 'Unable to connect. Check your connection and try again.'], + ['/register', 'Unable to connect. Check your connection and try again.'], + ['/login', 'Authentication is temporarily unavailable. Please try again.'], + [ + '/register', + 'Authentication is temporarily unavailable. Please try again.', + ], + ] as const)( + 'shows %s failure: %s and permits retry', + async (route, message) => { + const request = vi.mocked(route === '/login' ? loginUser : registerUser); + request.mockRejectedValueOnce(new Error(message)); + const user = userEvent.setup(); + renderAuthPage(route); + if (route === '/register') { + await user.type(screen.getByLabelText(/^Name/), 'Hasan'); + await user.type( + screen.getByLabelText(/^Confirm password/), + 'secret123', + ); + } + await user.type(screen.getByLabelText(/^Email/), 'hasan@example.com'); + await user.type(screen.getByLabelText(/^Password/), 'secret123'); + await user.click(screen.getByRole('button')); + expect(await screen.findByRole('alert')).toHaveTextContent(message); + expect( + screen.queryByRole('heading', { name: 'Explore' }), + ).not.toBeInTheDocument(); + expect(useAppStore.getState().currentUser).toBeNull(); + expect(localStorage.getItem('recipe-platform-session-token')).toBeNull(); + expect(screen.getByRole('button')).toBeEnabled(); + request.mockResolvedValueOnce({ + user: authenticatedUser, + sessionToken: 'retry-session', + }); + await user.click(screen.getByRole('button')); + expect( + await screen.findByRole('heading', { name: 'Explore' }), + ).toBeInTheDocument(); + }, + ); + + it.each(['/login', '/register'] as const)( + 'prevents duplicate submissions on %s', + async (route) => { + let resolve!: (value: { + user: typeof authenticatedUser; + sessionToken: string; + }) => void; + const request = vi.mocked(route === '/login' ? loginUser : registerUser); + request.mockReturnValueOnce( + new Promise((done) => { + resolve = done; + }), + ); + const user = userEvent.setup(); + renderAuthPage(route); + if (route === '/register') { + await user.type(screen.getByLabelText(/^Name/), 'Hasan'); + await user.type( + screen.getByLabelText(/^Confirm password/), + 'secret123', + ); + } + await user.type(screen.getByLabelText(/^Email/), 'hasan@example.com'); + await user.type(screen.getByLabelText(/^Password/), 'secret123'); + await user.click(screen.getByRole('button')); + expect(screen.getByRole('button')).toBeDisabled(); + await user.click(screen.getByRole('button')); + expect(request).toHaveBeenCalledTimes(1); + resolve({ user: authenticatedUser, sessionToken: 'session-123' }); + expect( + await screen.findByRole('heading', { name: 'Explore' }), + ).toBeInTheDocument(); + }, + ); }); diff --git a/apps/web/src/features/auth/LoginPage.tsx b/apps/web/src/features/auth/LoginPage.tsx index e5044c2..7845356 100644 --- a/apps/web/src/features/auth/LoginPage.tsx +++ b/apps/web/src/features/auth/LoginPage.tsx @@ -2,6 +2,7 @@ import { useState, type FormEvent } from 'react'; import { Link, useNavigate } from 'react-router-dom'; import Button from '../../components/ui/Button/Button'; +import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage'; import Field from '../../components/ui/Field/Field'; import { useAppStore } from '../../store'; import './AuthPage.css'; @@ -19,8 +20,13 @@ function LoginPage() { const [password, setPassword] = useState(''); const [errors, setErrors] = useState({}); + const [submitError, setSubmitError] = useState(''); + const [isSubmitting, setIsSubmitting] = useState(false); + const handleSubmit = async (event: FormEvent) => { event.preventDefault(); + if (isSubmitting) return; + setSubmitError(''); const nextErrors: LoginErrors = {}; @@ -42,8 +48,19 @@ function LoginPage() { return; } - await login(email.trim(), password); - navigate('/'); + setIsSubmitting(true); + try { + await login(email.trim(), password); + navigate('/'); + } catch (error) { + setSubmitError( + error instanceof Error + ? error.message + : 'Something went wrong. Please try again.', + ); + } finally { + setIsSubmitting(false); + } }; return ( @@ -78,18 +95,23 @@ function LoginPage() { onChange={(event) => setPassword(event.target.value)} /> -

Do not have an account? Register

- -

- This prototype uses mock authentication. Do not enter a real password. -

); diff --git a/apps/web/src/features/auth/RegisterPage.tsx b/apps/web/src/features/auth/RegisterPage.tsx index 0e651e7..897c3b6 100644 --- a/apps/web/src/features/auth/RegisterPage.tsx +++ b/apps/web/src/features/auth/RegisterPage.tsx @@ -2,6 +2,7 @@ import { useState, type FormEvent } from 'react'; import { Link, useNavigate } from 'react-router-dom'; import Button from '../../components/ui/Button/Button'; +import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage'; import Field from '../../components/ui/Field/Field'; import { useAppStore } from '../../store'; import './AuthPage.css'; @@ -23,8 +24,13 @@ function RegisterPage() { const [confirmPassword, setConfirmPassword] = useState(''); const [errors, setErrors] = useState({}); + const [submitError, setSubmitError] = useState(''); + const [isSubmitting, setIsSubmitting] = useState(false); + const handleSubmit = async (event: FormEvent) => { event.preventDefault(); + if (isSubmitting) return; + setSubmitError(''); const nextErrors: RegisterErrors = {}; @@ -56,8 +62,19 @@ function RegisterPage() { return; } - await register(name.trim(), email.trim(), password); - navigate('/'); + setIsSubmitting(true); + try { + await register(name.trim(), email.trim(), password); + navigate('/'); + } catch (error) { + setSubmitError( + error instanceof Error + ? error.message + : 'Something went wrong. Please try again.', + ); + } finally { + setIsSubmitting(false); + } }; return ( @@ -66,7 +83,7 @@ function RegisterPage() {

Recipe Platform

Register

- Create a mock account to save and manage recipes. + Create an account to save and manage recipes.

@@ -115,18 +132,23 @@ function RegisterPage() { onChange={(event) => setConfirmPassword(event.target.value)} /> -

Already have an account? Log in

- -

- This prototype uses mock authentication. Do not enter a real password. -

); diff --git a/apps/web/src/features/auth/authApi.test.ts b/apps/web/src/features/auth/authApi.test.ts new file mode 100644 index 0000000..6838268 --- /dev/null +++ b/apps/web/src/features/auth/authApi.test.ts @@ -0,0 +1,66 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { getCurrentUser, loginUser, registerUser } from './authApi'; + +afterEach(() => vi.unstubAllGlobals()); +const requests = [ + () => loginUser('a@example.com', 'secret123'), + () => registerUser('Hasan', 'a@example.com', 'secret123'), +]; + +describe('authentication API errors', () => { + it.each(requests)('translates network failures', async (request) => { + vi.stubGlobal( + 'fetch', + vi.fn().mockRejectedValue(new TypeError('Failed to fetch')), + ); + await expect(request()).rejects.toThrow( + 'Unable to connect. Check your connection and try again.', + ); + }); + it.each(requests)('translates HTTP failures', async (request) => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue(new Response('', { status: 503 })), + ); + await expect(request()).rejects.toThrow( + 'Authentication is temporarily unavailable. Please try again.', + ); + }); + it.each([ + 'Invalid email or password.', + 'An account with this email already exists.', + ])('preserves expected API errors: %s', async (message) => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue(Response.json({ errors: [{ message }] })), + ); + await expect(loginUser('a@example.com', 'secret123')).rejects.toThrow( + message, + ); + }); + it('does not expose internal server messages', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + Response.json({ + errors: [{ message: 'Database connection details' }], + }), + ), + ); + await expect(loginUser('a@example.com', 'secret123')).rejects.toThrow( + 'Authentication is temporarily unavailable. Please try again.', + ); + }); + it('rejects GraphQL errors even when currentUser is null', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + Response.json({ + data: { currentUser: null }, + errors: [{ message: 'Database unavailable' }], + }), + ), + ); + await expect(getCurrentUser('session-123')).rejects.toThrow(); + }); +}); diff --git a/apps/web/src/features/auth/authApi.ts b/apps/web/src/features/auth/authApi.ts index a309e1e..9b732ca 100644 --- a/apps/web/src/features/auth/authApi.ts +++ b/apps/web/src/features/auth/authApi.ts @@ -18,20 +18,25 @@ async function graphqlRequest( query: string, variables: Record, ): Promise { - const response = await fetch(GRAPHQL_URL, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query, - variables, - }), - }); + let response: Response; + try { + response = await fetch(GRAPHQL_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + query, + variables, + }), + }); + } catch { + throw new Error('Unable to connect. Check your connection and try again.'); + } if (!response.ok) { throw new Error( - `Authentication request failed with HTTP ${response.status}.`, + 'Authentication is temporarily unavailable. Please try again.', ); } @@ -40,7 +45,18 @@ async function graphqlRequest( const error = result.errors?.[0]; if (error) { - throw new Error(error.message); + const expectedMessages = [ + 'Invalid email or password.', + 'An account with this email already exists.', + 'Name must contain at least 2 characters.', + 'Enter a valid email address.', + 'Password must contain at least 6 characters.', + ]; + throw new Error( + expectedMessages.includes(error.message) + ? error.message + : 'Authentication is temporarily unavailable. Please try again.', + ); } if (!result.data) { diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index 90f5908..7395208 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -55,6 +55,20 @@ describe('authentication store', () => { expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBeNull(); }); + it.each(['Network error', 'API unavailable'])( + 'keeps the token after %s and restores on retry', + async (message) => { + localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); + vi.mocked(getCurrentUser).mockRejectedValueOnce(new Error(message)); + await useAppStore.getState().restoreSession(); + expect(localStorage.getItem(SESSION_TOKEN_KEY)).toBe('session-123'); + expect(useAppStore.getState().currentUser).toBeNull(); + vi.mocked(getCurrentUser).mockResolvedValueOnce(authenticatedUser); + await useAppStore.getState().restoreSession(); + expect(useAppStore.getState().currentUser).toEqual(authenticatedUser); + }, + ); + it('signs out and removes the session', async () => { localStorage.setItem(SESSION_TOKEN_KEY, 'session-123'); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index fa7b803..9c6e943 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -75,7 +75,8 @@ export const useAppStore = create((set) => ({ set({ currentUser }); } catch { - localStorage.removeItem(SESSION_TOKEN_KEY); + // A failed request does not establish that the session is invalid. + // Keep the token so a later restoration attempt can validate it. } }, From ea04a4f13d1aee2fe86bd8aa4e20ef02ee81dee6 Mon Sep 17 00:00:00 2001 From: Hasan Mohammad Fawzi Date: Sun, 11 Oct 2026 22:24:40 +0200 Subject: [PATCH 3/4] feat(db): add recipe database model and migration --- README.md | 4 + apps/api/migrations/0002_recipe_model.sql | 105 +++ apps/api/migrations/meta/0002_snapshot.json | 700 ++++++++++++++++++++ apps/api/migrations/meta/_journal.json | 7 + apps/api/src/db/migrate.ts | 9 +- apps/api/src/db/schema.ts | 178 ++++- docs/database-model.md | 111 ++++ package.json | 3 +- scripts/test-database.ts | 329 +++++++++ 9 files changed, 1438 insertions(+), 8 deletions(-) create mode 100644 apps/api/migrations/0002_recipe_model.sql create mode 100644 apps/api/migrations/meta/0002_snapshot.json create mode 100644 docs/database-model.md create mode 100644 scripts/test-database.ts diff --git a/README.md b/README.md index a3d67cf..fd16a34 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,10 @@ Session tokens are bearer credentials stored in localStorage to restore login af Security trade-off: localStorage is readable by JavaScript on the same origin. An XSS vulnerability could steal a token and let an attacker impersonate its owner until expiry or revocation. This prototype accepts that limitation; production deployment should use HTTPS and consider Secure, HttpOnly, SameSite cookies with appropriate CSRF protection. HttpOnly cookies prevent JavaScript from reading the session credential. +## Database + +Se [databasemodellen](docs/database-model.md) for tabeller, ER-diagram, regler, migrasjon og tester. Modellen utvider autentiseringen og er klar for CRUD i neste steg. + ## Nyttige kommandoer | Kommando | Bruk | diff --git a/apps/api/migrations/0002_recipe_model.sql b/apps/api/migrations/0002_recipe_model.sql new file mode 100644 index 0000000..5065027 --- /dev/null +++ b/apps/api/migrations/0002_recipe_model.sql @@ -0,0 +1,105 @@ +-- Existing placeholder recipes need a deliberate author/content backfill. +-- Stop before changing tables rather than inventing ownership or losing data. +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM "project2"."recipes") THEN + RAISE EXCEPTION 'Recipe migration requires an empty legacy recipes table. Back up existing rows and prepare an explicit author/content backfill before retrying.'; + END IF; +END $$; +--> statement-breakpoint +CREATE TABLE "project2"."ratings" ( + "user_id" uuid NOT NULL, + "recipe_id" uuid NOT NULL, + "score" integer NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "ratings_user_id_recipe_id_pk" PRIMARY KEY("user_id","recipe_id"), + CONSTRAINT "ratings_score_valid" CHECK ("project2"."ratings"."score" BETWEEN 1 AND 5) +); +--> statement-breakpoint +CREATE TABLE "project2"."recipe_ingredients" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "recipe_id" uuid NOT NULL, + "name" text NOT NULL, + "amount" numeric(12, 4) NOT NULL, + "unit" text NOT NULL, + "note" text, + "position" integer NOT NULL, + CONSTRAINT "recipe_ingredients_name_not_blank" CHECK (length(trim("project2"."recipe_ingredients"."name")) > 0), + CONSTRAINT "recipe_ingredients_amount_positive" CHECK ("project2"."recipe_ingredients"."amount" > 0 AND "project2"."recipe_ingredients"."amount" <> 'NaN'::numeric), + CONSTRAINT "recipe_ingredients_position_positive" CHECK ("project2"."recipe_ingredients"."position" > 0) +); +--> statement-breakpoint +CREATE TABLE "project2"."recipe_instructions" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "recipe_id" uuid NOT NULL, + "text" text NOT NULL, + "position" integer NOT NULL, + CONSTRAINT "recipe_instructions_text_not_blank" CHECK (length(trim("project2"."recipe_instructions"."text")) > 0), + CONSTRAINT "recipe_instructions_position_positive" CHECK ("project2"."recipe_instructions"."position" > 0) +); +--> statement-breakpoint +CREATE TABLE "project2"."recipe_tags" ( + "recipe_id" uuid NOT NULL, + "tag" text NOT NULL, + CONSTRAINT "recipe_tags_recipe_id_tag_pk" PRIMARY KEY("recipe_id","tag"), + CONSTRAINT "recipe_tags_normalized" CHECK (length("project2"."recipe_tags"."tag") > 0 AND "project2"."recipe_tags"."tag" = lower(trim("project2"."recipe_tags"."tag"))) +); +--> statement-breakpoint +CREATE TABLE "project2"."saved_recipes" ( + "user_id" uuid NOT NULL, + "recipe_id" uuid NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "saved_recipes_user_id_recipe_id_pk" PRIMARY KEY("user_id","recipe_id") +); +--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "author_id" uuid NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "description" text NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "image_url" text;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "category" text NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "cuisine" text NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "difficulty" text NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "visibility" text DEFAULT 'private' NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "prep_minutes" integer NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "cook_minutes" integer NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "servings" integer NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "created_at" timestamp with time zone DEFAULT now() NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "updated_at" timestamp with time zone DEFAULT now() NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."ratings" ADD CONSTRAINT "ratings_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "project2"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."ratings" ADD CONSTRAINT "ratings_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."recipe_ingredients" ADD CONSTRAINT "recipe_ingredients_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."recipe_instructions" ADD CONSTRAINT "recipe_instructions_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."recipe_tags" ADD CONSTRAINT "recipe_tags_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."saved_recipes" ADD CONSTRAINT "saved_recipes_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "project2"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project2"."saved_recipes" ADD CONSTRAINT "saved_recipes_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "ratings_recipe_idx" ON "project2"."ratings" USING btree ("recipe_id");--> statement-breakpoint +CREATE UNIQUE INDEX "recipe_ingredients_recipe_position_unique" ON "project2"."recipe_ingredients" USING btree ("recipe_id","position");--> statement-breakpoint +CREATE UNIQUE INDEX "recipe_instructions_recipe_position_unique" ON "project2"."recipe_instructions" USING btree ("recipe_id","position");--> statement-breakpoint +CREATE INDEX "saved_recipes_recipe_idx" ON "project2"."saved_recipes" USING btree ("recipe_id");--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_author_id_users_id_fk" FOREIGN KEY ("author_id") REFERENCES "project2"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "recipes_author_idx" ON "project2"."recipes" USING btree ("author_id");--> statement-breakpoint +CREATE INDEX "recipes_public_created_idx" ON "project2"."recipes" USING btree ("created_at","id") WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_title_not_blank" CHECK (length(trim("project2"."recipes"."title")) > 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_category_not_blank" CHECK (length(trim("project2"."recipes"."category")) > 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_cuisine_not_blank" CHECK (length(trim("project2"."recipes"."cuisine")) > 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_difficulty_valid" CHECK ("project2"."recipes"."difficulty" IN ('easy', 'medium', 'hard'));--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_visibility_valid" CHECK ("project2"."recipes"."visibility" IN ('public', 'private'));--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_prep_minutes_nonnegative" CHECK ("project2"."recipes"."prep_minutes" >= 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_cook_minutes_nonnegative" CHECK ("project2"."recipes"."cook_minutes" >= 0);--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_servings_positive" CHECK ("project2"."recipes"."servings" > 0); +--> statement-breakpoint +-- Database triggers also cover writes made through raw SQL (as in auth). +CREATE FUNCTION "project2"."touch_updated_at"() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + NEW.updated_at = clock_timestamp(); + RETURN NEW; +END $$; +--> statement-breakpoint +CREATE TRIGGER recipes_touch_updated_at +BEFORE UPDATE ON "project2"."recipes" +FOR EACH ROW EXECUTE FUNCTION "project2"."touch_updated_at"(); +--> statement-breakpoint +CREATE TRIGGER ratings_touch_updated_at +BEFORE UPDATE ON "project2"."ratings" +FOR EACH ROW EXECUTE FUNCTION "project2"."touch_updated_at"(); diff --git a/apps/api/migrations/meta/0002_snapshot.json b/apps/api/migrations/meta/0002_snapshot.json new file mode 100644 index 0000000..742398e --- /dev/null +++ b/apps/api/migrations/meta/0002_snapshot.json @@ -0,0 +1,700 @@ +{ + "id": "078adb6f-bfdc-42b6-9e70-e621fc612161", + "prevId": "8106c561-4f83-4ec4-9119-840e77bd557d", + "version": "7", + "dialect": "postgresql", + "tables": { + "project2.ratings": { + "name": "ratings", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "score": { + "name": "score", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "ratings_recipe_idx": { + "name": "ratings_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "ratings_user_id_users_id_fk": { + "name": "ratings_user_id_users_id_fk", + "tableFrom": "ratings", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "ratings_recipe_id_recipes_id_fk": { + "name": "ratings_recipe_id_recipes_id_fk", + "tableFrom": "ratings", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "ratings_user_id_recipe_id_pk": { + "name": "ratings_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "ratings_score_valid": { + "name": "ratings_score_valid", + "value": "\"project2\".\"ratings\".\"score\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_ingredients": { + "name": "recipe_ingredients", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "numeric(12, 4)", + "primaryKey": false, + "notNull": true + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_ingredients_recipe_position_unique": { + "name": "recipe_ingredients_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_ingredients_recipe_id_recipes_id_fk": { + "name": "recipe_ingredients_recipe_id_recipes_id_fk", + "tableFrom": "recipe_ingredients", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_ingredients_name_not_blank": { + "name": "recipe_ingredients_name_not_blank", + "value": "length(trim(\"project2\".\"recipe_ingredients\".\"name\")) > 0" + }, + "recipe_ingredients_amount_positive": { + "name": "recipe_ingredients_amount_positive", + "value": "\"project2\".\"recipe_ingredients\".\"amount\" > 0 AND \"project2\".\"recipe_ingredients\".\"amount\" <> 'NaN'::numeric" + }, + "recipe_ingredients_position_positive": { + "name": "recipe_ingredients_position_positive", + "value": "\"project2\".\"recipe_ingredients\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_instructions": { + "name": "recipe_instructions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_instructions_recipe_position_unique": { + "name": "recipe_instructions_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_instructions_recipe_id_recipes_id_fk": { + "name": "recipe_instructions_recipe_id_recipes_id_fk", + "tableFrom": "recipe_instructions", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_instructions_text_not_blank": { + "name": "recipe_instructions_text_not_blank", + "value": "length(trim(\"project2\".\"recipe_instructions\".\"text\")) > 0" + }, + "recipe_instructions_position_positive": { + "name": "recipe_instructions_position_positive", + "value": "\"project2\".\"recipe_instructions\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_tags": { + "name": "recipe_tags", + "schema": "project2", + "columns": { + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "recipe_tags_recipe_id_recipes_id_fk": { + "name": "recipe_tags_recipe_id_recipes_id_fk", + "tableFrom": "recipe_tags", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "recipe_tags_recipe_id_tag_pk": { + "name": "recipe_tags_recipe_id_tag_pk", + "columns": ["recipe_id", "tag"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_tags_normalized": { + "name": "recipe_tags_normalized", + "value": "length(\"project2\".\"recipe_tags\".\"tag\") > 0 AND \"project2\".\"recipe_tags\".\"tag\" = lower(trim(\"project2\".\"recipe_tags\".\"tag\"))" + } + }, + "isRLSEnabled": false + }, + "project2.recipes": { + "name": "recipes", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "image_url": { + "name": "image_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cuisine": { + "name": "cuisine", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "difficulty": { + "name": "difficulty", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'private'" + }, + "prep_minutes": { + "name": "prep_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cook_minutes": { + "name": "cook_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "servings": { + "name": "servings", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "recipes_author_idx": { + "name": "recipes_author_idx", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_public_created_idx": { + "name": "recipes_public_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipes_author_id_users_id_fk": { + "name": "recipes_author_id_users_id_fk", + "tableFrom": "recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["author_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipes_title_not_blank": { + "name": "recipes_title_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"title\")) > 0" + }, + "recipes_category_not_blank": { + "name": "recipes_category_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"category\")) > 0" + }, + "recipes_cuisine_not_blank": { + "name": "recipes_cuisine_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"cuisine\")) > 0" + }, + "recipes_difficulty_valid": { + "name": "recipes_difficulty_valid", + "value": "\"project2\".\"recipes\".\"difficulty\" IN ('easy', 'medium', 'hard')" + }, + "recipes_visibility_valid": { + "name": "recipes_visibility_valid", + "value": "\"project2\".\"recipes\".\"visibility\" IN ('public', 'private')" + }, + "recipes_prep_minutes_nonnegative": { + "name": "recipes_prep_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"prep_minutes\" >= 0" + }, + "recipes_cook_minutes_nonnegative": { + "name": "recipes_cook_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"cook_minutes\" >= 0" + }, + "recipes_servings_positive": { + "name": "recipes_servings_positive", + "value": "\"project2\".\"recipes\".\"servings\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.saved_recipes": { + "name": "saved_recipes", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "saved_recipes_recipe_idx": { + "name": "saved_recipes_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "saved_recipes_user_id_users_id_fk": { + "name": "saved_recipes_user_id_users_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "saved_recipes_recipe_id_recipes_id_fk": { + "name": "saved_recipes_recipe_id_recipes_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "saved_recipes_user_id_recipe_id_pk": { + "name": "saved_recipes_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.sessions": { + "name": "sessions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.users": { + "name": "users", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/apps/api/migrations/meta/_journal.json b/apps/api/migrations/meta/_journal.json index ebc2b8a..f6e7dc8 100644 --- a/apps/api/migrations/meta/_journal.json +++ b/apps/api/migrations/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1791418622259, "tag": "0001_familiar_shocker", "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1791729925525, + "tag": "0002_recipe_model", + "breakpoints": true } ] } diff --git a/apps/api/src/db/migrate.ts b/apps/api/src/db/migrate.ts index 9f29dfd..1491bbb 100644 --- a/apps/api/src/db/migrate.ts +++ b/apps/api/src/db/migrate.ts @@ -2,5 +2,10 @@ import { drizzle } from 'drizzle-orm/node-postgres'; import { migrate } from 'drizzle-orm/node-postgres/migrator'; import { db } from './client.js'; -await migrate(drizzle(db), { migrationsFolder: 'apps/api/migrations' }); -await db.end(); +try { + // The original migrations reference project2 without creating it. + await db.query('CREATE SCHEMA IF NOT EXISTS project2'); + await migrate(drizzle(db), { migrationsFolder: 'apps/api/migrations' }); +} finally { + await db.end(); +} diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts index 01f90f1..a7d02b5 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -1,4 +1,10 @@ +import { sql } from 'drizzle-orm'; import { + check, + index, + integer, + numeric, + primaryKey, pgSchema, text, timestamp, @@ -8,11 +14,6 @@ import { const project2 = pgSchema('project2'); -export const recipes = project2.table('recipes', { - id: uuid().primaryKey().defaultRandom(), - title: text().notNull(), -}); - export const users = project2.table( 'users', { @@ -34,3 +35,170 @@ export const sessions = project2.table('sessions', { .references(() => users.id, { onDelete: 'cascade' }), expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(), }); + +// Each recipe belongs to one user. Ingredient and instruction rows belong to +// the recipe and are removed automatically when that recipe is deleted. +export const recipes = project2.table( + 'recipes', + { + id: uuid().primaryKey().defaultRandom(), + authorId: uuid('author_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + title: text().notNull(), + description: text().notNull(), + imageUrl: text('image_url'), + category: text().notNull(), + cuisine: text().notNull(), + difficulty: text({ enum: ['easy', 'medium', 'hard'] }).notNull(), + visibility: text({ enum: ['public', 'private'] }) + .notNull() + .default('private'), + prepMinutes: integer('prep_minutes').notNull(), + cookMinutes: integer('cook_minutes').notNull(), + servings: integer().notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + index('recipes_author_idx').on(table.authorId), + index('recipes_public_created_idx') + .on(table.createdAt, table.id) + .where(sql`${table.visibility} = 'public'`), + check('recipes_title_not_blank', sql`length(trim(${table.title})) > 0`), + check( + 'recipes_category_not_blank', + sql`length(trim(${table.category})) > 0`, + ), + check('recipes_cuisine_not_blank', sql`length(trim(${table.cuisine})) > 0`), + check( + 'recipes_difficulty_valid', + sql`${table.difficulty} IN ('easy', 'medium', 'hard')`, + ), + check( + 'recipes_visibility_valid', + sql`${table.visibility} IN ('public', 'private')`, + ), + check('recipes_prep_minutes_nonnegative', sql`${table.prepMinutes} >= 0`), + check('recipes_cook_minutes_nonnegative', sql`${table.cookMinutes} >= 0`), + check('recipes_servings_positive', sql`${table.servings} > 0`), + ], +); + +export const recipeIngredients = project2.table( + 'recipe_ingredients', + { + id: uuid().primaryKey().defaultRandom(), + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + name: text().notNull(), + // PostgreSQL numeric preserves decimal quantities; Drizzle returns strings. + amount: numeric({ precision: 12, scale: 4 }).notNull(), + unit: text().notNull(), + note: text(), + position: integer().notNull(), + }, + (table) => [ + uniqueIndex('recipe_ingredients_recipe_position_unique').on( + table.recipeId, + table.position, + ), + check( + 'recipe_ingredients_name_not_blank', + sql`length(trim(${table.name})) > 0`, + ), + check( + 'recipe_ingredients_amount_positive', + sql`${table.amount} > 0 AND ${table.amount} <> 'NaN'::numeric`, + ), + check('recipe_ingredients_position_positive', sql`${table.position} > 0`), + ], +); + +export const recipeInstructions = project2.table( + 'recipe_instructions', + { + id: uuid().primaryKey().defaultRandom(), + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + text: text().notNull(), + position: integer().notNull(), + }, + (table) => [ + uniqueIndex('recipe_instructions_recipe_position_unique').on( + table.recipeId, + table.position, + ), + check( + 'recipe_instructions_text_not_blank', + sql`length(trim(${table.text})) > 0`, + ), + check('recipe_instructions_position_positive', sql`${table.position} > 0`), + ], +); + +export const recipeTags = project2.table( + 'recipe_tags', + { + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + tag: text().notNull(), + }, + (table) => [ + primaryKey({ columns: [table.recipeId, table.tag] }), + check( + 'recipe_tags_normalized', + sql`length(${table.tag}) > 0 AND ${table.tag} = lower(trim(${table.tag}))`, + ), + ], +); + +export const savedRecipes = project2.table( + 'saved_recipes', + { + userId: uuid('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + primaryKey({ columns: [table.userId, table.recipeId] }), + index('saved_recipes_recipe_idx').on(table.recipeId), + ], +); + +export const ratings = project2.table( + 'ratings', + { + userId: uuid('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + recipeId: uuid('recipe_id') + .notNull() + .references(() => recipes.id, { onDelete: 'cascade' }), + score: integer().notNull(), + createdAt: timestamp('created_at', { withTimezone: true }) + .defaultNow() + .notNull(), + updatedAt: timestamp('updated_at', { withTimezone: true }) + .defaultNow() + .notNull(), + }, + (table) => [ + primaryKey({ columns: [table.userId, table.recipeId] }), + index('ratings_recipe_idx').on(table.recipeId), + check('ratings_score_valid', sql`${table.score} BETWEEN 1 AND 5`), + ], +); diff --git a/docs/database-model.md b/docs/database-model.md new file mode 100644 index 0000000..2683ff1 --- /dev/null +++ b/docs/database-model.md @@ -0,0 +1,111 @@ +# Databasemodell + +Modellen bruker PostgreSQL og Drizzle i skjemaet `project2`. Brukere og sesjoner +fra autentiseringen er beholdt. API-operasjoner kommer i neste steg. + +```mermaid +erDiagram + users ||--o{ sessions : har + users ||--o{ recipes : eier + recipes ||--o{ recipe_ingredients : inneholder + recipes ||--o{ recipe_instructions : inneholder + recipes ||--o{ recipe_tags : har + users ||--o{ saved_recipes : lagrer + recipes ||--o{ saved_recipes : lagres + users ||--o{ ratings : vurderer + recipes ||--o{ ratings : vurderes +``` + +`||--o{` betyr at én rad kan ha null eller flere tilknyttede rader. + +| Tabell | Innhold og regler | +| --------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| `users` | Eksisterende brukere med unik e-post og passordhash. | +| `sessions` | Eksisterende innloggingssesjoner med bruker og utløpstid. | +| `recipes` | Forfatter, tittel, beskrivelse, bilde-URL, kategori, kjøkken, vanskelighetsgrad, synlighet, tider, porsjoner og datoer. | +| `recipe_ingredients` | Navn, mengde, enhet, valgfri merknad og rekkefølge i oppskriften. | +| `recipe_instructions` | Tekst og rekkefølge for hvert steg. | +| `recipe_tags` | Enkle tagger per oppskrift, uten duplikater. | +| `saved_recipes` | Hvilke brukere som har lagret hvilke oppskrifter. | +| `ratings` | Én vurdering mellom 1 og 5 per bruker per oppskrift. | + +## Viktige valg + +- `recipes.author_id` peker på `users.id`. Oppskrifter er private som standard. +- Vanskelighetsgrad er `easy`, `medium` eller `hard`; synlighet er `public` eller + `private`. Både TypeScript og databasekontroller begrenser verdiene. +- Kategori og kjøkken er tekst. API-et bør normalisere disse mot frontendens + valglister. Egne kategoritabeller kan innføres senere ved behov. +- `image_url` er valgfri. Selve bildefilen lagres ikke i databasen. +- Ingrediensmengder bruker `numeric(12,4)`, som gir nøyaktige desimaltall med + opptil åtte sifre før komma. Drizzle/pg returnerer verdiene som strenger. + API-et må konvertere dem til frontendens tallformat ved behov. +- Mengder og porsjoner må være positive. Tider kan være null, men ikke negative. +- Ingredienser og steg har en unik, positiv `position` innenfor hver oppskrift. + Hent alltid med `ORDER BY position`; databasen krever ikke sammenhengende tall. + Tom ingrediensenhet er tillatt for for eksempel «2 egg». +- Tagger lagres med små bokstaver uten innledende/avsluttende mellomrom. +- Gjennomsnittsvurdering, antall vurderinger og antall lagringer beregnes fra + tabellene. De lagres ikke som ekstra tellere på oppskriften. +- `isSaved` og `isCreatedByCurrentUser` beregnes ut fra innlogget bruker. +- Databasetriggere oppdaterer `updated_at` ved endring av oppskrifter og + vurderinger, også gjennom vanlig SQL. Endring av bare ingredienser, steg eller + tagger må også oppdatere foreldreraden i den senere API-transaksjonen. + +## Sletting og indekser + +Sletting av en oppskrift sletter automatisk ingredienser, steg, tagger, lagringer +og vurderinger. Sletting av en bruker sletter brukerens oppskrifter, sesjoner, +lagringer og vurderinger. Dette er bevisst valgt med `ON DELETE CASCADE`. +Brukersletting bør derfor behandles som en tydelig, destruktiv handling i et +senere API. + +Indekser støtter oppslag etter forfatter, offentlige oppskrifter sortert etter +opprettelsesdato og ID, og lagringer/vurderinger per oppskrift. De sammensatte +primærnøklene støtter brukerens egne lagringer og vurderinger. Unike indekser +støtter ordnede ingredienser og steg. Flere søke- og filterindekser bør velges +etter at API-spørringene finnes og kan måles. + +## Klar for CRUD + +1. **Opprett:** Bruk innlogget bruker som forfatter. Sett inn oppskrift, + ingredienser, steg og tagger i én transaksjon. +2. **Les:** Returner offentlige oppskrifter eller brukerens egne private + oppskrifter. Hent ingredienser/steg i riktig rekkefølge. +3. **Oppdater:** Kontroller eierskap og oppdater hele oppskriften i én transaksjon. + Ved erstatning av ingredienser/steg: slett de gamle radene og sett inn de nye + innenfor samme transaksjon for å unngå midlertidige posisjonskonflikter. +4. **Slett:** Kontroller eierskap før oppskriften slettes. Databasen rydder barna. + +Bruk `INSERT ... ON CONFLICT` for idempotent lagring eller endring av en +vurdering. Bruk `DELETE` for å fjerne lagring/vurdering. API-et må validere tilgang +til oppskriften, og håndheve at eiere ikke vurderer eller lagrer egne oppskrifter. +Fremmednøkler kontrollerer koblinger, ikke hvem som er innlogget. API-et må også +kreve minst én ingrediens og ett steg dersom dette er et produktkrav. + +## Migrasjon og tester + +Kjør fra prosjektroten med `DATABASE_URL` i `.env`: + +```powershell +npm.cmd run db:check +npm.cmd run test:db +npm.cmd run db:migrate +``` + +`test:db` krever lokal PostgreSQL og rettighet til å opprette skjemaer. Den bruker +et tilfeldig skjema i én transaksjon og ruller alt tilbake, inkludert tabellene. +Den endrer ikke `project2` eller migrasjonshistorikken. Testen kontrollerer +migrasjoner, bevaring av auth-data, datakvalitet, unike koblinger, desimaltall, +tidsstempler og automatisk sletting. + +`db:migrate` gjør de faktiske endringene. Migrasjon `0002_recipe_model.sql` +forutsetter at den gamle `recipes`-tabellen med bare ID og tittel er tom. Hvis +den inneholder rader, stopper migrasjonen med en forklarende feil. Ta vare på +dataene og lag en eksplisitt overgang med riktig forfatter og innhold før +migrasjonen kjøres videre; migrasjonen gjetter ikke eierskap eller sletter data. +Eksisterende brukere og sesjoner beholdes. + +Triggere og migrasjonens kontroll av gamle oppskrifter er håndskrevet SQL i +`0002_recipe_model.sql`. Drizzle-snapshotet beskriver tabeller, indekser og +constraints; behold de håndskrevne delene ved senere endringer. diff --git a/package.json b/package.json index eb80514..4c96a1d 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,8 @@ "typecheck": "tsc -p apps/web/tsconfig.json && tsc -p apps/api/tsconfig.json --noEmit", "test": "vitest run --passWithNoTests", "test:e2e": "playwright test", - "check": "npm run format:check && npm run lint && npm run types:check && npm run db:check && npm run typecheck && npm test && npm run build" + "check": "npm run format:check && npm run lint && npm run types:check && npm run db:check && npm run typecheck && npm test && npm run build", + "test:db": "tsx --env-file-if-exists=.env scripts/test-database.ts" }, "devDependencies": { "@eslint/js": "9.39.5", diff --git a/scripts/test-database.ts b/scripts/test-database.ts new file mode 100644 index 0000000..09f16c7 --- /dev/null +++ b/scripts/test-database.ts @@ -0,0 +1,329 @@ +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { test } from 'node:test'; +import { Pool } from 'pg'; + +// Run separately from unit tests: requires PostgreSQL and schema-create rights. +// Every change, including DDL, is rolled back; project2 is never touched. +await test('recipe model against PostgreSQL', async (t) => { + assert.ok( + process.env.DATABASE_URL, + 'Set DATABASE_URL in .env before running test:db.', + ); + const pool = new Pool({ + connectionString: process.env.DATABASE_URL, + connectionTimeoutMillis: 5000, + }); + const client = await pool.connect(); + const schema = 'model_test_' + randomUUID().replaceAll('-', ''); + const table = (name: string) => '"' + schema + '"."' + name + '"'; + const journal = JSON.parse( + await readFile('apps/api/migrations/meta/_journal.json', 'utf8'), + ) as { entries: { tag: string }[] }; + const migrations = await Promise.all( + journal.entries.map(async ({ tag }) => + ( + await readFile('apps/api/migrations/' + tag + '.sql', 'utf8') + ).replaceAll('"project2"', '"' + schema + '"'), + ), + ); + async function rejectsSql(sql: string, values: unknown[], code: string) { + await client.query('SAVEPOINT invalid_write'); + try { + await assert.rejects( + client.query(sql, values), + (error: unknown) => + typeof error === 'object' && + error !== null && + 'code' in error && + error.code === code, + ); + } finally { + await client.query('ROLLBACK TO SAVEPOINT invalid_write'); + await client.query('RELEASE SAVEPOINT invalid_write'); + } + } + try { + await client.query('BEGIN'); + await client.query('CREATE SCHEMA "' + schema + '"'); + for (const migration of migrations.slice(0, 2)) + await client.query(migration); + const users = await client.query<{ id: string }>( + 'INSERT INTO ' + + table('users') + + ' (name, email, password_hash) VALUES ($1,$2,$3),($4,$5,$6) RETURNING id', + [ + 'Author', + 'author@test.local', + 'hash', + 'Reader', + 'reader@test.local', + 'hash', + ], + ); + const authorId = users.rows[0]!.id; + const readerId = users.rows[1]!.id; + await client.query( + 'INSERT INTO ' + + table('sessions') + + ' (user_id, expires_at) VALUES ($1, $2)', + [authorId, new Date(Date.now() + 86400000)], + ); + const recipeMigration = migrations[2]!; + await t.test( + 'legacy recipe data blocks migration without losing auth data', + async () => { + await client.query('SAVEPOINT legacy_data'); + await client.query( + 'INSERT INTO ' + table('recipes') + ' (title) VALUES ($1)', + ['Legacy recipe'], + ); + await assert.rejects( + client.query(recipeMigration), + /empty legacy recipes table/, + ); + await client.query('ROLLBACK TO SAVEPOINT legacy_data'); + await client.query('RELEASE SAVEPOINT legacy_data'); + }, + ); + await t.test( + 'migrations preserve existing users and sessions', + async () => { + await client.query(recipeMigration); + assert.equal( + ( + await client.query( + 'SELECT count(*)::int AS count FROM ' + table('users'), + ) + ).rows[0].count, + 2, + ); + assert.equal( + ( + await client.query( + 'SELECT count(*)::int AS count FROM ' + table('sessions'), + ) + ).rows[0].count, + 1, + ); + }, + ); + const insertRecipe = + 'INSERT INTO ' + + table('recipes') + + ' (author_id,title,description,category,cuisine,difficulty,prep_minutes,cook_minutes,servings) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) RETURNING id,visibility'; + const recipeValues = [ + authorId, + 'Soup', + 'Simple soup', + 'Soup', + 'Norwegian', + 'easy', + 5, + 20, + 4, + ]; + const recipe = ( + await client.query<{ id: string; visibility: string }>( + insertRecipe, + recipeValues, + ) + ).rows[0]!; + const recipeId = recipe.id; + await t.test( + 'recipe defaults to private and rejects invalid fields/author', + async () => { + assert.equal(recipe.visibility, 'private'); + for (const [field, value] of [ + [8, 0], + [6, -1], + [7, -1], + [5, 'impossible'], + [1, ' '], + ] as const) { + const values = [...recipeValues]; + values[field] = value; + await rejectsSql(insertRecipe, values, '23514'); + } + await rejectsSql( + insertRecipe, + [randomUUID(), ...recipeValues.slice(1)], + '23503', + ); + await rejectsSql( + 'UPDATE ' + table('recipes') + ' SET visibility=$1 WHERE id=$2', + ['invalid', recipeId], + '23514', + ); + }, + ); + const ingredientSql = + 'INSERT INTO ' + + table('recipe_ingredients') + + ' (recipe_id,name,amount,unit,position) VALUES ($1,$2,$3,$4,$5)'; + await t.test( + 'decimal amounts and ordered ingredients/instructions', + async () => { + await client.query(ingredientSql, [ + recipeId, + 'Salt', + '0.125', + 'tsp', + 1, + ]); + assert.equal( + ( + await client.query( + 'SELECT amount FROM ' + table('recipe_ingredients'), + ) + ).rows[0].amount, + '0.1250', + ); + await rejectsSql( + ingredientSql, + [recipeId, 'Salt', '1', 'tsp', 1], + '23505', + ); + await rejectsSql( + ingredientSql, + [recipeId, 'Salt', '-1', 'tsp', 2], + '23514', + ); + await rejectsSql( + ingredientSql, + [recipeId, 'Salt', 'NaN', 'tsp', 2], + '23514', + ); + await rejectsSql( + ingredientSql, + [recipeId, 'Salt', '1', 'tsp', 0], + '23514', + ); + const instructionSql = + 'INSERT INTO ' + + table('recipe_instructions') + + ' (recipe_id,text,position) VALUES ($1,$2,$3)'; + await client.query(instructionSql, [recipeId, 'Stir', 1]); + await rejectsSql(instructionSql, [recipeId, 'Stir again', 1], '23505'); + await rejectsSql(instructionSql, [recipeId, ' ', 2], '23514'); + }, + ); + await t.test( + 'unique tags, saves and ratings with valid scores', + async () => { + const tagSql = + 'INSERT INTO ' + + table('recipe_tags') + + ' (recipe_id,tag) VALUES ($1,$2)'; + await client.query(tagSql, [recipeId, 'quick']); + await rejectsSql(tagSql, [recipeId, 'quick'], '23505'); + await rejectsSql(tagSql, [recipeId, ' Quick '], '23514'); + const saveSql = + 'INSERT INTO ' + + table('saved_recipes') + + ' (user_id,recipe_id) VALUES ($1,$2)'; + await client.query(saveSql, [readerId, recipeId]); + await rejectsSql(saveSql, [readerId, recipeId], '23505'); + const ratingSql = + 'INSERT INTO ' + + table('ratings') + + ' (user_id,recipe_id,score) VALUES ($1,$2,$3)'; + await client.query(ratingSql, [readerId, recipeId, 4]); + await rejectsSql(ratingSql, [readerId, recipeId, 5], '23505'); + await rejectsSql(ratingSql, [authorId, recipeId, 0], '23514'); + await rejectsSql(ratingSql, [authorId, recipeId, 6], '23514'); + }, + ); + await t.test( + 'updates touch timestamps through SQL and ratings can be changed', + async () => { + for (const name of ['recipes', 'ratings']) { + await client.query('UPDATE ' + table(name) + ' SET updated_at=$1', [ + '2000-01-01', + ]); + assert.ok( + ( + await client.query('SELECT updated_at FROM ' + table(name)) + ).rows[0].updated_at.getFullYear() > 2000, + ); + } + await client.query( + 'UPDATE ' + + table('ratings') + + ' SET score=5 WHERE user_id=$1 AND recipe_id=$2', + [readerId, recipeId], + ); + assert.equal( + ( + await client.query( + 'SELECT avg(score)::float AS average FROM ' + table('ratings'), + ) + ).rows[0].average, + 5, + ); + }, + ); + await t.test( + 'recipe deletion cascades to dependent rows, preserving users', + async () => { + await client.query('DELETE FROM ' + table('recipes') + ' WHERE id=$1', [ + recipeId, + ]); + for (const name of [ + 'recipe_ingredients', + 'recipe_instructions', + 'recipe_tags', + 'saved_recipes', + 'ratings', + ]) { + assert.equal( + ( + await client.query( + 'SELECT count(*)::int AS count FROM ' + table(name), + ) + ).rows[0].count, + 0, + ); + } + assert.equal( + ( + await client.query( + 'SELECT count(*)::int AS count FROM ' + table('users'), + ) + ).rows[0].count, + 2, + ); + }, + ); + await t.test( + 'user deletion removes owned recipes and sessions', + async () => { + await client.query(insertRecipe, recipeValues); + await client.query('DELETE FROM ' + table('users') + ' WHERE id=$1', [ + authorId, + ]); + assert.equal( + ( + await client.query( + 'SELECT count(*)::int AS count FROM ' + table('recipes'), + ) + ).rows[0].count, + 0, + ); + assert.equal( + ( + await client.query( + 'SELECT count(*)::int AS count FROM ' + table('sessions'), + ) + ).rows[0].count, + 0, + ); + }, + ); + } finally { + await client.query('ROLLBACK'); + client.release(); + await pool.end(); + } +}); From f5efe30f0aeb541df03208f31f11556fc731a175 Mon Sep 17 00:00:00 2001 From: Hasan Mohammad Fawzi Date: Mon, 12 Oct 2026 11:37:02 +0200 Subject: [PATCH 4/4] fix(db): address recipe model review feedback --- apps/api/migrations/0003_recipe_review.sql | 10 + apps/api/migrations/meta/0003_snapshot.json | 731 ++++++++++++++++++++ apps/api/migrations/meta/_journal.json | 7 + apps/api/src/db/schema.ts | 16 +- docs/database-model.md | 16 +- scripts/test-database.ts | 104 ++- 6 files changed, 877 insertions(+), 7 deletions(-) create mode 100644 apps/api/migrations/0003_recipe_review.sql create mode 100644 apps/api/migrations/meta/0003_snapshot.json diff --git a/apps/api/migrations/0003_recipe_review.sql b/apps/api/migrations/0003_recipe_review.sql new file mode 100644 index 0000000..df53def --- /dev/null +++ b/apps/api/migrations/0003_recipe_review.sql @@ -0,0 +1,10 @@ +ALTER TABLE "project2"."recipes" DROP CONSTRAINT "recipes_category_not_blank";--> statement-breakpoint +ALTER TABLE "project2"."recipes" ALTER COLUMN "cuisine" DROP NOT NULL;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD COLUMN "source_recipe_id" uuid;--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_source_recipe_id_recipes_id_fk" FOREIGN KEY ("source_recipe_id") REFERENCES "project2"."recipes"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "recipes_source_idx" ON "project2"."recipes" USING btree ("source_recipe_id");--> statement-breakpoint +-- Normalize known category labels without guessing mappings for unknown values. +-- Unknown categories abort the migration and require an explicit correction. +UPDATE "project2"."recipes" SET "category" = lower(trim("category")) +WHERE "category" <> lower(trim("category"));--> statement-breakpoint +ALTER TABLE "project2"."recipes" ADD CONSTRAINT "recipes_category_valid" CHECK ("project2"."recipes"."category" IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')); diff --git a/apps/api/migrations/meta/0003_snapshot.json b/apps/api/migrations/meta/0003_snapshot.json new file mode 100644 index 0000000..ef92bf5 --- /dev/null +++ b/apps/api/migrations/meta/0003_snapshot.json @@ -0,0 +1,731 @@ +{ + "id": "c0ecbb19-5a20-4d7a-808d-836ae2992c9e", + "prevId": "078adb6f-bfdc-42b6-9e70-e621fc612161", + "version": "7", + "dialect": "postgresql", + "tables": { + "project2.ratings": { + "name": "ratings", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "score": { + "name": "score", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "ratings_recipe_idx": { + "name": "ratings_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "ratings_user_id_users_id_fk": { + "name": "ratings_user_id_users_id_fk", + "tableFrom": "ratings", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "ratings_recipe_id_recipes_id_fk": { + "name": "ratings_recipe_id_recipes_id_fk", + "tableFrom": "ratings", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "ratings_user_id_recipe_id_pk": { + "name": "ratings_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "ratings_score_valid": { + "name": "ratings_score_valid", + "value": "\"project2\".\"ratings\".\"score\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_ingredients": { + "name": "recipe_ingredients", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "numeric(12, 4)", + "primaryKey": false, + "notNull": true + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_ingredients_recipe_position_unique": { + "name": "recipe_ingredients_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_ingredients_recipe_id_recipes_id_fk": { + "name": "recipe_ingredients_recipe_id_recipes_id_fk", + "tableFrom": "recipe_ingredients", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_ingredients_name_not_blank": { + "name": "recipe_ingredients_name_not_blank", + "value": "length(trim(\"project2\".\"recipe_ingredients\".\"name\")) > 0" + }, + "recipe_ingredients_amount_positive": { + "name": "recipe_ingredients_amount_positive", + "value": "\"project2\".\"recipe_ingredients\".\"amount\" > 0 AND \"project2\".\"recipe_ingredients\".\"amount\" <> 'NaN'::numeric" + }, + "recipe_ingredients_position_positive": { + "name": "recipe_ingredients_position_positive", + "value": "\"project2\".\"recipe_ingredients\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_instructions": { + "name": "recipe_instructions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "recipe_instructions_recipe_position_unique": { + "name": "recipe_instructions_recipe_position_unique", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipe_instructions_recipe_id_recipes_id_fk": { + "name": "recipe_instructions_recipe_id_recipes_id_fk", + "tableFrom": "recipe_instructions", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_instructions_text_not_blank": { + "name": "recipe_instructions_text_not_blank", + "value": "length(trim(\"project2\".\"recipe_instructions\".\"text\")) > 0" + }, + "recipe_instructions_position_positive": { + "name": "recipe_instructions_position_positive", + "value": "\"project2\".\"recipe_instructions\".\"position\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.recipe_tags": { + "name": "recipe_tags", + "schema": "project2", + "columns": { + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "recipe_tags_recipe_id_recipes_id_fk": { + "name": "recipe_tags_recipe_id_recipes_id_fk", + "tableFrom": "recipe_tags", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "recipe_tags_recipe_id_tag_pk": { + "name": "recipe_tags_recipe_id_tag_pk", + "columns": ["recipe_id", "tag"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipe_tags_normalized": { + "name": "recipe_tags_normalized", + "value": "length(\"project2\".\"recipe_tags\".\"tag\") > 0 AND \"project2\".\"recipe_tags\".\"tag\" = lower(trim(\"project2\".\"recipe_tags\".\"tag\"))" + } + }, + "isRLSEnabled": false + }, + "project2.recipes": { + "name": "recipes", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_recipe_id": { + "name": "source_recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "image_url": { + "name": "image_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cuisine": { + "name": "cuisine", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "difficulty": { + "name": "difficulty", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'private'" + }, + "prep_minutes": { + "name": "prep_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cook_minutes": { + "name": "cook_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "servings": { + "name": "servings", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "recipes_author_idx": { + "name": "recipes_author_idx", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_source_idx": { + "name": "recipes_source_idx", + "columns": [ + { + "expression": "source_recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "recipes_public_created_idx": { + "name": "recipes_public_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"project2\".\"recipes\".\"visibility\" = 'public'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "recipes_author_id_users_id_fk": { + "name": "recipes_author_id_users_id_fk", + "tableFrom": "recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["author_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "recipes_source_recipe_id_recipes_id_fk": { + "name": "recipes_source_recipe_id_recipes_id_fk", + "tableFrom": "recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["source_recipe_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "recipes_title_not_blank": { + "name": "recipes_title_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"title\")) > 0" + }, + "recipes_category_valid": { + "name": "recipes_category_valid", + "value": "\"project2\".\"recipes\".\"category\" IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')" + }, + "recipes_cuisine_not_blank": { + "name": "recipes_cuisine_not_blank", + "value": "length(trim(\"project2\".\"recipes\".\"cuisine\")) > 0" + }, + "recipes_difficulty_valid": { + "name": "recipes_difficulty_valid", + "value": "\"project2\".\"recipes\".\"difficulty\" IN ('easy', 'medium', 'hard')" + }, + "recipes_visibility_valid": { + "name": "recipes_visibility_valid", + "value": "\"project2\".\"recipes\".\"visibility\" IN ('public', 'private')" + }, + "recipes_prep_minutes_nonnegative": { + "name": "recipes_prep_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"prep_minutes\" >= 0" + }, + "recipes_cook_minutes_nonnegative": { + "name": "recipes_cook_minutes_nonnegative", + "value": "\"project2\".\"recipes\".\"cook_minutes\" >= 0" + }, + "recipes_servings_positive": { + "name": "recipes_servings_positive", + "value": "\"project2\".\"recipes\".\"servings\" > 0" + } + }, + "isRLSEnabled": false + }, + "project2.saved_recipes": { + "name": "saved_recipes", + "schema": "project2", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "saved_recipes_recipe_idx": { + "name": "saved_recipes_recipe_idx", + "columns": [ + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "saved_recipes_user_id_users_id_fk": { + "name": "saved_recipes_user_id_users_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "saved_recipes_recipe_id_recipes_id_fk": { + "name": "saved_recipes_recipe_id_recipes_id_fk", + "tableFrom": "saved_recipes", + "tableTo": "recipes", + "schemaTo": "project2", + "columnsFrom": ["recipe_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "saved_recipes_user_id_recipe_id_pk": { + "name": "saved_recipes_user_id_recipe_id_pk", + "columns": ["user_id", "recipe_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.sessions": { + "name": "sessions", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "schemaTo": "project2", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "project2.users": { + "name": "users", + "schema": "project2", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/apps/api/migrations/meta/_journal.json b/apps/api/migrations/meta/_journal.json index f6e7dc8..4d08ec8 100644 --- a/apps/api/migrations/meta/_journal.json +++ b/apps/api/migrations/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1791729925525, "tag": "0002_recipe_model", "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1791796199161, + "tag": "0003_recipe_review", + "breakpoints": true } ] } diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts index a7d02b5..cc6c5f3 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -1,5 +1,6 @@ import { sql } from 'drizzle-orm'; import { + type AnyPgColumn, check, index, integer, @@ -45,11 +46,17 @@ export const recipes = project2.table( authorId: uuid('author_id') .notNull() .references(() => users.id, { onDelete: 'cascade' }), + sourceRecipeId: uuid('source_recipe_id').references( + (): AnyPgColumn => recipes.id, + { onDelete: 'set null' }, + ), title: text().notNull(), description: text().notNull(), imageUrl: text('image_url'), - category: text().notNull(), - cuisine: text().notNull(), + category: text({ + enum: ['breakfast', 'lunch', 'dinner', 'dessert', 'soup'], + }).notNull(), + cuisine: text(), difficulty: text({ enum: ['easy', 'medium', 'hard'] }).notNull(), visibility: text({ enum: ['public', 'private'] }) .notNull() @@ -66,13 +73,14 @@ export const recipes = project2.table( }, (table) => [ index('recipes_author_idx').on(table.authorId), + index('recipes_source_idx').on(table.sourceRecipeId), index('recipes_public_created_idx') .on(table.createdAt, table.id) .where(sql`${table.visibility} = 'public'`), check('recipes_title_not_blank', sql`length(trim(${table.title})) > 0`), check( - 'recipes_category_not_blank', - sql`length(trim(${table.category})) > 0`, + 'recipes_category_valid', + sql`${table.category} IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')`, ), check('recipes_cuisine_not_blank', sql`length(trim(${table.cuisine})) > 0`), check( diff --git a/docs/database-model.md b/docs/database-model.md index 2683ff1..f90830d 100644 --- a/docs/database-model.md +++ b/docs/database-model.md @@ -7,6 +7,7 @@ fra autentiseringen er beholdt. API-operasjoner kommer i neste steg. erDiagram users ||--o{ sessions : har users ||--o{ recipes : eier + recipes |o--o{ recipes : kopiert_fra recipes ||--o{ recipe_ingredients : inneholder recipes ||--o{ recipe_instructions : inneholder recipes ||--o{ recipe_tags : har @@ -34,8 +35,13 @@ erDiagram - `recipes.author_id` peker på `users.id`. Oppskrifter er private som standard. - Vanskelighetsgrad er `easy`, `medium` eller `hard`; synlighet er `public` eller `private`. Både TypeScript og databasekontroller begrenser verdiene. -- Kategori og kjøkken er tekst. API-et bør normalisere disse mot frontendens - valglister. Egne kategoritabeller kan innføres senere ved behov. +- Kategori bruker faste nøkler: `breakfast`, `lunch`, `dinner`, `dessert`, `soup`. + En databasekontroll avviser andre verdier; klienten viser lesbare etiketter. +- `cuisine` er valgfri fritekst (`NULL` når ukjent); oppgitt tekst må være ikke-tom. +- `source_recipe_id` er en valgfri henvisning til originaloppskriften. Kopier er + egne oppskrifter, uavhengige av bokmerker. Ved sletting av originalen settes + henvisningen til `NULL`, mens kopien beholdes. Varig kildeattribusjon med + lagret forfatternavn/tittel kan legges til senere. - `image_url` er valgfri. Selve bildefilen lagres ikke i databasen. - Ingrediensmengder bruker `numeric(12,4)`, som gir nøyaktige desimaltall med opptil åtte sifre før komma. Drizzle/pg returnerer verdiene som strenger. @@ -109,3 +115,9 @@ Eksisterende brukere og sesjoner beholdes. Triggere og migrasjonens kontroll av gamle oppskrifter er håndskrevet SQL i `0002_recipe_model.sql`. Drizzle-snapshotet beskriver tabeller, indekser og constraints; behold de håndskrevne delene ved senere endringer. + +Migrasjon `0003_recipe_review.sql` gjør kjøkken valgfritt, legger til kildehenvisning +og håndhever kategorinøklene. Eksisterende kategorier normaliseres til små +bokstaver uten ytre mellomrom. Ukjente kategorier stopper migrasjonen og m? +korrigeres eksplisitt. `0002` er beholdt uendret. API-et må kontrollere tilgang +til originalen ved kopiering og kopiere ingredienser/steg i samme transaksjon. diff --git a/scripts/test-database.ts b/scripts/test-database.ts index 09f16c7..23badab 100644 --- a/scripts/test-database.ts +++ b/scripts/test-database.ts @@ -109,6 +109,25 @@ await test('recipe model against PostgreSQL', async (t) => { ); }, ); + await client.query( + 'INSERT INTO ' + + table('recipes') + + ' (author_id,title,description,category,cuisine,difficulty,prep_minutes,cook_minutes,servings) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)', + [authorId, 'Legacy soup', '', ' Soup ', 'Norwegian', 'easy', 0, 10, 1], + ); + await t.test( + 'review migration normalizes existing category labels', + async () => { + for (const migration of migrations.slice(3)) + await client.query(migration); + assert.equal( + (await client.query('SELECT category FROM ' + table('recipes'))) + .rows[0].category, + 'soup', + ); + await client.query('DELETE FROM ' + table('recipes')); + }, + ); const insertRecipe = 'INSERT INTO ' + table('recipes') + @@ -117,7 +136,7 @@ await test('recipe model against PostgreSQL', async (t) => { authorId, 'Soup', 'Simple soup', - 'Soup', + 'soup', 'Norwegian', 'easy', 5, @@ -141,6 +160,9 @@ await test('recipe model against PostgreSQL', async (t) => { [7, -1], [5, 'impossible'], [1, ' '], + [3, 'Soup'], + [3, ' dinner '], + [3, 'unknown'], ] as const) { const values = [...recipeValues]; values[field] = value; @@ -158,6 +180,86 @@ await test('recipe model against PostgreSQL', async (t) => { ); }, ); + await t.test('optional cuisine and canonical categories', async () => { + await client.query('SAVEPOINT optional_fields'); + for (const category of [ + 'breakfast', + 'lunch', + 'dinner', + 'dessert', + 'soup', + ]) { + const values: unknown[] = [...recipeValues]; + values[3] = category; + values[4] = null; + const row = (await client.query(insertRecipe, values)).rows[0]; + assert.equal( + ( + await client.query( + 'SELECT cuisine FROM ' + table('recipes') + ' WHERE id=$1', + [row.id], + ) + ).rows[0].cuisine, + null, + ); + } + await client.query('ROLLBACK TO SAVEPOINT optional_fields'); + await client.query('RELEASE SAVEPOINT optional_fields'); + }); + await t.test('copies survive unsaving and source deletion', async () => { + await client.query('SAVEPOINT copies'); + const sourceId = (await client.query(insertRecipe, recipeValues)).rows[0] + .id; + const copyId = ( + await client.query(insertRecipe, [readerId, ...recipeValues.slice(1)]) + ).rows[0].id; + await client.query( + 'UPDATE ' + table('recipes') + ' SET source_recipe_id=$1 WHERE id=$2', + [sourceId, copyId], + ); + await rejectsSql( + 'UPDATE ' + table('recipes') + ' SET source_recipe_id=$1 WHERE id=$2', + [randomUUID(), copyId], + '23503', + ); + await client.query( + 'INSERT INTO ' + + table('saved_recipes') + + ' (user_id,recipe_id) VALUES ($1,$2)', + [readerId, sourceId], + ); + await client.query( + 'DELETE FROM ' + + table('saved_recipes') + + ' WHERE user_id=$1 AND recipe_id=$2', + [readerId, sourceId], + ); + assert.equal( + ( + await client.query( + 'SELECT source_recipe_id FROM ' + table('recipes') + ' WHERE id=$1', + [copyId], + ) + ).rows[0].source_recipe_id, + sourceId, + ); + await client.query('DELETE FROM ' + table('recipes') + ' WHERE id=$1', [ + sourceId, + ]); + const copy = ( + await client.query( + 'SELECT author_id,source_recipe_id,title FROM ' + + table('recipes') + + ' WHERE id=$1', + [copyId], + ) + ).rows[0]; + assert.equal(copy.author_id, readerId); + assert.equal(copy.source_recipe_id, null); + assert.equal(copy.title, 'Soup'); + await client.query('ROLLBACK TO SAVEPOINT copies'); + await client.query('RELEASE SAVEPOINT copies'); + }); const ingredientSql = 'INSERT INTO ' + table('recipe_ingredients') +