BackupCodeController.php 1.5 KB

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