From c3c25c6d57f2a4a1557cece254bfed7a73fd3516 Mon Sep 17 00:00:00 2001 From: Kevin Labory Date: Fri, 10 Jan 2020 17:16:31 +0100 Subject: [PATCH] Update README.md Add an example of implementation for custom check role function. --- README.md | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 49278d6..fb8d8d2 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,43 @@ export default { ## Custom check role function -Same as with the authenticate function, you can add your own logic to checking roles. +Same as with the authenticate function, you can add your own logic to checking roles. Here is an example of implementation: + +```js +import { AuthenticationError } from 'apollo-server'; +import jwt from 'jsonwebtoken'; +import { jwtSecret } from '../config'; + +export default (ctx, value) => { + const authorization = + ctx.request && ctx.request.headers && ctx.request.headers.authorization; + + if (!authorization) { + throw new AuthenticationError('Unauthorized access!'); + } + + const token = authorization.replace('Bearer ', ''); + + const decodedToken = jwt.verify(token, jwtSecret); + + const mandatoryRoles = value.split(',').map((s) => s.trim()); + + if (decodedToken && decodedToken.user && decodedToken.user.roles) { + const { roles } = decodedToken.user; + const rolesIntersection = roles.filter((role) => + mandatoryRoles.includes(role), + ); + + if (rolesIntersection.length === 0) { + throw new AuthenticationError('Invalid role!'); + } + + return rolesIntersection; + } + + throw new AuthenticationError('Invalid token!'); +}; +``` ### How to create your own function