Skip to content

Commit db1195d

Browse files
committed
protected graphql
1 parent 8e605bb commit db1195d

2 files changed

Lines changed: 21 additions & 14 deletions

File tree

auth-graphql/auth-gql.js

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ const GQL = require('fastify-gql')
44
const JWT = require('fastify-jwt')
55

66
function plugin (instance, options, next) {
7+
/**
8+
* Authentication settings
9+
*/
710
instance.register(JWT, {
811
secret: 'supersecret'
912
})
@@ -16,42 +19,46 @@ function plugin (instance, options, next) {
1619

1720
instance.decorate('authenticate', async function (request, reply) {
1821
try {
22+
// Autorization logic
1923
await request.jwtVerify()
2024
} catch (err) {
2125
reply.send(err)
2226
}
2327
})
2428

29+
instance.addHook('onRoute', (routeOptions) => {
30+
if (routeOptions.url === '/graphql') {
31+
routeOptions.preValidation = [instance.authenticate]
32+
}
33+
})
34+
35+
/**
36+
* GraphQL Stuff
37+
*/
2538
const schema = `
26-
type Query {
27-
add(x: Int, y: Int): Int
28-
}
29-
`
39+
type Query {
40+
add(x: Int, y: Int): Int
41+
}
42+
`
3043

3144
const resolvers = {
3245
Query: {
3346
add: async (_, { x, y }) => x + y
3447
}
3548
}
3649

50+
// A protected /graphql endpoint is exposed
3751
instance.register(GQL, {
3852
schema,
3953
resolvers
4054
})
4155

56+
// I can use the graphql also without authentication
4257
instance.get('/public', async function (req, reply) {
4358
const query = '{ add(x: 2, y: 2) }'
4459
return reply.graphql(query)
4560
})
4661

47-
instance.get('/private',
48-
{
49-
preValidation: [instance.authenticate]
50-
}, async function (req, reply) {
51-
const query = '{ add(x: 5, y: 5) }'
52-
return reply.graphql(query)
53-
})
54-
5562
next()
5663
}
5764

auth-graphql/package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@
88
"lint": "standard",
99
"lint:fix": "standard --fix",
1010
"try-me:public": "curl http://localhost:3000/public",
11-
"try-me:private": "curl http://localhost:3000/private",
11+
"try-me:private": "curl -X POST http://localhost:3000/graphql -H 'Content-Type: application/json' -H 'Authorization: Bearer ${JWT_TOKEN}' -d '{\"query\": \"{ add(x: 2, y: 2) }\" }'",
1212
"try-me:login": "JWT_TOKEN=$(curl -X POST http://localhost:3000/login) && echo ${JWT_TOKEN}",
13-
"try-me:private:login": "JWT_TOKEN=$(curl -X POST http://localhost:3000/login) && echo ${JWT_TOKEN} && curl http://localhost:3000/private -H \"Authorization: Bearer ${JWT_TOKEN}\"",
13+
"try-me:private:login": "npm run try-me:login && try-me:private",
1414
"test": "echo \"Error: no test specified\" && exit 1"
1515
},
1616
"keywords": [],

0 commit comments

Comments
 (0)