TwoFactorAuthController.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 store(EnableTwoFactorAuthRequest $request)
  19. {
  20. if (!$this->twoFactor->verifyKey(user()->two_factor_secret, $request->two_factor_token)) {
  21. return redirect(url()->previous().'#two-factor')->withErrors(['two_factor_token' => 'The token you entered was incorrect']);
  22. }
  23. user()->webauthnKeys()->delete();
  24. user()->update([
  25. 'two_factor_enabled' => true,
  26. 'two_factor_backup_code' => bcrypt($code = Str::random(40))
  27. ]);
  28. $this->authenticator->login();
  29. return back()->with(['backupCode' => $code]);
  30. }
  31. public function update()
  32. {
  33. if (user()->two_factor_enabled) {
  34. return back()->withErrors(['regenerate_2fa' => 'You must disable 2FA before you can regenerate your secret key']);
  35. }
  36. user()->update(['two_factor_secret' => $this->twoFactor->generateSecretKey()]);
  37. return back()->with(['status' => '2FA Secret Successfully Regenerated']);
  38. }
  39. public function destroy(Request $request)
  40. {
  41. if (!Hash::check($request->current_password_2fa, user()->password)) {
  42. return back()->withErrors(['current_password_2fa' => 'Current password incorrect']);
  43. }
  44. user()->update([
  45. 'two_factor_enabled' => false,
  46. 'two_factor_secret' => $this->twoFactor->generateSecretKey()
  47. ]);
  48. $this->authenticator->logout();
  49. return back()->with(['status' => '2FA Disabled Successfully']);
  50. }
  51. public function authenticateTwoFactor(Request $request)
  52. {
  53. if ($request->session()->has('intended_path')) {
  54. return redirect($request->session()->pull('intended_path'));
  55. }
  56. redirect()->intended($request->redirectPath);
  57. }
  58. }