init
This commit is contained in:
commit
04267b3886
100 changed files with 16495 additions and 0 deletions
31
backend/src/middleware/auth.ts
Normal file
31
backend/src/middleware/auth.ts
Normal file
|
@ -0,0 +1,31 @@
|
|||
import { RequestHandler } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import dotenv from 'dotenv';
|
||||
dotenv.config();
|
||||
|
||||
export interface JwtPayload { id: string; email: string; }
|
||||
|
||||
declare module 'express-serve-static-core' {
|
||||
interface Request {
|
||||
user?: JwtPayload;
|
||||
}
|
||||
}
|
||||
|
||||
const auth: RequestHandler = (req, res, next) => {
|
||||
const header = req.headers.authorization;
|
||||
const token = header?.split(' ')[1];
|
||||
|
||||
if (!token) {
|
||||
res.status(401).json({ message: 'Token mancante' });
|
||||
return; // ← niente valore
|
||||
}
|
||||
|
||||
try {
|
||||
req.user = jwt.verify(token, process.env.JWT_SECRET!) as JwtPayload;
|
||||
next(); // anche qui il valore è void
|
||||
} catch {
|
||||
res.status(401).json({ message: 'Token non valido' });
|
||||
}
|
||||
};
|
||||
|
||||
export default auth;
|
Loading…
Add table
Add a link
Reference in a new issue