add app.grantsRequired

This commit is contained in:
AJ ONeal 2017-05-29 21:39:52 +00:00
parent a2dcd45403
commit f07780ac4e
1 changed files with 38 additions and 0 deletions

View File

@ -157,6 +157,44 @@ module.exports.create = function (xconfx, apiFactories, apiDeps) {
myApp = express();
myApp.handlePromise = require('./common').promisableRequest;
myApp.handleRejection = require('./common').rejectableRequest;
myApp.grantsRequired = function (grants) {
if (!Array.isArray(grants)) {
throw new Error("Usage: app.grantsRequired([ 'name|altname|altname2', 'othergrant' ])");
}
if (!grants.length) {
return function (req, res, next) {
next();
};
}
return function (req, res, next) {
if (!(req.oauth3 || req.oauth3.token)) {
// TODO some error generator for standard messages
res.send({ error: { message: "You must be logged in", code: "E_NO_AUTHN" } });
return;
}
if ('string' !== req.oauth3.token.scp) {
res.send({ error: { message: "Token must contain a grants string in 'scp'", code: "E_NO_GRANTS" } });
return;
}
// every grant in the array must be present
if (!grants.every(function (grant) {
var scopes = grant.split(/\|/g);
return scopes.some(function (scp) {
return req.oauth3.token.scp.split(/[,\s]+/mg).some(function (s) {
return scp === s;
});
});
})) {
res.send({ error: { message: "Token does not contain valid grants: '" + grants + "'", code: "E_NO_GRANTS" } });
return;
}
next();
};
};
var _getOauth3Controllers = pkgDeps.getOauth3Controllers = require('oauthcommon/example-oauthmodels').create(
{ sqlite3Sock: xconfx.sqlite3Sock, ipcKey: xconfx.ipcKey }