-
Notifications
You must be signed in to change notification settings - Fork 8
/
example.js
52 lines (44 loc) · 1.04 KB
/
example.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
'use strict'
const fastify = require('fastify')()
const fastifyGuard = require('./src/index')
const chalk = require('chalk')
const defaults = { port: 3000 }
;(async () => {
await fastify.register(fastifyGuard)
// simulation for user authentication process
fastify.addHook('onRequest', (req, _, done) => {
req.user = {
id: 306,
name: 'Huseyin',
role: ['user', 'admin', 'editor'],
scope: ['profile', 'email', 'openid'],
location: 'Istanbul'
}
done()
})
fastify.get(
'/',
{ preHandler: [fastify.guard.role('admin')] },
(req, reply) => {
reply
.type('application/json')
.send(req.user)
}
)
fastify.get(
'/insufficient',
{ preHandler: [fastify.guard.role(['supervisor'])] },
(req, reply) => {
reply
.type('application/json')
.send(req.user)
}
)
fastify.listen(defaults.port, () => {
console.log(
chalk.bgYellow(
chalk.black(`Fastify server is running on port: ${defaults.port}`)
)
)
})
})()