feat: creates backend for the project
This commit is contained in:
50
backend/src/middleware/auth.ts
Normal file
50
backend/src/middleware/auth.ts
Normal 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();
|
||||
}
|
||||
Reference in New Issue
Block a user