diff options
Diffstat (limited to 'server/helpers/otp.ts')
-rw-r--r-- | server/helpers/otp.ts | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/server/helpers/otp.ts b/server/helpers/otp.ts new file mode 100644 index 000000000..a13edc5e2 --- /dev/null +++ b/server/helpers/otp.ts | |||
@@ -0,0 +1,54 @@ | |||
1 | import { Secret, TOTP } from 'otpauth' | ||
2 | import { WEBSERVER } from '@server/initializers/constants' | ||
3 | |||
4 | function isOTPValid (options: { | ||
5 | secret: string | ||
6 | token: string | ||
7 | }) { | ||
8 | const { token, secret } = options | ||
9 | |||
10 | const totp = new TOTP({ | ||
11 | ...baseOTPOptions(), | ||
12 | |||
13 | secret | ||
14 | }) | ||
15 | |||
16 | const delta = totp.validate({ | ||
17 | token, | ||
18 | window: 1 | ||
19 | }) | ||
20 | |||
21 | if (delta === null) return false | ||
22 | |||
23 | return true | ||
24 | } | ||
25 | |||
26 | function generateOTPSecret (email: string) { | ||
27 | const totp = new TOTP({ | ||
28 | ...baseOTPOptions(), | ||
29 | |||
30 | label: email, | ||
31 | secret: new Secret() | ||
32 | }) | ||
33 | |||
34 | return { | ||
35 | secret: totp.secret.base32, | ||
36 | uri: totp.toString() | ||
37 | } | ||
38 | } | ||
39 | |||
40 | export { | ||
41 | isOTPValid, | ||
42 | generateOTPSecret | ||
43 | } | ||
44 | |||
45 | // --------------------------------------------------------------------------- | ||
46 | |||
47 | function baseOTPOptions () { | ||
48 | return { | ||
49 | issuer: WEBSERVER.HOST, | ||
50 | algorithm: 'SHA1', | ||
51 | digits: 6, | ||
52 | period: 30 | ||
53 | } | ||
54 | } | ||