Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -59,6 +59,18 @@ 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.

### Protected routes

`/cookbook` and `/recipes/new` require a validated session. On refresh, the router waits for session restoration before rendering protected content or redirecting to login. A temporary API/network error shows a retry action and preserves the token. Successful login or registration returns to the requested protected URL, including its query and hash. Explore and recipe details remain public. This is client-side routing; future protected API operations must enforce authentication and ownership on the server.

## Nyttige kommandoer

| Kommando | Bruk |
Expand Down Expand Up @@ -103,8 +115,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

Expand Down
16 changes: 16 additions & 0 deletions apps/api/migrations/0001_familiar_shocker.sql
Original file line number Diff line number Diff line change
@@ -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");
149 changes: 149 additions & 0 deletions apps/api/migrations/meta/0001_snapshot.json
Original file line number Diff line number Diff line change
@@ -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": {}
}
}
7 changes: 7 additions & 0 deletions apps/api/migrations/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
]
}
3 changes: 2 additions & 1 deletion apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
12 changes: 11 additions & 1 deletion apps/api/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
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({
typeDefs: readFileSync(
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',
});
30 changes: 29 additions & 1 deletion apps/api/src/db/schema.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,36 @@
import { pgSchema, text, uuid } from 'drizzle-orm/pg-core';
import {
pgSchema,
text,
timestamp,
uniqueIndex,
uuid,
} from 'drizzle-orm/pg-core';

const project2 = pgSchema('project2');

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(),
});
74 changes: 74 additions & 0 deletions apps/api/src/features/auth/authRepository.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
Loading
Loading