-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
47 lines (38 loc) · 1.3 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
'use strict'
const fp = require('fastify-plugin')
const Auth = require('./lib/auth')
const { validateOpts } = require('./lib/validation')
const filterSchema = require('./lib/filter-schema')
const plugin = fp(
async function (app, opts) {
validateOpts(opts)
// Start auth and register hooks
const auth = new Auth(opts)
// Get auth policy
const authSchema = auth.getPolicy(app.graphql.schema)
// Wrap resolvers with auth handlers
auth.registerAuthHandlers(app.graphql.schema, authSchema, opts.outputPolicyErrors)
// Add hook to regenerate the resolvers when the schema is refreshed
if (app.graphqlGateway) {
app.graphqlGateway.addHook('onGatewayReplaceSchema', async (instance, schema) => {
const authSchema = auth.getPolicy(schema)
auth.registerAuthHandlers(schema, authSchema, opts.outputPolicyErrors)
if (opts.filterSchema === true) {
filterSchema.updatePolicy(app, authSchema, opts)
}
})
}
if (typeof opts.authContext !== 'undefined') {
app.graphql.addHook('preExecution', auth.authContextHook.bind(auth))
}
if (opts.filterSchema === true) {
filterSchema(app, authSchema, opts)
}
},
{
name: 'mercurius-auth',
fastify: '5.x',
dependencies: ['mercurius']
}
)
module.exports = plugin