generated from lokalise/node-service-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwtTokenPlugin.ts
42 lines (37 loc) · 841 Bytes
/
jwtTokenPlugin.ts
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
import type {
FastifyInstance,
FastifyReply,
FastifyRequest,
HookHandlerDoneFunction,
} from 'fastify'
import fp from 'fastify-plugin'
export type JwtTokenPluginOptions = {
skipList: Set<string>
}
function plugin(
fastify: FastifyInstance,
pluginOptions: JwtTokenPluginOptions,
next: (err?: Error) => void,
) {
fastify.addHook(
'onRequest',
(req: FastifyRequest, _res: FastifyReply, done: HookHandlerDoneFunction) => {
if (req.routeOptions.url && pluginOptions.skipList.has(req.routeOptions.url)) {
return done()
}
req
.jwtVerify()
.then(() => {
done()
})
.catch((err) => {
done(err)
})
},
)
next()
}
export const jwtTokenPlugin = fp<JwtTokenPluginOptions>(plugin, {
fastify: '4.x',
name: 'jwt-token-plugin',
})