unpkg/modules/middleware/requireAuth.js

41 lines
935 B
JavaScript
Raw Normal View History

2017-11-11 20:18:13 +00:00
/**
* Adds the given scope to the array in req.auth if the user has sufficient
* permissions. Otherwise rejects the request.
*/
function requireAuth(scope) {
2018-02-18 02:00:56 +00:00
let checkScopes;
2017-11-25 21:25:01 +00:00
if (scope.includes(".")) {
2018-02-18 02:00:56 +00:00
const parts = scope.split(".");
checkScopes = scopes =>
parts.reduce((memo, part) => memo && memo[part], scopes) != null;
2017-11-11 20:18:13 +00:00
} else {
2018-02-18 02:00:56 +00:00
checkScopes = scopes => scopes[scope] != null;
2017-11-11 20:18:13 +00:00
}
return function(req, res, next) {
if (req.auth && req.auth.includes(scope)) {
2018-02-18 02:00:56 +00:00
return next(); // Already auth'd
2017-11-11 20:18:13 +00:00
}
2018-02-18 02:00:56 +00:00
const user = req.user;
2017-11-11 20:18:13 +00:00
if (!user) {
2018-02-18 02:00:56 +00:00
return res.status(403).send({ error: "Missing auth token" });
2017-11-11 20:18:13 +00:00
}
if (!user.scopes || !checkScopes(user.scopes)) {
2018-02-18 02:00:56 +00:00
return res.status(403).send({ error: "Insufficient scopes" });
2017-11-11 20:18:13 +00:00
}
if (req.auth) {
2018-02-18 02:00:56 +00:00
req.auth.push(scope);
2017-11-11 20:18:13 +00:00
} else {
2018-02-18 02:00:56 +00:00
req.auth = [scope];
2017-11-11 20:18:13 +00:00
}
2018-02-18 02:00:56 +00:00
next();
};
2017-11-11 20:18:13 +00:00
}
2018-02-18 02:00:56 +00:00
module.exports = requireAuth;