38 lines
1.1 KiB
JavaScript
38 lines
1.1 KiB
JavaScript
import Jwt from 'jsonwebtoken';
|
|
|
|
export default function (options) {
|
|
return function jwt(req, res, next) {
|
|
if('exclude' in options && options.exclude.includes(req.path)) {
|
|
next();
|
|
return;
|
|
}
|
|
|
|
if (req.headers && req.headers.authorization) {
|
|
let parts = req.headers.authorization.split(' ');
|
|
if (parts.length == 2) {
|
|
let scheme = parts[0];
|
|
let token = parts[1];
|
|
if (/^Bearer$/i.test(scheme)) {
|
|
Jwt.verify(token, options.secret, (error, decoded) => {
|
|
if(error) {
|
|
res.status(401).send({ success: false, error: error.message });
|
|
console.error(error);
|
|
} else {
|
|
req.user = decoded;
|
|
next();
|
|
}
|
|
});
|
|
} else {
|
|
res.status(401).send({ success: false, error: 'Unsupported authorization header' });
|
|
console.error('Unsupported authorization header');
|
|
}
|
|
} else {
|
|
res.status(401).send({ success: false, error: 'Invalid authorization header' });
|
|
console.error('Invalid authorization header');
|
|
}
|
|
} else {
|
|
res.status(401).send({ success: false, error: 'Missing authorization header' });
|
|
console.error('Missing authorization header');
|
|
}
|
|
};
|
|
} |