feat: read a new (temporary) token type, OBSUserId from Authorization header

This commit is contained in:
Paul Bienkowski 2020-11-21 16:38:52 +01:00
parent b63afb1146
commit fb11a71663
2 changed files with 44 additions and 21 deletions

2
app.js
View file

@ -5,6 +5,7 @@ const session = require('express-session');
const cors = require('cors'); const cors = require('cors');
const errorhandler = require('errorhandler'); const errorhandler = require('errorhandler');
const mongoose = require('mongoose'); const mongoose = require('mongoose');
const auth = require('./routes/auth');
const isProduction = process.env.NODE_ENV === 'production'; const isProduction = process.env.NODE_ENV === 'production';
@ -12,6 +13,7 @@ const isProduction = process.env.NODE_ENV === 'production';
const app = express(); const app = express();
app.use(cors()); app.use(cors());
app.use(auth.getUserIdMiddleware);
// Normal express config defaults // Normal express config defaults
app.use(require('morgan')('dev')); app.use(require('morgan')('dev'));

View file

@ -2,30 +2,51 @@ const jwt = require('express-jwt');
const secret = require('../config').secret; const secret = require('../config').secret;
function getTokenFromHeader(req) { function getTokenFromHeader(req) {
if ( const [tokenType, token] = req.headers.authorization?.split(' ') || [];
(req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Token') ||
(req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') if (tokenType === 'Token' || tokenType === 'Bearer') {
) { return token;
return req.headers.authorization.split(' ')[1];
} }
return null; return null;
} }
const auth = { const jwtOptional = jwt({
required: jwt({ secret: secret,
secret: secret, userProperty: 'payload',
userProperty: 'payload', credentialsRequired: false,
getToken: getTokenFromHeader, getToken: getTokenFromHeader,
algorithms: ['HS256'], algorithms: ['HS256'],
}), });
optional: jwt({
secret: secret,
userProperty: 'payload',
credentialsRequired: false,
getToken: getTokenFromHeader,
algorithms: ['HS256'],
}),
};
module.exports = auth; 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,
};