generated from FIS2425/template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathverifyAuth.js
45 lines (42 loc) · 1.78 KB
/
verifyAuth.js
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
44
45
import jwt from 'jsonwebtoken';
import logger from '../config/logger.js';
const JWT_SECRET= process.env.NODE_ENV=='test'? process.env.VITE_JWT_SECRET:process.env.JWT_SECRET;
export const verifyAuth = (req, res, next) => {
const token = req.cookies.token ? req.cookies.token : (req.headers['authorization'] && req.headers['authorization'].split(' ')[1]);
if (!token) {
logger.error('Error on token validation', {
method: req.method,
url: req.originalUrl,
ip: req.headers && req.headers['x-forwarded-for'] || req.ip,
requestId: req.headers && req.headers['x-request-id'] || null,
error: 'Access denied: No token provided',
});
return res.status(401).send({ error: 'Access denied: No token provided' });
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
if (!decoded.roles.includes('patient') && !decoded.roles.includes('clinicadmin') && !decoded.roles.includes('doctor')) {
logger.error('Error on token validation', {
method: req.method,
url: req.originalUrl,
ip: req.headers && req.headers['x-forwarded-for'] || req.ip,
requestId: req.headers && req.headers['x-request-id'] || null,
userId: decoded.userId,
error: 'Access denied. Insufficient permissions.',
roles: decoded.roles
});
return res.status(403).send({ error: 'Access denied: Insufficient permissions' });
}
req.user = decoded;
next();
} catch (error) {
logger.error('Error on token validation', {
method: req.method,
url: req.originalUrl,
ip: req.headers && req.headers['x-forwarded-for'] || req.ip,
requestId: req.headers && req.headers['x-request-id'] || null,
error: error.message
});
res.status(400).send({ error: 'Invalid token', message: error.message });
}
};