diff --git a/lib/apis.js b/lib/apis.js index b807721..e7970a7 100644 --- a/lib/apis.js +++ b/lib/apis.js @@ -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 }