@davoodmehraban89 / LifeMate / commits / 2418d35
Fork 0

LifeMate — Personal, Family & Learning Companion

feat: implement identity API foundation

davoodmehraban89 committed Oct 5, 2026 at 07:32 UTC 2418d350c5589c628c28de512ccdf265fa27d911
1 file changed +126
backend/src/server.js new
+126
@@ -0,0 +1,126 @@
1 +import crypto from 'node:crypto';
2 +import express from 'express';
3 +import argon2 from 'argon2';
4 +import jwt from 'jsonwebtoken';
5 +import pg from 'pg';
6 +
7 +const { Pool } = pg;
8 +const app = express();
9 +app.use(express.json({ limit: '64kb' }));
10 +const pool = new Pool({ connectionString: process.env.DATABASE_URL });
11 +const jwtSecret = process.env.JWT_SECRET;
12 +if (!jwtSecret || jwtSecret.length < 32) throw new Error('JWT_SECRET must be at least 32 characters');
13 +
14 +const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
15 +const randomToken = () => crypto.randomBytes(32).toString('base64url');
16 +const normalizeEmail = (email) => String(email ?? '').trim().toLowerCase();
17 +const validPassword = (p) => typeof p === 'string' && p.length >= 10 && p.length <= 200;
18 +const issueAccess = (userId) => jwt.sign({ sub: userId, aud: 'lifemate-api' }, jwtSecret, { expiresIn: '15m', issuer: 'lifemate' });
19 +
20 +async function auth(req, res, next) {
21 + const raw = req.headers.authorization?.replace(/^Bearer\s+/i, '');
22 + try { req.identity = jwt.verify(raw, jwtSecret, { audience: 'lifemate-api', issuer: 'lifemate' }); next(); }
23 + catch { res.status(401).json({ error: 'unauthorized' }); }
24 +}
25 +
26 +async function createOneTimeToken(client, userId, kind, minutes) {
27 + const raw = randomToken();
28 + await client.query('insert into auth_token(user_id,kind,token_digest,expires_at) values($1,$2,$3,now()+($4 || \' minutes\')::interval)', [userId, kind, sha256(raw), String(minutes)]);
29 + return raw;
30 +}
31 +
32 +app.get('/health', async (_req, res) => {
33 + const r = await pool.query('select 1 as ok');
34 + res.json({ status: r.rows[0].ok === 1 ? 'ok' : 'degraded' });
35 +});
36 +
37 +app.post('/v1/auth/register', async (req, res) => {
38 + const email = normalizeEmail(req.body.email); const password = req.body.password; const name = String(req.body.displayName ?? '').trim();
39 + if (!email.includes('@') || !validPassword(password) || !name) return res.status(400).json({ error: 'invalid_input' });
40 + const client = await pool.connect();
41 + try {
42 + await client.query('begin');
43 + const hash = await argon2.hash(password, { type: argon2.argon2id });
44 + const u = await client.query('insert into app_user(identity_subject,email_normalized) values($1,$2) returning id', [`local:${crypto.randomUUID()}`, email]);
45 + await client.query('insert into profile(user_id,display_name) values($1,$2)', [u.rows[0].id, name]);
46 + await client.query('insert into auth_credential(user_id,password_hash) values($1,$2)', [u.rows[0].id, hash]);
47 + const verificationToken = await createOneTimeToken(client, u.rows[0].id, 'email_verification', 60 * 24);
48 + await client.query('commit');
49 + res.status(201).json({ userId: u.rows[0].id, verificationToken: process.env.NODE_ENV === 'test' ? verificationToken : undefined });
50 + } catch (e) {
51 + await client.query('rollback');
52 + if (e.code === '23505') return res.status(409).json({ error: 'account_exists' });
53 + throw e;
54 + } finally { client.release(); }
55 +});
56 +
57 +app.post('/v1/auth/verify-email', async (req, res) => {
58 + const digest = sha256(String(req.body.token ?? ''));
59 + const r = await pool.query("update auth_token t set used_at=now() from app_user u where t.user_id=u.id and t.kind='email_verification' and t.token_digest=$1 and t.used_at is null and t.expires_at>now() returning u.id", [digest]);
60 + if (!r.rowCount) return res.status(400).json({ error: 'invalid_or_expired_token' });
61 + await pool.query('update app_user set email_verified_at=coalesce(email_verified_at,now()) where id=$1', [r.rows[0].id]);
62 + res.status(204).end();
63 +});
64 +
65 +app.post('/v1/auth/login', async (req, res) => {
66 + const email = normalizeEmail(req.body.email); const password = String(req.body.password ?? '');
67 + const r = await pool.query('select u.id,u.email_verified_at,c.password_hash from app_user u join auth_credential c on c.user_id=u.id where u.email_normalized=$1 and u.disabled_at is null', [email]);
68 + if (!r.rowCount || !(await argon2.verify(r.rows[0].password_hash, password))) return res.status(401).json({ error: 'invalid_credentials' });
69 + if (!r.rows[0].email_verified_at) return res.status(403).json({ error: 'email_not_verified' });
70 + res.json({ accessToken: issueAccess(r.rows[0].id) });
71 +});
72 +
73 +app.post('/v1/auth/forgot-password', async (req, res) => {
74 + const email = normalizeEmail(req.body.email);
75 + const r = await pool.query('select id from app_user where email_normalized=$1 and disabled_at is null', [email]);
76 + let resetToken;
77 + if (r.rowCount) { const c = await pool.connect(); try { resetToken = await createOneTimeToken(c, r.rows[0].id, 'password_reset', 30); } finally { c.release(); } }
78 + res.json({ accepted: true, resetToken: process.env.NODE_ENV === 'test' ? resetToken : undefined });
79 +});
80 +
81 +app.post('/v1/auth/reset-password', async (req, res) => {
82 + if (!validPassword(req.body.newPassword)) return res.status(400).json({ error: 'invalid_password' });
83 + const digest = sha256(String(req.body.token ?? '')); const client = await pool.connect();
84 + try {
85 + await client.query('begin');
86 + const r = await client.query("update auth_token set used_at=now() where kind='password_reset' and token_digest=$1 and used_at is null and expires_at>now() returning user_id", [digest]);
87 + if (!r.rowCount) { await client.query('rollback'); return res.status(400).json({ error: 'invalid_or_expired_token' }); }
88 + const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
89 + await client.query('update auth_credential set password_hash=$1,password_changed_at=now() where user_id=$2', [hash, r.rows[0].user_id]);
90 + await client.query('update auth_session set revoked_at=now() where user_id=$1 and revoked_at is null', [r.rows[0].user_id]);
91 + await client.query('commit'); res.status(204).end();
92 + } finally { client.release(); }
93 +});
94 +
95 +app.post('/v1/auth/change-password', auth, async (req, res) => {
96 + if (!validPassword(req.body.newPassword)) return res.status(400).json({ error: 'invalid_password' });
97 + const r = await pool.query('select password_hash from auth_credential where user_id=$1', [req.identity.sub]);
98 + if (!r.rowCount || !(await argon2.verify(r.rows[0].password_hash, String(req.body.currentPassword ?? '')))) return res.status(403).json({ error: 'invalid_current_password' });
99 + const hash = await argon2.hash(req.body.newPassword, { type: argon2.argon2id });
100 + await pool.query('update auth_credential set password_hash=$1,password_changed_at=now() where user_id=$2', [hash, req.identity.sub]);
101 + res.status(204).end();
102 +});
103 +
104 +app.get('/v1/profile', auth, async (req, res) => {
105 + const r = await pool.query('select p.display_name,p.birth_date,p.theme_preference,u.email_normalized,u.email_verified_at from profile p join app_user u on u.id=p.user_id where p.user_id=$1', [req.identity.sub]);
106 + res.json(r.rows[0]);
107 +});
108 +
109 +app.post('/v1/families', auth, async (req, res) => {
110 + const name = String(req.body.name ?? '').trim(); if (!name) return res.status(400).json({ error: 'invalid_name' });
111 + const c = await pool.connect(); try { await c.query('begin'); const f = await c.query('insert into family_workspace(name,created_by) values($1,$2) returning id,name', [name, req.identity.sub]); await c.query("insert into family_membership(family_id,user_id,role) values($1,$2,'owner_admin')", [f.rows[0].id, req.identity.sub]); await c.query('commit'); res.status(201).json(f.rows[0]); } catch(e) { await c.query('rollback'); throw e; } finally { c.release(); }
112 +});
113 +
114 +app.post('/v1/families/:familyId/invitations', auth, async (req, res) => {
115 + const allowed = await pool.query("select 1 from family_membership where family_id=$1 and user_id=$2 and ended_at is null and role in ('owner_admin','parent_guardian')", [req.params.familyId, req.identity.sub]);
116 + if (!allowed.rowCount) return res.status(403).json({ error: 'forbidden' });
117 + const email = normalizeEmail(req.body.email); const role = req.body.role; const token = randomToken();
118 + const r = await pool.query("insert into family_invitation(family_id,invited_email_normalized,intended_role,token_digest,invited_by,expires_at) values($1,$2,$3,$4,$5,now()+interval '7 days') returning id,expires_at", [req.params.familyId,email,role,sha256(token),req.identity.sub]);
119 + res.status(201).json({ ...r.rows[0], invitationToken: process.env.NODE_ENV === 'test' ? token : undefined });
120 +});
121 +
122 +app.use((err, _req, res, _next) => { console.error(err); res.status(500).json({ error: 'internal_error' }); });
123 +
124 +const port = Number(process.env.PORT ?? 8080);
125 +if (process.env.NODE_ENV !== 'test') app.listen(port, () => console.log(`LifeMate API listening on ${port}`));
126 +export default app;