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