3 namespace BookStack\Access\Controllers;
5 use BookStack\Access\LoginService;
6 use BookStack\Access\Mfa\MfaSession;
7 use BookStack\Access\Mfa\MfaValue;
8 use BookStack\Access\Mfa\TotpService;
9 use BookStack\Access\Mfa\TotpValidationRule;
10 use BookStack\Activity\ActivityType;
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, $this->currentOrLastAttemptedUser());
35 $svg = $totp->generateQrCodeSvg($qrCodeUrl);
37 $this->setPageTitle(trans('auth.mfa_gen_totp_title'));
39 return view('mfa.totp-generate', [
46 * Confirm the setup of TOTP and save the auth method secret
47 * against the current user.
49 * @throws ValidationException
50 * @throws NotFoundException
52 public function confirm(Request $request)
54 $totpSecret = decrypt(session()->get(static::SETUP_SECRET_SESSION_KEY));
55 $this->validate($request, [
59 new TotpValidationRule($totpSecret),
63 MfaValue::upsertWithValue($this->currentOrLastAttemptedUser(), MfaValue::METHOD_TOTP, $totpSecret);
64 session()->remove(static::SETUP_SECRET_SESSION_KEY);
65 $this->logActivity(ActivityType::MFA_SETUP_METHOD, 'totp');
67 if (!auth()->check()) {
68 $this->showSuccessNotification(trans('auth.mfa_setup_login_notification'));
70 return redirect('/login');
73 return redirect('/mfa/setup');
77 * Verify the MFA method submission on check.
79 * @throws NotFoundException
81 public function verify(Request $request, LoginService $loginService, MfaSession $mfaSession)
83 $user = $this->currentOrLastAttemptedUser();
84 $totpSecret = MfaValue::getValueForUser($user, MfaValue::METHOD_TOTP);
86 $this->validate($request, [
90 new TotpValidationRule($totpSecret),
94 $mfaSession->markVerifiedForUser($user);
95 $loginService->reattemptLoginFor($user);
97 return redirect()->intended();