40 lines
981 B
TypeScript
40 lines
981 B
TypeScript
import { Request, Response, NextFunction } from 'express';
|
|
import jwt from 'jsonwebtoken';
|
|
import { PrismaClient } from '@prisma/client';
|
|
import { User } from '../../src/types/auth';
|
|
|
|
const prisma = new PrismaClient();
|
|
|
|
interface AuthRequest extends Request {
|
|
user?: User;
|
|
}
|
|
|
|
export const auth = async (req: AuthRequest, res: Response, next: NextFunction) => {
|
|
try {
|
|
const token = req.header('Authorization')?.replace('Bearer ', '');
|
|
|
|
if (!token) {
|
|
throw new Error();
|
|
}
|
|
|
|
const decoded = jwt.verify(token, process.env.JWT_SECRET || 'fallback-secret') as { id: string };
|
|
const user = await prisma.user.findUnique({
|
|
where: { id: decoded.id },
|
|
select: {
|
|
id: true,
|
|
email: true,
|
|
displayName: true,
|
|
permissions: true
|
|
}
|
|
});
|
|
|
|
if (!user) {
|
|
throw new Error();
|
|
}
|
|
|
|
req.user = user as User;
|
|
next();
|
|
} catch (error) {
|
|
res.status(401).json({ error: 'Please authenticate' });
|
|
}
|
|
}; |