-
Notifications
You must be signed in to change notification settings - Fork 98
/
add-verification.ts
62 lines (54 loc) · 1.79 KB
/
add-verification.ts
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
import { GeneralError } from '@feathersjs/errors';
import { checkContext } from 'feathers-hooks-common';
import {
getLongToken,
getShortToken,
ensureFieldHasChanged
} from '../helpers';
import { defaultPath } from '../options';
import type { HookContext } from '@feathersjs/feathers';
import type { AuthenticationManagementService } from '../services';
/**
*
* @param [path='authManagement'] the servicePath for your authManagement service
* @returns
*/
export function addVerification <H extends HookContext = HookContext>(
path?: string
) {
path = path || defaultPath; // default: 'authManagement'
return async (context: H): Promise<H> => {
checkContext(context, 'before', ['create', 'patch', 'update']);
try {
const { options } = (context.app.service(path) as unknown as AuthenticationManagementService);
const dataArray = (Array.isArray(context.data))
? context.data
: [context.data];
if (
(['patch', 'update'].includes(context.method)) &&
!!context.params.user &&
dataArray.some(data => {
return !options.identifyUserProps.some(ensureFieldHasChanged(data, context.params.user));
})
) {
return context;
}
await Promise.all(
dataArray.map(async data => {
const [longToken, shortToken] = await Promise.all([
getLongToken(options.longTokenLen),
getShortToken(options.shortTokenLen, options.shortTokenDigits)
]);
data.isVerified = false;
data.verifyExpires = Date.now() + options.delay;
data.verifyToken = longToken;
data.verifyShortToken = shortToken;
data.verifyChanges = {};
})
);
return context;
} catch (err) {
throw new GeneralError(err);
}
};
}