1 | 'use strict'
|
2 |
|
3 | const fastify = require('fastify')()
|
4 | const fastifyGuard = require('./src/index')
|
5 | const chalk = require('chalk')
|
6 |
|
7 | const defaults = { port: 3000 }
|
8 |
|
9 | ;(async () => {
|
10 | await fastify.register(fastifyGuard)
|
11 |
|
12 |
|
13 | fastify.addHook('onRequest', (req, reply, done) => {
|
14 | req.user = {
|
15 | id: 306,
|
16 | name: 'Huseyin',
|
17 | role: ['user', 'admin', 'editor'],
|
18 | scope: ['profile', 'email', 'openid'],
|
19 | location: 'Istanbul'
|
20 | }
|
21 |
|
22 | done()
|
23 | })
|
24 |
|
25 | fastify.get(
|
26 | '/',
|
27 | { preHandler: [fastify.guard.role('admin')] },
|
28 | (req, reply) => {
|
29 | reply
|
30 | .type('application/json')
|
31 | .send(req.user)
|
32 | }
|
33 | )
|
34 |
|
35 | fastify.get(
|
36 | '/insufficient',
|
37 | { preHandler: [fastify.guard.role(['supervisor'])] },
|
38 | (req, reply) => {
|
39 | reply
|
40 | .type('application/json')
|
41 | .send(req.user)
|
42 | }
|
43 | )
|
44 |
|
45 | fastify.listen(defaults.port, () => {
|
46 | console.log(
|
47 | chalk.bgYellow(
|
48 | chalk.black(`Fastify server is running on port: ${defaults.port}`)
|
49 | )
|
50 | )
|
51 | })
|
52 | })()
|