TwoFactorAuthController.php 2.3 KB

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