-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
89 lines (74 loc) · 2.25 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
'use strict'
const fp = require('fastify-plugin')
/**
* Namespace applies to both JWT and headers
* We can have JWT, webhook or both. In teh "both" case:
* 1. JWT is checked first, if this is OK, the user is created from the JWT token
* 2. If JWT is not OK, the user is created from the answer returned by the webhook (currently the body)
*/
async function fastifyUser (app, options, done) {
const {
webhook,
jwt,
authStrategies
} = options
const strategies = []
if (jwt) {
await app.register(require('./lib/jwt'), { jwt })
strategies.push({
name: 'jwt',
createSession: (req) => req.createJWTSession()
})
}
if (webhook) {
await app.register(require('./lib/webhook'), { webhook })
strategies.push({
name: 'webhook',
createSession: (req) => req.createWebhookSession()
})
}
for (const strategy of authStrategies || []) {
strategies.push(strategy)
}
app.decorate('addAuthStrategy', (strategy) => {
strategies.push(strategy)
})
app.decorateRequest('createSession', async function () {
const errors = []
for (const strategy of strategies) {
try {
return await strategy.createSession(this)
} catch (error) {
errors.push({ strategy: strategy.name, error })
this.log.trace({ strategy: strategy.name, error })
}
}
if (errors.length === 1) {
throw new Error(errors[0].error)
}
const errorsMessage = errors.map(({ strategy, error }) => `${strategy}: ${error}`).join('; ')
throw new Error(`No auth strategy succeeded. ${errorsMessage}`)
})
const extractUser = async function () {
const request = this
if (typeof request.createSession === 'function') {
try {
// `createSession` actually exists only if jwt or webhook are enabled
// and creates a new `request.user` object
await request.createSession()
request.log.debug({ user: request.user }, 'logged user in')
} catch (err) {
request.log.error({ err })
}
}
return request.user
}
app.decorateRequest('extractUser', extractUser)
done()
}
module.exports = fp(fastifyUser, {
fastify: '4.x',
name: 'fastify-user'
})
module.exports.default = fastifyUser
module.exports.fastifyUser = fastifyUser