feature : Connect front to backend #1
@@ -1,5 +1,6 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import prisma from '../lib/prisma.js';
|
||||
|
||||
export interface JwtPayload {
|
||||
userId: string;
|
||||
@@ -15,7 +16,7 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
export function authenticate(req: Request, res: Response, next: NextFunction): void {
|
||||
export async function authenticate(req: Request, res: Response, next: NextFunction): Promise<void> {
|
||||
const header = req.headers.authorization;
|
||||
if (!header?.startsWith('Bearer ')) {
|
||||
res.status(401).json({ error: 'Missing or invalid Authorization header' });
|
||||
@@ -25,7 +26,21 @@ export function authenticate(req: Request, res: Response, next: NextFunction): v
|
||||
const token = header.slice(7);
|
||||
try {
|
||||
const payload = jwt.verify(token, process.env.JWT_SECRET!) as JwtPayload;
|
||||
req.user = payload;
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: payload.userId },
|
||||
select: { id: true, role: true, isAdmin: true, isBanned: true },
|
||||
});
|
||||
|
||||
if (!user || user.isBanned) {
|
||||
res.status(401).json({ error: 'Token user no longer exists or is banned. Please login again.' });
|
||||
return;
|
||||
}
|
||||
|
||||
req.user = {
|
||||
userId: user.id,
|
||||
role: user.role,
|
||||
isAdmin: user.isAdmin,
|
||||
};
|
||||
next();
|
||||
} catch {
|
||||
res.status(401).json({ error: 'Token expired or invalid' });
|
||||
|
||||
Reference in New Issue
Block a user