2020-11-20 10:02:30 +00:00
|
|
|
const jwt = require('express-jwt');
|
|
|
|
const secret = require('../config').secret;
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-09-29 20:08:29 +00:00
|
|
|
function getTokenFromHeader(req) {
|
2020-11-21 15:38:52 +00:00
|
|
|
const [tokenType, token] = req.headers.authorization?.split(' ') || [];
|
|
|
|
|
|
|
|
if (tokenType === 'Token' || tokenType === 'Bearer') {
|
|
|
|
return token;
|
2020-04-13 00:02:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2020-11-21 15:38:52 +00:00
|
|
|
const jwtOptional = jwt({
|
|
|
|
secret: secret,
|
|
|
|
userProperty: 'payload',
|
|
|
|
credentialsRequired: false,
|
|
|
|
getToken: getTokenFromHeader,
|
|
|
|
algorithms: ['HS256'],
|
|
|
|
});
|
2020-04-13 00:02:40 +00:00
|
|
|
|
2020-11-21 15:38:52 +00:00
|
|
|
function getUserIdMiddleware(req, res, next) {
|
|
|
|
try {
|
|
|
|
const [tokenType, token] = req.headers.authorization.split(' ') || [];
|
|
|
|
|
|
|
|
if (tokenType === 'Token' || tokenType === 'Bearer') {
|
|
|
|
return jwtOptional(req, res, next);
|
|
|
|
} else if (tokenType === 'OBSUserId') {
|
|
|
|
req.payload = { id: token.trim() };
|
|
|
|
next();
|
|
|
|
} else {
|
|
|
|
req.payload = null;
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
next(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
required(req, res, next) {
|
|
|
|
if (!req.payload) {
|
|
|
|
return res.sendStatus(403);
|
|
|
|
} else {
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
},
|
|
|
|
optional(req, res, next) {
|
|
|
|
return next();
|
|
|
|
},
|
|
|
|
getUserIdMiddleware,
|
|
|
|
};
|