-
-
Notifications
You must be signed in to change notification settings - Fork 795
Expand file tree
/
Copy pathauthenticate.ts
More file actions
64 lines (48 loc) · 2.1 KB
/
authenticate.ts
File metadata and controls
64 lines (48 loc) · 2.1 KB
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
import flatten from 'lodash/flatten';
import omit from 'lodash/omit';
import { HookContext } from '@feathersjs/feathers';
import { NotAuthenticated } from '@feathersjs/errors';
import Debug from 'debug';
const debug = Debug('@feathersjs/authentication/hooks/authenticate');
export interface AuthenticateHookSettings {
service?: string;
strategies: string[];
}
export default (originalSettings: string | AuthenticateHookSettings, ...originalStrategies: string[]) => {
const settings = typeof originalSettings === 'string'
? { strategies: flatten([ originalSettings, ...originalStrategies ]) }
: originalSettings;
if (!originalSettings || settings.strategies.length === 0) {
throw new Error('The authenticate hook needs at least one allowed strategy');
}
return async (context: HookContext<any, any>) => {
const { app, params, type, path, service } = context;
const { strategies } = settings;
const { provider, authentication } = params;
const authService = app.defaultAuthentication(settings.service);
debug(`Running authenticate hook on '${path}'`);
if (type && type !== 'before') {
throw new NotAuthenticated('The authenticate hook must be used as a before hook');
}
if (!authService || typeof authService.authenticate !== 'function') {
throw new NotAuthenticated('Could not find a valid authentication service');
}
// @ts-ignore
if (service === authService) {
throw new NotAuthenticated('The authenticate hook does not need to be used on the authentication service');
}
if (params.authenticated === true) {
return context;
}
if (authentication) {
const authParams = omit(params, 'provider', 'authentication');
debug('Authenticating with', authentication, strategies);
const authResult = await authService.authenticate(authentication, authParams, ...strategies);
context.params = Object.assign({}, params, omit(authResult, 'accessToken'), { authenticated: true });
return context;
} else if (provider) {
throw new NotAuthenticated('Not authenticated');
}
return context;
};
};