forked from unpkg/unpkg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequireAuth.js
More file actions
38 lines (32 loc) · 919 Bytes
/
requireAuth.js
File metadata and controls
38 lines (32 loc) · 919 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Adds the given scope to the array in req.auth if the user has sufficient
* permissions. Otherwise rejects the request.
*/
export default function requireAuth(scope) {
let checkScopes;
if (scope.includes('.')) {
const parts = scope.split('.');
checkScopes = scopes =>
parts.reduce((memo, part) => memo && memo[part], scopes) != null;
} else {
checkScopes = scopes => scopes[scope] != null;
}
return function(req, res, next) {
if (req.auth && req.auth.includes(scope)) {
return next(); // Already auth'd
}
const user = req.user;
if (!user) {
return res.status(403).send({ error: 'Missing auth token' });
}
if (!user.scopes || !checkScopes(user.scopes)) {
return res.status(403).send({ error: 'Insufficient scopes' });
}
if (req.auth) {
req.auth.push(scope);
} else {
req.auth = [scope];
}
next();
};
}