BackupCodeController.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Http\Controllers\Auth;
  3. use App\Facades\Webauthn;
  4. use App\Http\Controllers\Controller;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\Hash;
  7. use Illuminate\Support\Str;
  8. use PragmaRX\Google2FALaravel\Support\Authenticator;
  9. class BackupCodeController extends Controller
  10. {
  11. public function __construct()
  12. {
  13. $this->middleware('auth');
  14. $this->middleware('throttle:3,1')->only('login');
  15. }
  16. public function index(Request $request)
  17. {
  18. $authenticator = app(Authenticator::class)->boot($request);
  19. if (($authenticator->isAuthenticated() || ! $request->user()->two_factor_enabled) && ! Webauthn::enabled($request->user())) {
  20. return redirect('/');
  21. }
  22. return view('auth.backup_code');
  23. }
  24. public function login(Request $request)
  25. {
  26. $this->validate($request, [
  27. 'backup_code' => 'required',
  28. ]);
  29. if (! Hash::check($request->backup_code, user()->two_factor_backup_code)) {
  30. return back()->withErrors([
  31. 'backup_code' => __('The backup code was invalid.'),
  32. ]);
  33. }
  34. $twoFactor = app('pragmarx.google2fa');
  35. user()->update([
  36. 'two_factor_enabled' => false,
  37. 'two_factor_secret' => $twoFactor->generateSecretKey(),
  38. 'two_factor_backup_code' => null,
  39. ]);
  40. user()->webauthnKeys()->delete();
  41. if ($request->session()->has('intended_path')) {
  42. return redirect($request->session()->pull('intended_path'));
  43. }
  44. return redirect()->intended($request->redirectPath);
  45. }
  46. public function update()
  47. {
  48. user()->update([
  49. 'two_factor_backup_code' => bcrypt($code = Str::random(40)),
  50. ]);
  51. return back()->with(['backupCode' => $code]);
  52. }
  53. }