3 namespace BookStack\Http\Controllers\Auth;
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\Access\LoginService;
7 use BookStack\Auth\Access\Mfa\MfaSession;
8 use BookStack\Auth\Access\Mfa\MfaValue;
9 use BookStack\Auth\Access\Mfa\TotpService;
10 use BookStack\Auth\Access\Mfa\TotpValidationRule;
11 use BookStack\Exceptions\NotFoundException;
12 use BookStack\Http\Controllers\Controller;
13 use Illuminate\Http\Request;
14 use Illuminate\Validation\ValidationException;
16 class MfaTotpController extends Controller
18 use HandlesPartialLogins;
20 protected const SETUP_SECRET_SESSION_KEY = 'mfa-setup-totp-secret';
23 * Show a view that generates and displays a TOTP QR code.
25 public function generate(TotpService $totp)
27 if (session()->has(static::SETUP_SECRET_SESSION_KEY)) {
28 $totpSecret = decrypt(session()->get(static::SETUP_SECRET_SESSION_KEY));
30 $totpSecret = $totp->generateSecret();
31 session()->put(static::SETUP_SECRET_SESSION_KEY, encrypt($totpSecret));
34 $qrCodeUrl = $totp->generateUrl($totpSecret);
35 $svg = $totp->generateQrCodeSvg($qrCodeUrl);
37 return view('mfa.totp-generate', [
38 'secret' => $totpSecret,
44 * Confirm the setup of TOTP and save the auth method secret
45 * against the current user.
46 * @throws ValidationException
47 * @throws NotFoundException
49 public function confirm(Request $request)
51 $totpSecret = decrypt(session()->get(static::SETUP_SECRET_SESSION_KEY));
52 $this->validate($request, [
56 new TotpValidationRule($totpSecret),
60 MfaValue::upsertWithValue($this->currentOrLastAttemptedUser(), MfaValue::METHOD_TOTP, $totpSecret);
61 session()->remove(static::SETUP_SECRET_SESSION_KEY);
62 $this->logActivity(ActivityType::MFA_SETUP_METHOD, 'totp');
64 if (!auth()->check()) {
65 $this->showSuccessNotification(trans('auth.mfa_setup_login_notification'));
66 return redirect('/login');
69 return redirect('/mfa/setup');
73 * Verify the MFA method submission on check.
74 * @throws NotFoundException
76 public function verify(Request $request, LoginService $loginService, MfaSession $mfaSession)
78 $user = $this->currentOrLastAttemptedUser();
79 $totpSecret = MfaValue::getValueForUser($user, MfaValue::METHOD_TOTP);
81 $this->validate($request, [
85 new TotpValidationRule($totpSecret),
89 $mfaSession->markVerifiedForUser($user);
90 $loginService->reattemptLoginFor($user);
92 return redirect()->intended();