TwoFactorAuthController.php 2.0 KB

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