feat: creates backend for the project

This commit is contained in:
vakabunga
2026-03-02 00:32:37 +03:00
parent 9d12702688
commit 4d67636633
24 changed files with 1735 additions and 0 deletions

View File

@@ -0,0 +1,50 @@
import { Request, Response, NextFunction } from 'express';
import { pool } from '../db/pool';
import { config } from '../config';
declare global {
namespace Express {
interface Request {
sessionId?: string;
}
}
}
export async function requireAuth(
req: Request,
res: Response,
next: NextFunction,
): Promise<void> {
const sid = req.cookies?.sid;
if (!sid) {
res.status(401).json({ error: 'UNAUTHORIZED', message: 'No session' });
return;
}
const { rows } = await pool.query(
'SELECT id, last_activity_at, is_active FROM sessions WHERE id = $1',
[sid],
);
if (rows.length === 0 || !rows[0].is_active) {
res.clearCookie('sid');
res.status(401).json({ error: 'UNAUTHORIZED', message: 'Invalid session' });
return;
}
const lastActivity = new Date(rows[0].last_activity_at).getTime();
if (Date.now() - lastActivity > config.sessionTimeoutMs) {
await pool.query('UPDATE sessions SET is_active = FALSE WHERE id = $1', [sid]);
res.clearCookie('sid');
res.status(401).json({ error: 'UNAUTHORIZED', message: 'Session expired' });
return;
}
await pool.query(
'UPDATE sessions SET last_activity_at = NOW() WHERE id = $1',
[sid],
);
req.sessionId = sid;
next();
}