UNPKG

1.06 kBJavaScriptView Raw
1'use strict'
2
3const fastify = require('fastify')()
4const fastifyGuard = require('./src/index')
5const chalk = require('chalk')
6
7const defaults = { port: 3000 }
8
9;(async () => {
10 await fastify.register(fastifyGuard)
11
12 // simulation for user authentication process
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})()