1 | import { HookContext, NextFunction } from '@feathersjs/feathers'
|
2 | import { NotAuthenticated } from '@feathersjs/errors'
|
3 | import { createDebug } from '@feathersjs/commons'
|
4 |
|
5 | const debug = createDebug('@feathersjs/authentication/hooks/authenticate')
|
6 |
|
7 | export interface AuthenticateHookSettings {
|
8 | service?: string
|
9 | strategies?: string[]
|
10 | }
|
11 |
|
12 | export default (originalSettings: string | AuthenticateHookSettings, ...originalStrategies: string[]) => {
|
13 | const settings =
|
14 | typeof originalSettings === 'string'
|
15 | ? { strategies: [originalSettings, ...originalStrategies] }
|
16 | : originalSettings
|
17 |
|
18 | if (!originalSettings || settings.strategies.length === 0) {
|
19 | throw new Error('The authenticate hook needs at least one allowed strategy')
|
20 | }
|
21 |
|
22 | return async (context: HookContext, _next?: NextFunction) => {
|
23 | const next = typeof _next === 'function' ? _next : async () => context
|
24 | const { app, params, type, path, service } = context
|
25 | const { strategies } = settings
|
26 | const { provider, authentication } = params
|
27 | const authService = app.defaultAuthentication(settings.service)
|
28 |
|
29 | debug(`Running authenticate hook on '${path}'`)
|
30 |
|
31 | if (type && type !== 'before' && type !== 'around') {
|
32 | throw new NotAuthenticated('The authenticate hook must be used as a before hook')
|
33 | }
|
34 |
|
35 | if (!authService || typeof authService.authenticate !== 'function') {
|
36 | throw new NotAuthenticated('Could not find a valid authentication service')
|
37 | }
|
38 |
|
39 | if (service === authService) {
|
40 | throw new NotAuthenticated(
|
41 | 'The authenticate hook does not need to be used on the authentication service'
|
42 | )
|
43 | }
|
44 |
|
45 | if (params.authenticated === true) {
|
46 | return next()
|
47 | }
|
48 |
|
49 | if (authentication) {
|
50 | const { provider, authentication, ...authParams } = params
|
51 |
|
52 | debug('Authenticating with', authentication, strategies)
|
53 |
|
54 | const authResult = await authService.authenticate(authentication, authParams, ...strategies)
|
55 |
|
56 | const { accessToken, ...authResultWithoutToken } = authResult
|
57 |
|
58 | context.params = {
|
59 | ...params,
|
60 | ...authResultWithoutToken,
|
61 | authenticated: true
|
62 | }
|
63 | } else if (provider) {
|
64 | throw new NotAuthenticated('Not authenticated')
|
65 | }
|
66 |
|
67 | return next()
|
68 | }
|
69 | }
|