Spaces:
Running
Running
| import { Request, Response, NextFunction } from 'express'; | |
| import jwt from 'jsonwebtoken'; | |
| import { config } from '../config'; | |
| import { getDatabase } from '../database'; | |
| export interface AuthRequest extends Request { | |
| userId?: string; | |
| userEmail?: string; | |
| } | |
| export function authenticate(req: AuthRequest, res: Response, next: NextFunction): void { | |
| const authHeader = req.headers.authorization; | |
| if (!authHeader || !authHeader.startsWith('Bearer ')) { | |
| res.status(401).json({ error: 'Authentication required' }); | |
| return; | |
| } | |
| const token = authHeader.substring(7); | |
| try { | |
| const decoded = jwt.verify(token, config.jwtSecret) as { userId: string; email: string }; | |
| const db = getDatabase(); | |
| const session = db.prepare('SELECT id FROM sessions WHERE token = ? AND expires_at > ?').get( | |
| token, | |
| Date.now() | |
| ); | |
| if (!session) { | |
| res.status(401).json({ error: 'Session expired or invalid' }); | |
| return; | |
| } | |
| req.userId = decoded.userId; | |
| req.userEmail = decoded.email; | |
| next(); | |
| } catch { | |
| res.status(401).json({ error: 'Invalid token' }); | |
| } | |
| } | |