diff --git a/docs/roomie.postman_collection.json b/docs/roomie.postman_collection.json index 9abab61..74857b9 100644 --- a/docs/roomie.postman_collection.json +++ b/docs/roomie.postman_collection.json @@ -2,12 +2,42 @@ "info": { "name": "Roomie API (local)", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", - "description": "Roomie API. Start the server (`npm run dev`) and send Health check. More endpoints come with the features on the mvp-features branch." + "description": "Roomie API so far: health, login and profile. Start the server (`npm run dev`, with AUTH_DEV_BYPASS=true) and click **Run collection**, or send the requests top to bottom.\n\nAuth uses the dev login: `Bearer dev:{{netid}}`. Requests marked as the roommate use `dev:{{roommateNetid}}`. Each full run picks new NetIDs." + }, + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "dev:{{netid}}", + "type": "string" + } + ] }, "variable": [ { "key": "baseUrl", "value": "http://localhost:8000" + }, + { + "key": "netid", + "value": "lk452" + }, + { + "key": "roommateNetid", + "value": "sc2291" + }, + { + "key": "keepNetids", + "value": "" + }, + { + "key": "myId", + "value": "" + }, + { + "key": "roommateId", + "value": "" } ], "item": [ @@ -26,6 +56,21 @@ "pm.test(\"database connected\", () => pm.expect(pm.response.json().database).to.eql('connected'));" ] } + }, + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "// New NetIDs every run so the collection can be re-run against the same DB.", + "// To explore the seeded demo house instead, set netid to lk452 and skip this folder.", + "if (pm.info.iteration === 0 && !pm.collectionVariables.get('keepNetids')) {", + " const n = Math.floor(100000 + Math.random() * 899999);", + " pm.collectionVariables.set('netid', 'pm' + n);", + " pm.collectionVariables.set('roommateNetid', 'pr' + n);", + "}" + ] + } } ], "request": { @@ -43,6 +88,154 @@ } } ] + }, + { + "name": "1 \u00b7 Auth & me", + "item": [ + { + "name": "Login (creates account first time)", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 201\", () => pm.response.to.have.status(201));", + "", + "const body = pm.response.json();", + "pm.collectionVariables.set('myId', body.user.id);", + "pm.test(\"is a new user with no house\", () => { pm.expect(body.isNewUser).to.be.true; pm.expect(body.house).to.be.null; });" + ] + } + } + ], + "request": { + "method": "POST", + "header": [], + "url": { + "raw": "{{baseUrl}}/auth/login", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "auth", + "login" + ] + }, + "description": "Real apps send the Firebase ID token from Google sign-in. Locally, `Bearer dev:` works when AUTH_DEV_BYPASS=true. Returns 201 the first time, 200 after." + } + }, + { + "name": "Get me", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/me", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + "me" + ] + } + } + }, + { + "name": "Update me (name, presence)", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));", + "pm.test(\"name updated\", () => pm.expect(pm.response.json().user.name).to.eql('Postman Tester'));" + ] + } + } + ], + "request": { + "method": "PATCH", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/users/me", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + "me" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"Postman Tester\",\n \"major\": \"Computer Science\",\n \"presence\": \"HOME\"\n}", + "options": { + "raw": { + "language": "json" + } + } + } + } + }, + { + "name": "Roommate logs in", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 201\", () => pm.response.to.have.status(201));", + "pm.collectionVariables.set('roommateId', pm.response.json().user.id);" + ] + } + } + ], + "request": { + "method": "POST", + "header": [], + "url": { + "raw": "{{baseUrl}}/auth/login", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "auth", + "login" + ] + }, + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "dev:{{roommateNetid}}", + "type": "string" + } + ] + } + } + } + ] } ] } diff --git a/src/app.ts b/src/app.ts index 729274c..7507cd0 100644 --- a/src/app.ts +++ b/src/app.ts @@ -3,10 +3,13 @@ import helmet from 'helmet'; import express from 'express'; import type { Request, Response } from 'express'; +import authRouter from './auth/authRouter.js'; +import { requireAuth } from './middleware/authentication.js'; import { globalErrorHandler } from './middleware/errorHandler.js'; import { requestLogger } from './middleware/logger.js'; import { ipRateLimiter } from './middleware/rateLimit.js'; import { prisma } from './prisma.js'; +import userRouter from './users/userRouter.js'; import { NotFoundError } from './utils/AppError.js'; export const createApp = () => { @@ -35,8 +38,13 @@ export const createApp = () => { } }); - // Feature routers (auth, users, houses, chores, shopping) get mounted here. - // They live on the mvp-features branch. + // Public + router.use('/auth', authRouter); + + // Signed in + router.use(requireAuth); + router.use('/users', userRouter); + // Feature routers (houses, chores, shopping) get mounted here. app.use(router); diff --git a/src/auth/authRouter.ts b/src/auth/authRouter.ts new file mode 100644 index 0000000..933402c --- /dev/null +++ b/src/auth/authRouter.ts @@ -0,0 +1,46 @@ +import { Router } from 'express'; +import type { Request, Response } from 'express'; + +import { prisma } from '../prisma.js'; +import { getSession } from '../users/userService.js'; +import { meSelect } from '../utils/selects.js'; +import { bearerToken, verifyIdToken } from './tokens.js'; + +const router = Router(); + +/** + * POST /auth/login + * Header: Authorization: Bearer + * + * Creates the Roomie account on first sign-in and returns the session the app + * needs to decide where to go next: + * - no house + pendingInvites → show "join ?" + * - no house → onboarding (create a house or enter an invite code) + * - house → Home + */ +router.post('/login', async (req: Request, res: Response) => { + const identity = await verifyIdToken(bearerToken(req.headers.authorization)); + + const existing = await prisma.user.findUnique({ + where: { firebaseUid: identity.firebaseUid }, + select: { id: true }, + }); + + const user = existing + ? existing + : await prisma.user.create({ + data: { + firebaseUid: identity.firebaseUid, + email: identity.email, + netid: identity.netid, + name: identity.name, + avatarUrl: identity.avatarUrl, + }, + select: meSelect, + }); + + const session = await getSession(user.id); + res.status(existing ? 200 : 201).json({ isNewUser: !existing, ...session }); +}); + +export default router; diff --git a/src/auth/tokens.ts b/src/auth/tokens.ts new file mode 100644 index 0000000..646698a --- /dev/null +++ b/src/auth/tokens.ts @@ -0,0 +1,88 @@ +import { getFirebaseAuth } from '../firebase.js'; +import { ForbiddenError, UnauthorizedError } from '../utils/AppError.js'; + +export interface VerifiedIdentity { + firebaseUid: string; + email: string; + netid: string; + name: string; + avatarUrl?: string; +} + +const CORNELL_SUFFIX = '@cornell.edu'; + +/** Comma-separated full emails allowed besides @cornell.edu (e.g. a reviewer account). */ +const emailAllowlist = () => + new Set( + (process.env.EMAIL_ALLOWLIST ?? '') + .split(',') + .map((e) => e.trim().toLowerCase()) + .filter(Boolean), + ); + +export const isDevBypassEnabled = () => + process.env.AUTH_DEV_BYPASS === 'true' && + process.env.NODE_ENV !== 'production'; + +const netidFromEmail = (email: string) => email.split('@')[0]!.toLowerCase(); + +/** + * Verifies a Firebase ID token (from Google sign-in on iOS/Android) and returns + * who it belongs to. Only Cornell accounts get through. + * + * Local development: with AUTH_DEV_BYPASS=true (never in production) you can send + * `Bearer dev:` instead of a real token. + */ +export const verifyIdToken = async ( + token: string, +): Promise => { + if (token.startsWith('dev:')) { + if (!isDevBypassEnabled()) { + throw new UnauthorizedError('Invalid token.'); + } + const netid = token.slice(4).toLowerCase(); + if (!/^[a-z]{1,4}\d{1,6}$/.test(netid)) { + throw new UnauthorizedError('Dev tokens look like dev:.'); + } + return { + firebaseUid: `dev-${netid}`, + email: `${netid}${CORNELL_SUFFIX}`, + netid, + name: netid, + }; + } + + let decoded; + try { + decoded = await getFirebaseAuth().verifyIdToken(token); + } catch { + throw new UnauthorizedError('Invalid or expired token.'); + } + + const email = decoded.email?.trim().toLowerCase(); + if (!email || !decoded.email_verified) { + throw new ForbiddenError('A verified email is required.'); + } + if (!email.endsWith(CORNELL_SUFFIX) && !emailAllowlist().has(email)) { + throw new ForbiddenError('Only Cornell accounts can use Roomie.'); + } + + return { + firebaseUid: decoded.uid, + email, + netid: netidFromEmail(email), + name: (decoded.name as string | undefined) ?? netidFromEmail(email), + avatarUrl: decoded.picture, + }; +}; + +export const bearerToken = (header: string | undefined) => { + if (!header?.startsWith('Bearer ')) { + throw new UnauthorizedError('No token provided or wrong format.'); + } + const token = header.slice(7).trim(); + if (!token) { + throw new UnauthorizedError('No token provided.'); + } + return token; +}; diff --git a/src/firebase.ts b/src/firebase.ts new file mode 100644 index 0000000..9eb6ce2 --- /dev/null +++ b/src/firebase.ts @@ -0,0 +1,32 @@ +import { readFileSync } from 'fs'; +import { resolve } from 'path'; + +import { cert, getApps, initializeApp } from 'firebase-admin/app'; +import type { ServiceAccount } from 'firebase-admin/app'; +import { getAuth } from 'firebase-admin/auth'; + +/** + * Firebase Admin is initialized lazily so the server (and tests) can run with + * the dev auth bypass before anyone has set up a Firebase project. + * + * Credentials, in order of preference (same as Resell): + * FIREBASE_SERVICE_ACCOUNT_JSON stringified service-account JSON (good for hosted envs) + * FIREBASE_SERVICE_ACCOUNT_PATH path to the JSON file (good for local dev / Docker volume) + */ +const loadServiceAccount = (): ServiceAccount => { + if (process.env.FIREBASE_SERVICE_ACCOUNT_JSON) { + return JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT_JSON); + } + const path = resolve( + process.env.FIREBASE_SERVICE_ACCOUNT_PATH || + './firebase-service-account.json', + ); + return JSON.parse(readFileSync(path, 'utf8')); +}; + +export const getFirebaseAuth = () => { + if (getApps().length === 0) { + initializeApp({ credential: cert(loadServiceAccount()) }); + } + return getAuth(); +}; diff --git a/src/middleware/authentication.ts b/src/middleware/authentication.ts new file mode 100644 index 0000000..a23b2eb --- /dev/null +++ b/src/middleware/authentication.ts @@ -0,0 +1,28 @@ +import type { NextFunction, Request, Response } from 'express'; + +import { bearerToken, verifyIdToken } from '../auth/tokens.js'; +import { prisma } from '../prisma.js'; +import { ForbiddenError } from '../utils/AppError.js'; + +/** + * Verifies the Firebase ID token on every request and loads the Roomie user. + * The user must have called POST /auth/login once to create their account. + */ +export const requireAuth = async ( + req: Request, + _res: Response, + next: NextFunction, +) => { + const identity = await verifyIdToken(bearerToken(req.headers.authorization)); + const user = await prisma.user.findUnique({ + where: { firebaseUid: identity.firebaseUid }, + include: { membership: true }, + }); + if (!user) { + throw new ForbiddenError( + 'No Roomie account yet. Call POST /auth/login first.', + ); + } + req.user = user; + next(); +}; diff --git a/src/server.ts b/src/server.ts index 5d70e14..1aa7db4 100644 --- a/src/server.ts +++ b/src/server.ts @@ -9,6 +9,14 @@ const app = createApp(); const server = app.listen(port, async () => { console.log(`Roomie API listening at http://localhost:${port}`); console.log(`Environment: ${process.env.NODE_ENV || 'development'}`); + if ( + process.env.AUTH_DEV_BYPASS === 'true' && + process.env.NODE_ENV !== 'production' + ) { + console.warn( + 'AUTH_DEV_BYPASS is on: "Bearer dev:" tokens are accepted.', + ); + } try { await prisma.$connect(); console.log('Database connected'); diff --git a/src/types/express/index.d.ts b/src/types/express/index.d.ts index 09ce91c..ebfcb57 100644 --- a/src/types/express/index.d.ts +++ b/src/types/express/index.d.ts @@ -1,10 +1,14 @@ +import type { HouseMember, User } from '../../generated/prisma/client.js'; + +export type AuthedUser = User & { membership: HouseMember | null }; + declare global { namespace Express { export interface Request { + /** Set by requireAuth. */ + user?: AuthedUser; /** Set by validateRequest: the parsed (coerced, defaulted) request data. */ validated?: { body: unknown; query: unknown; params: unknown }; } } } - -export {}; diff --git a/src/users/userRouter.ts b/src/users/userRouter.ts new file mode 100644 index 0000000..7f6753e --- /dev/null +++ b/src/users/userRouter.ts @@ -0,0 +1,38 @@ +import { z } from 'zod'; + +import { Router } from 'express'; +import type { Request, Response } from 'express'; + +import { valid, validateRequest } from '../middleware/validateRequest.js'; +import { prisma } from '../prisma.js'; +import { getSession } from './userService.js'; + +const router = Router(); + +/** GET /users/me: same payload as login, for app launch. */ +router.get('/me', async (req: Request, res: Response) => { + res.json(await getSession(req.user!.id)); +}); + +const updateMeSchema = z.object({ + body: z + .object({ + name: z.string().trim().min(1).max(80), + major: z.string().trim().max(80).nullable(), + presence: z.enum(['HOME', 'AWAY']), + }) + .partial(), +}); + +/** PATCH /users/me: profile edits and the "I'm home / away" toggle. */ +router.patch( + '/me', + validateRequest(updateMeSchema), + async (req: Request, res: Response) => { + const { body } = valid(req, updateMeSchema); + await prisma.user.update({ where: { id: req.user!.id }, data: body }); + res.json(await getSession(req.user!.id)); + }, +); + +export default router; diff --git a/src/users/userService.ts b/src/users/userService.ts new file mode 100644 index 0000000..dd99835 --- /dev/null +++ b/src/users/userService.ts @@ -0,0 +1,56 @@ +import { prisma } from '../prisma.js'; +import { NotFoundError } from '../utils/AppError.js'; +import { meSelect, publicUserSelect } from '../utils/selects.js'; + +/** The signed-in user, their house (if any), and invites waiting for them. */ +export const getSession = async (userId: number) => { + const user = await prisma.user.findUnique({ + where: { id: userId }, + select: { + ...meSelect, + membership: { + select: { + role: true, + house: { select: { id: true, name: true, color: true } }, + }, + }, + }, + }); + if (!user) throw new NotFoundError('User not found.'); + + const { membership, ...me } = user; + + const pendingInvites = membership + ? [] + : await prisma.houseInvite.findMany({ + where: { netid: me.netid, status: 'PENDING' }, + orderBy: { createdAt: 'desc' }, + select: { + id: true, + createdAt: true, + house: { + select: { + id: true, + name: true, + color: true, + members: { select: { user: { select: publicUserSelect } } }, + }, + }, + invitedBy: { select: publicUserSelect }, + }, + }); + + return { + user: me, + house: membership ? { ...membership.house, role: membership.role } : null, + pendingInvites: pendingInvites.map(({ house, ...invite }) => ({ + ...invite, + house: { + id: house.id, + name: house.name, + color: house.color, + members: house.members.map((m) => m.user), + }, + })), + }; +}; diff --git a/src/utils/selects.ts b/src/utils/selects.ts new file mode 100644 index 0000000..646ccd8 --- /dev/null +++ b/src/utils/selects.ts @@ -0,0 +1,15 @@ +/** What other roommates can see about a user. */ +export const publicUserSelect = { + id: true, + netid: true, + name: true, + avatarUrl: true, + presence: true, +} as const; + +export const meSelect = { + ...publicUserSelect, + email: true, + major: true, + createdAt: true, +} as const; diff --git a/test/auth.test.ts b/test/auth.test.ts new file mode 100644 index 0000000..10785e0 --- /dev/null +++ b/test/auth.test.ts @@ -0,0 +1,85 @@ +import request from 'supertest'; +import { describe, expect, it } from 'vitest'; + +import { app, as, signUp } from './helpers.js'; + +describe('auth', () => { + it('rejects requests without a token', async () => { + const res = await request(app).get('/users/me'); + expect(res.status).toBe(401); + expect(res.body.errorCode).toBe('UNAUTHORIZED'); + }); + + it('rejects garbage tokens', async () => { + const res = await request(app) + .get('/users/me') + .set('Authorization', 'Bearer nope'); + expect(res.status).toBe(401); + }); + + it('creates the account on first login, then logs in', async () => { + const first = await as('lk452').post('/auth/login'); + expect(first.status).toBe(201); + expect(first.body).toMatchObject({ + isNewUser: true, + user: { netid: 'lk452', email: 'lk452@cornell.edu', presence: 'HOME' }, + house: null, + pendingInvites: [], + }); + + const again = await as('lk452').post('/auth/login'); + expect(again.status).toBe(200); + expect(again.body.isNewUser).toBe(false); + expect(again.body.user.id).toBe(first.body.user.id); + }); + + it('requires login before other routes', async () => { + const res = await as('zz999').get('/users/me'); + expect(res.status).toBe(403); + }); + + it('never accepts dev tokens in production', async () => { + const prev = process.env.NODE_ENV; + process.env.NODE_ENV = 'production'; + try { + const res = await as('lk452').post('/auth/login'); + expect(res.status).toBe(401); + } finally { + process.env.NODE_ENV = prev; + } + }); +}); + +describe('users', () => { + it('updates profile and presence', async () => { + const leah = await signUp('lk452'); + const res = await leah.patch('/users/me', { + name: 'Leah Kim', + presence: 'AWAY', + }); + expect(res.status).toBe(200); + expect(res.body.user).toMatchObject({ name: 'Leah Kim', presence: 'AWAY' }); + }); + + it('validates input', async () => { + const leah = await signUp('lk452'); + const res = await leah.patch('/users/me', { presence: 'ASLEEP' }); + expect(res.status).toBe(400); + expect(res.body.data).toHaveProperty('body.presence'); + }); +}); + +describe('server', () => { + it('reports health', async () => { + const res = await request(app).get('/health'); + expect(res.body).toMatchObject({ + status: 'healthy', + database: 'connected', + }); + }); + + it('404s unknown routes', async () => { + const leah = await signUp('lk452'); + expect((await leah.get('/nope')).status).toBe(404); + }); +}); diff --git a/test/health.test.ts b/test/health.test.ts index eb172d1..275fdda 100644 --- a/test/health.test.ts +++ b/test/health.test.ts @@ -15,10 +15,10 @@ describe('server', () => { }); }); - it('404s unknown routes', async () => { + it('asks for a token on every other route', async () => { const res = await request(app).get('/nope'); - expect(res.status).toBe(404); - expect(res.body.errorCode).toBe('NOT_FOUND'); + expect(res.status).toBe(401); + expect(res.body.errorCode).toBe('UNAUTHORIZED'); }); it('rejects malformed JSON', async () => { diff --git a/test/helpers.ts b/test/helpers.ts new file mode 100644 index 0000000..46044b4 --- /dev/null +++ b/test/helpers.ts @@ -0,0 +1,33 @@ +import request from 'supertest'; + +import { createApp } from '../src/app.js'; + +export const app = createApp(); + +/** A signed-in client for a NetID, using the dev auth bypass. */ +export const as = (netid: string) => { + const auth = { Authorization: `Bearer dev:${netid}` }; + return { + get: (url: string) => request(app).get(url).set(auth), + post: (url: string, body?: object) => + request(app) + .post(url) + .set(auth) + .send(body ?? {}), + patch: (url: string, body?: object) => + request(app) + .patch(url) + .set(auth) + .send(body ?? {}), + delete: (url: string) => request(app).delete(url).set(auth), + }; +}; + +/** Signs a user up (POST /auth/login) and returns their client + user id. */ +export const signUp = async (netid: string) => { + const client = as(netid); + const res = await client.post('/auth/login'); + if (res.status >= 300) + throw new Error(`login failed: ${JSON.stringify(res.body)}`); + return { ...client, id: res.body.user.id as number, netid }; +};