BBS/src/users/userRepo.ts

120 lines
3.7 KiB
TypeScript

import bcrypt from 'bcryptjs';
import { pool } from '../db';
export interface User {
id: number;
handle: string;
password_hash: string;
real_name: string;
location: string;
email: string | null;
security_level: number;
times_called: number;
created_at: Date;
last_login_at: Date | null;
}
export interface NewUser {
handle: string;
password: string;
realName: string;
location: string;
email: string | null;
}
export class HandleTakenError extends Error {}
/** Security levels. Sysop-only features should check isSysop(). */
export const NEW_USER_LEVEL = 10;
export const SYSOP_LEVEL = 255;
// Used so a login attempt for an unknown handle costs the same as a real one.
const DUMMY_HASH = bcrypt.hashSync('not-a-real-password', 10);
export async function findByHandle(handle: string): Promise<User | null> {
const { rows } = await pool.query<User>('SELECT * FROM users WHERE lower(handle) = lower($1)', [handle]);
return rows[0] ?? null;
}
export async function handleExists(handle: string): Promise<boolean> {
return (await findByHandle(handle)) !== null;
}
export async function verifyLogin(handle: string, password: string): Promise<User | null> {
const user = await findByHandle(handle);
const ok = await bcrypt.compare(password, user?.password_hash ?? DUMMY_HASH);
return user && ok ? user : null;
}
/** The very first account created on the system becomes the Sysop. */
export async function createUser(u: NewUser): Promise<User> {
const hash = await bcrypt.hash(u.password, 10);
const client = await pool.connect();
try {
await client.query('BEGIN');
// Serialise signups so two simultaneous "first" users can't both become Sysop.
await client.query('SELECT pg_advisory_xact_lock(727275)');
const { rows } = await client.query<User>(
`INSERT INTO users (handle, password_hash, real_name, location, email, security_level)
VALUES ($1, $2, $3, $4, $5,
CASE WHEN EXISTS (SELECT 1 FROM users) THEN $6::int ELSE $7::int END)
RETURNING *`,
[u.handle, hash, u.realName, u.location, u.email, NEW_USER_LEVEL, SYSOP_LEVEL],
);
await client.query('COMMIT');
return rows[0];
} catch (err: unknown) {
await client.query('ROLLBACK');
if ((err as { code?: string }).code === '23505') throw new HandleTakenError();
throw err;
} finally {
client.release();
}
}
export function isSysop(user: User): boolean {
return user.security_level >= SYSOP_LEVEL;
}
/** Records a successful logon. Returns the system caller number and the refreshed user row. */
export async function recordCall(userId: number, node: number): Promise<{ callerNo: number; user: User }> {
const client = await pool.connect();
try {
await client.query('BEGIN');
const call = await client.query<{ id: number }>(
'INSERT INTO calls (user_id, node) VALUES ($1, $2) RETURNING id',
[userId, node],
);
const upd = await client.query<User>(
`UPDATE users SET times_called = times_called + 1, last_login_at = now()
WHERE id = $1 RETURNING *`,
[userId],
);
await client.query('COMMIT');
return { callerNo: call.rows[0].id, user: upd.rows[0] };
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
export interface LastCaller {
id: number;
handle: string;
location: string;
node: number;
connected_at: Date;
}
export async function lastCallers(limit = 10): Promise<LastCaller[]> {
const { rows } = await pool.query<LastCaller>(
`SELECT c.id, u.handle, u.location, c.node, c.connected_at
FROM calls c JOIN users u ON u.id = c.user_id
ORDER BY c.id DESC LIMIT $1`,
[limit],
);
return rows;
}