diff options
author | Chocobozzz <me@florianbigard.com> | 2022-10-05 15:37:15 +0200 |
---|---|---|
committer | Chocobozzz <me@florianbigard.com> | 2022-10-07 10:51:16 +0200 |
commit | 56f47830758ff8e92abcfcc5f35d474ab12fe215 (patch) | |
tree | 854e57ec1b800d6ad740c8e42bee00cbd21e1724 /server/helpers | |
parent | 7dd7ff4cebc290b09fe00d82046bb58e4e8a800d (diff) | |
download | PeerTube-56f47830758ff8e92abcfcc5f35d474ab12fe215.tar.gz PeerTube-56f47830758ff8e92abcfcc5f35d474ab12fe215.tar.zst PeerTube-56f47830758ff8e92abcfcc5f35d474ab12fe215.zip |
Support two factor authentication in backend
Diffstat (limited to 'server/helpers')
-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 | } | ||