This repository has been archived by the owner on May 31, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
hasRole.js
66 lines (52 loc) · 2.64 KB
/
hasRole.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const { SchemaDirectiveVisitor } = require('graphql-tools')
const { defaultFieldResolver } = require('graphql')
const { ForbiddenError } = require('apollo-server-express')
const newInternalServerError = require('../../../../lib/util/internalServerError')
const Joi = require('joi')
const { log } = require('../../../../lib/util/logger')
class HasRoleDirective extends SchemaDirectiveVisitor {
visitFieldDefinition (field) {
const { resolve = defaultFieldResolver } = field
const { error, value } = this.validateArgs()
const { roles } = value
field.resolve = async function (root, args, context, info) {
// must check for a validation error at runtime
// to ensure an appropriate message is sent back
log.info(`checking user is authorized to access ${field.name} on parent ${info.parentType.name}. Must have one of [${roles}]`)
if (error) {
log.error(`Invalid hasRole directive on field ${field.name} on parent ${info.parentType.name}`, error)
throw newInternalServerError(context)
}
if (!context.auth || !context.auth.isAuthenticated()) {
const AuthorizationErrorMessage = `Unable to find authentication. Authorization is required for field ${field.name} on parent ${info.parentType.name}. Must have one of the following roles: [${roles}]`
log.error({ error: AuthorizationErrorMessage })
throw new ForbiddenError(AuthorizationErrorMessage)
}
let foundRole = null // this will be the role the user was successfully authorized on
foundRole = roles.find((role) => {
return context.auth.hasRole(role)
})
if (!foundRole) {
const AuthorizationErrorMessage = `user is not authorized for field ${field.name} on parent ${info.parentType.name}. Must have one of the following roles: [${roles}]`
log.error({ error: AuthorizationErrorMessage, details: context.auth.getTokenContent() })
throw new ForbiddenError(AuthorizationErrorMessage)
}
log.info(`user successfully authorized with role: ${foundRole}`)
// Return appropriate error if this is false
const result = await resolve.apply(this, [root, args, context, info])
return result
}
}
validateArgs () {
// joi is dope. Read the docs and discover the magic.
// https://github.com/hapijs/joi/blob/master/API.md
const argsSchema = Joi.object({
role: Joi.array().required().items(Joi.string()).single()
})
const result = argsSchema.validate(this.args)
// result.value.role will be an array so it makes sense to add the roles alias
result.value.roles = result.value.role
return result
}
}
module.exports = HasRoleDirective