1 | import flatten from 'lodash/flatten';
|
2 | import omit from 'lodash/omit';
|
3 | import { HookContext } from '@feathersjs/feathers';
|
4 | import { NotAuthenticated } from '@feathersjs/errors';
|
5 | import Debug from 'debug';
|
6 |
|
7 | const debug = Debug('@feathersjs/authentication/hooks/authenticate');
|
8 |
|
9 | export interface AuthenticateHookSettings {
|
10 | service?: string;
|
11 | strategies: string[];
|
12 | }
|
13 |
|
14 | export default (originalSettings: string | AuthenticateHookSettings, ...originalStrategies: string[]) => {
|
15 | const settings = typeof originalSettings === 'string'
|
16 | ? { strategies: flatten([ originalSettings, ...originalStrategies ]) }
|
17 | : originalSettings;
|
18 |
|
19 | if (!originalSettings || settings.strategies.length === 0) {
|
20 | throw new Error('The authenticate hook needs at least one allowed strategy');
|
21 | }
|
22 |
|
23 | return async (context: HookContext) => {
|
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') {
|
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 |
|
40 | if (service === authService) {
|
41 | throw new NotAuthenticated('The authenticate hook does not need to be used on the authentication service');
|
42 | }
|
43 |
|
44 | if (params.authenticated === true) {
|
45 | return context;
|
46 | }
|
47 |
|
48 | if (authentication) {
|
49 | const authParams = omit(params, 'provider', 'authentication');
|
50 |
|
51 | debug('Authenticating with', authentication, strategies);
|
52 |
|
53 | const authResult = await authService.authenticate(authentication, authParams, ...strategies);
|
54 |
|
55 | context.params = Object.assign({}, params, omit(authResult, 'accessToken'), { authenticated: true });
|
56 |
|
57 | return context;
|
58 | } else if (provider) {
|
59 | throw new NotAuthenticated('Not authenticated');
|
60 | }
|
61 |
|
62 | return context;
|
63 | };
|
64 | };
|