forked from MyZubster-Ecosystem/myzubster
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
43 lines (37 loc) 路 1.08 KB
/
Copy pathauth.js
File metadata and controls
43 lines (37 loc) 路 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const jwt = require('jsonwebtoken');
exports.authenticate = async (req, res, next) => {
try {
// Prendi il token dall'header Authorization
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({
success: false,
message: 'Token di autenticazione mancante o non valido'
});
}
const token = authHeader.split(' ')[1];
// Verifica il token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.userId = decoded.userId;
req.userRole = decoded.role;
req.username = decoded.username;
next();
} catch (error) {
console.error('Auth error:', error);
res.status(401).json({
success: false,
message: 'Token non valido o scaduto',
error: error.message
});
}
};
// Middleware per verificare il ruolo admin
exports.isAdmin = (req, res, next) => {
if (req.userRole !== 'admin') {
return res.status(403).json({
success: false,
message: 'Permessi insufficienti. Richiesto ruolo admin.'
});
}
next();
};