3 namespace BookStack\Auth\Access\Mfa;
5 use BaconQrCode\Renderer\Color\Rgb;
6 use BaconQrCode\Renderer\Image\SvgImageBackEnd;
7 use BaconQrCode\Renderer\ImageRenderer;
8 use BaconQrCode\Renderer\RendererStyle\Fill;
9 use BaconQrCode\Renderer\RendererStyle\RendererStyle;
10 use BaconQrCode\Writer;
11 use BookStack\Auth\User;
12 use PragmaRX\Google2FA\Google2FA;
13 use PragmaRX\Google2FA\Support\Constants;
19 public function __construct(Google2FA $google2fa)
21 $this->google2fa = $google2fa;
22 // Use SHA1 as a default, Personal testing of other options in 2021 found
23 // many apps lack support for other algorithms yet still will scan
24 // the code causing a confusing UX.
25 $this->google2fa->setAlgorithm(Constants::SHA1);
29 * Generate a new totp secret key.
31 public function generateSecret(): string
33 /** @noinspection PhpUnhandledExceptionInspection */
34 return $this->google2fa->generateSecretKey();
38 * Generate a TOTP URL from secret key.
40 public function generateUrl(string $secret, User $user): string
42 return $this->google2fa->getQRCodeUrl(
50 * Generate a QR code to display a TOTP URL.
52 public function generateQrCodeSvg(string $url): string
54 $color = Fill::uniformColor(new Rgb(255, 255, 255), new Rgb(32, 110, 167));
58 new RendererStyle(192, 4, null, null, $color),
61 ))->writeString($url);
65 * Verify that the user provided code is valid for the secret.
66 * The secret must be known, not user-provided.
68 public function verifyCode(string $code, string $secret): bool
70 /** @noinspection PhpUnhandledExceptionInspection */
71 return $this->google2fa->verifyKey($secret, $code);