2018-07-25 21:34:16 -04:00
|
|
|
const Key = require('../models/Key.js');
|
2018-07-26 21:52:47 -04:00
|
|
|
const wrap = require('./wrap.js');
|
2018-07-25 21:34:16 -04:00
|
|
|
|
2018-07-28 12:19:38 -04:00
|
|
|
const verifyScope = require('./verifyScope.js');
|
2018-07-25 21:34:16 -04:00
|
|
|
|
2018-07-26 13:15:54 -04:00
|
|
|
// Checks for authentication by either API Key or Session
|
|
|
|
// Sets body.authUser and body.authKey if check passed
|
|
|
|
// If the request is authenticated and has the desired scope, continue.
|
|
|
|
// If the request is authenticated, but lacks the required scope, return 403 Forbidden.
|
|
|
|
// If the request is unauthenticated, return 401 Unauthorized.
|
2018-07-27 14:08:02 -04:00
|
|
|
const requireAuth = scope =>
|
2018-07-25 21:34:16 -04:00
|
|
|
wrap(async (req, res, next) => {
|
2018-07-26 13:15:54 -04:00
|
|
|
if (req.isAuthenticated()) {
|
|
|
|
if (scope ? verifyScope(req.session.passport.scope, scope) : true) {
|
2018-07-26 19:40:42 -04:00
|
|
|
req.username = req.session.passport.user;
|
|
|
|
req.displayname = req.session.passport.displayname;
|
|
|
|
req.scope = req.session.passport.scope;
|
|
|
|
req.key = null;
|
2018-07-26 13:15:54 -04:00
|
|
|
next();
|
|
|
|
} else {
|
|
|
|
res.status(403).json({message: 'Forbidden.'});
|
|
|
|
}
|
2018-07-28 12:19:38 -04:00
|
|
|
} else if (req.body.key) {
|
|
|
|
const key = await Key.findOne({key: key});
|
2018-07-26 13:15:54 -04:00
|
|
|
if (scope ? verifyScope(key.scope, scope) : true) {
|
2018-07-28 12:19:38 -04:00
|
|
|
req.username = key.issuer;
|
|
|
|
req.displayname = key.issuer;
|
2018-07-26 19:40:42 -04:00
|
|
|
req.scope = key.scope;
|
|
|
|
req.key = key.key;
|
2018-07-26 13:15:54 -04:00
|
|
|
next();
|
|
|
|
} else {
|
|
|
|
res.status(403).json({message: 'Forbidden.'});
|
|
|
|
}
|
|
|
|
} else {
|
2018-07-25 21:34:16 -04:00
|
|
|
res.status(401).json({'message': 'Unauthorized.'});
|
2018-07-26 13:15:54 -04:00
|
|
|
}
|
2018-07-27 14:08:02 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
module.exports = requireAuth;
|