41 lines
1 KiB
TypeScript
41 lines
1 KiB
TypeScript
|
|
import { getSession } from "@auth/express";
|
||
|
|
import type { NextFunction, Request, Response } from "express";
|
||
|
|
import { authConfig } from "../auth/config.js";
|
||
|
|
import type { Ruolo } from "../types/index.js";
|
||
|
|
|
||
|
|
export async function requireAuth(req: Request, res: Response, next: NextFunction) {
|
||
|
|
const session = await getSession(req, authConfig);
|
||
|
|
if (!session?.user?.id) {
|
||
|
|
res.status(401).json({ error: "Autenticazione richiesta" });
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
req.user = {
|
||
|
|
id: Number(session.user.id),
|
||
|
|
email: session.user.email,
|
||
|
|
name: session.user.name,
|
||
|
|
ruolo: session.user.ruolo,
|
||
|
|
};
|
||
|
|
next();
|
||
|
|
}
|
||
|
|
|
||
|
|
export function requireAmministratore(req: Request, res: Response, next: NextFunction) {
|
||
|
|
if (req.user?.ruolo !== "Amministratore") {
|
||
|
|
res.status(403).json({ error: "Operazione riservata agli amministratori" });
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
next();
|
||
|
|
}
|
||
|
|
|
||
|
|
declare global {
|
||
|
|
namespace Express {
|
||
|
|
interface Request {
|
||
|
|
user?: {
|
||
|
|
id: number;
|
||
|
|
email: string;
|
||
|
|
name: string;
|
||
|
|
ruolo: Ruolo;
|
||
|
|
};
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|