TwoFactorAuthController.php 2.2 KB

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