]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/otp.ts
Support two factor authentication in backend
[github/Chocobozzz/PeerTube.git] / server / helpers / otp.ts
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 }