1
0
mirror of https://github.com/Foltik/Shimapan synced 2024-11-13 00:26:55 -05:00

Make requireAuth() add request variables

This commit is contained in:
Jack Foltz 2018-07-26 13:15:54 -04:00
parent 0db0caf422
commit d0b26a7021
Signed by: foltik
GPG Key ID: 303F88F996E95541
2 changed files with 36 additions and 16 deletions

View File

@ -97,26 +97,24 @@ router.post('/login', canonicalizeRequest, wrap(async (req, res, next) => {
// Create session
await login(user, req);
// Set scope
// Set session vars
req.session.passport.display = user.username;
req.session.passport.scope = user.scope;
res.status(200).json({'message': 'Logged in.'});
}));
router.get('/logout', function (req, res) {
router.post('/logout', function (req, res) {
req.logout();
res.status(200).json({'message': 'Logged out.'});
});
router.get('/ping', requireAuth(), (req, res, next) => {
res.status(200).json({'message': 'pong'});
});
router.get('/session', requireAuth(), (req, res, next) => {
router.get('/whoami', requireAuth(), (req, res) => {
res.status(200).json({
username: req.session.passport.username,
canonicalname: req.session.passport.canonicalname,
scope: req.session.passport.scope
user: req.authUser,
display: req.authDisplay,
scope: req.authScope,
key: req.authKey
});
});

View File

@ -2,14 +2,36 @@ const Key = require('../models/Key.js');
const wrap = require('./wrap.js').wrap;
const verifyScope = (scope, requiredScope) => scope.indexOf(requiredScope) !== -1;
const getKeyScope = async apikey => (await Key.findOne({key: apikey})).scope;
// 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.
exports.requireAuth = scope =>
wrap(async (req, res, next) => {
if (req.isAuthenticated() && (scope ? verifyScope(req.session.passport.scope, scope) : true))
next();
else if (req.body.apikey && (scope ? verifyScope(getKeyScope(req.body.apikey), scope) : true))
next();
else
if (req.isAuthenticated()) {
if (scope ? verifyScope(req.session.passport.scope, scope) : true) {
req.authUser = req.session.passport.user;
req.authDisplay = req.session.passport.display;
req.authScope = req.session.passport.scope;
req.authKey = null;
next();
} else {
res.status(403).json({message: 'Forbidden.'});
}
} else if (req.body.apikey) {
const key = await Key.findOne({key: apikey});
if (scope ? verifyScope(key.scope, scope) : true) {
req.authUser = key.username;
req.authDisplay = key.username;
req.authScope = key.scope;
req.authKey = key.key;
next();
} else {
res.status(403).json({message: 'Forbidden.'});
}
} else {
res.status(401).json({'message': 'Unauthorized.'});
}
});