UNPKG

1.38 kBJavaScriptView Raw
1'use strict'
2
3// get required node modules
4const fastify = require('fastify')()
5const fastifyGuard = require('./src/index')
6const chalk = require('chalk')
7
8// defaults
9const defaults = { port: 3000 }
10
11;(async () => {
12 // register the plugin
13 await fastify.register(fastifyGuard)
14
15 // simulation for user authentication process
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 // all done
26 done()
27 })
28
29 // below routes are protected by fastify-guard
30 fastify.get(
31 '/',
32 { preHandler: [fastify.guard.role('admin')] },
33 (req, reply) => {
34 // set return type
35 reply.type('application/json')
36
37 // return the user
38 reply.send(req.user)
39 }
40 )
41
42 fastify.get(
43 '/insufficient',
44 { preHandler: [fastify.guard.role(['supervisor'])] },
45 (req, reply) => {
46 // set return type
47 reply.type('application/json')
48
49 // return the user
50 reply.send(req.user)
51 }
52 )
53
54 // initialize the fastify server
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})()