-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathindex.js
66 lines (58 loc) · 2.06 KB
/
index.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'use strict'
const fp = require('fastify-plugin')
const verifyBearerAuthFactory = require('./lib/verify-bearer-auth-factory')
const { FST_BEARER_AUTH_INVALID_HOOK, FST_BEARER_AUTH_INVALID_LOG_LEVEL } = require('./lib/errors')
/**
* Hook type limited to 'onRequest' and 'preParsing' to protect against DoS attacks.
* @see {@link https://github.com/fastify/fastify-auth?tab=readme-ov-file#hook-selection | fastify-auth hook selection}
*/
const validHooks = new Set(['onRequest', 'preParsing'])
function fastifyBearerAuth (fastify, options, done) {
options = { verifyErrorLogLevel: 'error', ...options }
if (options.addHook === true || options.addHook == null) {
options.addHook = 'onRequest'
}
if (
Object.hasOwn(fastify.log, 'error') === false ||
typeof fastify.log.error !== 'function'
) {
options.verifyErrorLogLevel = null
}
if (
options.verifyErrorLogLevel != null &&
(
typeof options.verifyErrorLogLevel !== 'string' ||
Object.hasOwn(fastify.log, options.verifyErrorLogLevel) === false ||
typeof fastify.log[options.verifyErrorLogLevel] !== 'function'
)
) {
done(new FST_BEARER_AUTH_INVALID_LOG_LEVEL(options.verifyErrorLogLevel))
}
try {
if (options.addHook) {
if (!validHooks.has(options.addHook)) {
done(new FST_BEARER_AUTH_INVALID_HOOK())
}
if (options.addHook === 'preParsing') {
const verifyBearerAuth = verifyBearerAuthFactory(options)
fastify.addHook('preParsing', (request, reply, _payload, done) => {
verifyBearerAuth(request, reply, done)
})
} else {
fastify.addHook(options.addHook, verifyBearerAuthFactory(options))
}
} else {
fastify.decorate('verifyBearerAuthFactory', verifyBearerAuthFactory)
fastify.decorate('verifyBearerAuth', verifyBearerAuthFactory(options))
}
done()
} catch (err) {
done(err)
}
}
module.exports = fp(fastifyBearerAuth, {
fastify: '5.x',
name: '@fastify/bearer-auth'
})
module.exports.default = fastifyBearerAuth
module.exports.fastifyBearerAuth = fastifyBearerAuth