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\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';
22 public function __construct(
23 protected TotpService $totp
28 * Show a view that generates and displays a TOTP QR code.
30 public function generate()
32 if (session()->has(static::SETUP_SECRET_SESSION_KEY)) {
33 $totpSecret = decrypt(session()->get(static::SETUP_SECRET_SESSION_KEY));
35 $totpSecret = $this->totp->generateSecret();
36 session()->put(static::SETUP_SECRET_SESSION_KEY, encrypt($totpSecret));
39 $qrCodeUrl = $this->totp->generateUrl($totpSecret, $this->currentOrLastAttemptedUser());
40 $svg = $this->totp->generateQrCodeSvg($qrCodeUrl);
42 $this->setPageTitle(trans('auth.mfa_gen_totp_title'));
44 return view('mfa.totp-generate', [
51 * Confirm the setup of TOTP and save the auth method secret
52 * against the current user.
54 * @throws ValidationException
55 * @throws NotFoundException
57 public function confirm(Request $request)
59 $totpSecret = decrypt(session()->get(static::SETUP_SECRET_SESSION_KEY));
60 $this->validate($request, [
64 new TotpValidationRule($totpSecret, $this->totp),
68 MfaValue::upsertWithValue($this->currentOrLastAttemptedUser(), MfaValue::METHOD_TOTP, $totpSecret);
69 session()->remove(static::SETUP_SECRET_SESSION_KEY);
70 $this->logActivity(ActivityType::MFA_SETUP_METHOD, 'totp');
72 if (!auth()->check()) {
73 $this->showSuccessNotification(trans('auth.mfa_setup_login_notification'));
75 return redirect('/login');
78 return redirect('/mfa/setup');
82 * Verify the MFA method submission on check.
84 * @throws NotFoundException
86 public function verify(Request $request, LoginService $loginService, MfaSession $mfaSession)
88 $user = $this->currentOrLastAttemptedUser();
89 $totpSecret = MfaValue::getValueForUser($user, MfaValue::METHOD_TOTP);
91 $this->validate($request, [
95 new TotpValidationRule($totpSecret, $this->totp),
99 $mfaSession->markVerifiedForUser($user);
100 $loginService->reattemptLoginFor($user);
102 return redirect()->intended();