-
Notifications
You must be signed in to change notification settings - Fork 46
/
index.js
49 lines (46 loc) · 1.26 KB
/
index.js
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
39
40
41
42
43
44
45
46
47
48
49
const jwt = require('jsonwebtoken');
const { AuthorizationError } = require('./../errors');
const checkAuthAndResolve = (context, controller) => {
const token = context.headers.authorization;
if (!token) {
throw new AuthorizationError({
message: `You must supply a JWT for authorization!`
});
}
const decoded = jwt.verify(
token.replace('Bearer ', ''),
process.env.JWT_SECRET
);
return controller.apply(this, [decoded]);
};
const checkScopesAndResolve = (
context,
expectedScopes,
controller,
...params
) => {
const token = context.headers.authorization;
if (!token) {
throw new AuthorizationError({
message: `You must supply a JWT for authorization!`
});
}
const decoded = jwt.verify(
token.replace('Bearer ', ''),
process.env.JWT_SECRET
);
const scopes = decoded.scope;
if (!scopes) {
throw new AuthorizationError({ message: 'No scopes supplied!' });
}
if (scopes && expectedScopes.some(scope => scopes.indexOf(scope) !== -1)) {
return controller.apply(this, params);
} else {
throw new AuthorizationError({
message: `You are not authorized. Expected scopes: ${expectedScopes.join(
', '
)}`
});
}
};
module.exports = { checkAuthAndResolve, checkScopesAndResolve };