3 namespace BookStack\Http\Controllers\Auth;
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\Access\LoginService;
7 use BookStack\Auth\Access\Mfa\BackupCodeService;
8 use BookStack\Auth\Access\Mfa\MfaSession;
9 use BookStack\Auth\Access\Mfa\MfaValue;
10 use BookStack\Exceptions\NotFoundException;
11 use BookStack\Http\Controllers\Controller;
13 use Illuminate\Http\Request;
14 use Illuminate\Validation\ValidationException;
16 class MfaBackupCodesController extends Controller
18 use HandlesPartialLogins;
20 protected const SETUP_SECRET_SESSION_KEY = 'mfa-setup-backup-codes';
23 * Show a view that generates and displays backup codes.
25 public function generate(BackupCodeService $codeService)
27 $codes = $codeService->generateNewSet();
28 session()->put(self::SETUP_SECRET_SESSION_KEY, encrypt($codes));
30 $downloadUrl = 'data:application/octet-stream;base64,' . base64_encode(implode("\n\n", $codes));
32 $this->setPageTitle(trans('auth.mfa_gen_backup_codes_title'));
34 return view('mfa.backup-codes-generate', [
36 'downloadUrl' => $downloadUrl,
41 * Confirm the setup of backup codes, storing them against the user.
45 public function confirm()
47 if (!session()->has(self::SETUP_SECRET_SESSION_KEY)) {
48 return response('No generated codes found in the session', 500);
51 $codes = decrypt(session()->pull(self::SETUP_SECRET_SESSION_KEY));
52 MfaValue::upsertWithValue($this->currentOrLastAttemptedUser(), MfaValue::METHOD_BACKUP_CODES, json_encode($codes));
54 $this->logActivity(ActivityType::MFA_SETUP_METHOD, 'backup-codes');
56 if (!auth()->check()) {
57 $this->showSuccessNotification(trans('auth.mfa_setup_login_notification'));
59 return redirect('/login');
62 return redirect('/mfa/setup');
66 * Verify the MFA method submission on check.
68 * @throws NotFoundException
69 * @throws ValidationException
71 public function verify(Request $request, BackupCodeService $codeService, MfaSession $mfaSession, LoginService $loginService)
73 $user = $this->currentOrLastAttemptedUser();
74 $codes = MfaValue::getValueForUser($user, MfaValue::METHOD_BACKUP_CODES) ?? '[]';
76 $this->validate($request, [
78 'required', 'max:12', 'min:8',
79 function ($attribute, $value, $fail) use ($codeService, $codes) {
80 if (!$codeService->inputCodeExistsInSet($value, $codes)) {
81 $fail(trans('validation.backup_codes'));
87 $updatedCodes = $codeService->removeInputCodeFromSet($request->get('code'), $codes);
88 MfaValue::upsertWithValue($user, MfaValue::METHOD_BACKUP_CODES, $updatedCodes);
90 $mfaSession->markVerifiedForUser($user);
91 $loginService->reattemptLoginFor($user);
93 if ($codeService->countCodesInSet($updatedCodes) < 5) {
94 $this->showWarningNotification(trans('auth.mfa_backup_codes_usage_limit_warning'));
97 return redirect()->intended();