aboutsummaryrefslogtreecommitdiff
path: root/src/lib/auth-helpers.ts
blob: b2d748854a4839a0fa66be2bd9852b70371ca8c7 (plain)
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
import { authenticator } from "otplib"

interface TwoFactorCheck {
  twoFactorEnabled?: boolean
  twoFactorSecret?: string
}

export function verifyTwoFactor(
  user: TwoFactorCheck, 
  code?: string
): void {
  if (user.twoFactorEnabled) {
    // If the user signed up but hasn't set up 2FA yet (secret is missing),
    // we can either skip 2FA or treat it as disabled.
    // Here we treat it as disabled if no secret is present.
    if (user.twoFactorSecret) {
      if (!code) {
        throw new Error("2FA_REQUIRED")
      }

      const isValid = authenticator.check(code, user.twoFactorSecret)
      if (!isValid) {
        throw new Error("Invalid 2FA Code")
      }
    }
  }
}