29 lines
831 B
TypeScript
29 lines
831 B
TypeScript
import { Response, NextFunction } from 'express';
|
|
import { AuthRequest } from './types.js';
|
|
import { extractToken } from './extractToken.js';
|
|
import { validateToken } from './validateToken.js';
|
|
import { getUser } from './getUser.js';
|
|
|
|
export async function auth(req: AuthRequest, res: Response, next: NextFunction) {
|
|
try {
|
|
const token = extractToken(req);
|
|
if (!token) {
|
|
return res.status(401).json({ error: 'No token provided' });
|
|
}
|
|
|
|
const payload = validateToken(token);
|
|
if (!payload) {
|
|
return res.status(401).json({ error: 'Invalid token' });
|
|
}
|
|
|
|
const user = await getUser(payload.id);
|
|
if (!user) {
|
|
return res.status(401).json({ error: 'User not found' });
|
|
}
|
|
|
|
req.user = user;
|
|
next();
|
|
} catch {
|
|
res.status(401).json({ error: 'Authentication failed' });
|
|
}
|
|
} |