Skip to content

Commit bc694ae

Browse files
kevinlaboryczystyl
authored andcommitted
Update README.md (#28)
Add an example of implementation for custom check role function.
1 parent 8159f0e commit bc694ae

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

README.md

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,43 @@ export default {
131131
132132
## Custom check role function
133133
134-
Same as with the authenticate function, you can add your own logic to checking roles.
134+
Same as with the authenticate function, you can add your own logic to checking roles. Here is an example of implementation:
135+
136+
```js
137+
import { AuthenticationError } from 'apollo-server';
138+
import jwt from 'jsonwebtoken';
139+
import { jwtSecret } from '../config';
140+
141+
export default (ctx, value) => {
142+
const authorization =
143+
ctx.request && ctx.request.headers && ctx.request.headers.authorization;
144+
145+
if (!authorization) {
146+
throw new AuthenticationError('Unauthorized access!');
147+
}
148+
149+
const token = authorization.replace('Bearer ', '');
150+
151+
const decodedToken = jwt.verify(token, jwtSecret);
152+
153+
const mandatoryRoles = value.split(',').map((s) => s.trim());
154+
155+
if (decodedToken && decodedToken.user && decodedToken.user.roles) {
156+
const { roles } = decodedToken.user;
157+
const rolesIntersection = roles.filter((role) =>
158+
mandatoryRoles.includes(role),
159+
);
160+
161+
if (rolesIntersection.length === 0) {
162+
throw new AuthenticationError('Invalid role!');
163+
}
164+
165+
return rolesIntersection;
166+
}
167+
168+
throw new AuthenticationError('Invalid token!');
169+
};
170+
```
135171
136172
### How to create your own function
137173

0 commit comments

Comments
 (0)