TwoFactorAuthController.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace App\Http\Controllers\Auth;
  3. use App\Http\Controllers\Controller;
  4. use App\Http\Requests\EnableTwoFactorAuthRequest;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\Hash;
  7. use Illuminate\Support\Str;
  8. use PragmaRX\Google2FALaravel\Support\Authenticator;
  9. class TwoFactorAuthController extends Controller
  10. {
  11. protected $twoFactor;
  12. protected $authenticator;
  13. public function __construct(Request $request)
  14. {
  15. $this->twoFactor = app('pragmarx.google2fa');
  16. $this->authenticator = app(Authenticator::class)->boot($request);
  17. }
  18. public function index()
  19. {
  20. return redirect('/');
  21. }
  22. public function store(EnableTwoFactorAuthRequest $request)
  23. {
  24. if (! $this->twoFactor->verifyKey(user()->two_factor_secret, $request->two_factor_token)) {
  25. return redirect(url()->previous().'#two-factor')->withErrors(['two_factor_token' => 'The token you entered was incorrect']);
  26. }
  27. user()->webauthnKeys()->delete();
  28. user()->update([
  29. 'two_factor_enabled' => true,
  30. 'two_factor_backup_code' => bcrypt($code = Str::random(40)),
  31. ]);
  32. $this->authenticator->login();
  33. return back()->with(['backupCode' => $code]);
  34. }
  35. public function update()
  36. {
  37. if (user()->two_factor_enabled) {
  38. return back()->withErrors(['regenerate_2fa' => 'You must disable 2FA before you can regenerate your secret key']);
  39. }
  40. user()->update(['two_factor_secret' => $this->twoFactor->generateSecretKey()]);
  41. return back()->with(['status' => '2FA Secret Successfully Regenerated']);
  42. }
  43. public function destroy(Request $request)
  44. {
  45. if (! Hash::check($request->current_password_2fa, user()->password)) {
  46. return back()->withErrors(['current_password_2fa' => 'Current password incorrect']);
  47. }
  48. user()->update([
  49. 'two_factor_enabled' => false,
  50. 'two_factor_secret' => $this->twoFactor->generateSecretKey(),
  51. ]);
  52. $this->authenticator->logout();
  53. return back()->with(['status' => '2FA Disabled Successfully']);
  54. }
  55. public function authenticateTwoFactor(Request $request)
  56. {
  57. if ($request->session()->has('intended_path')) {
  58. return redirect($request->session()->pull('intended_path'));
  59. }
  60. redirect()->intended($request->redirectPath);
  61. }
  62. }