SocialiteController.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Http\Controllers\Auth;
  3. use App\Facades\Settings;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\User;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Support\Carbon;
  8. use Illuminate\Support\Facades\Auth;
  9. use Illuminate\Support\Str;
  10. use Laravel\Socialite\Facades\Socialite;
  11. class SocialiteController extends Controller
  12. {
  13. /**
  14. * Redirect to the provider's authentication url
  15. *
  16. * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Illuminate\Http\RedirectResponse
  17. */
  18. public function redirect(Request $request, string $driver)
  19. {
  20. if (! config('services.' . $driver . '.client_id') || ! config('services.' . $driver . '.client_secret')) {
  21. return redirect('/error?err=sso_bad_provider_setup');
  22. }
  23. return Settings::get('enableSso')
  24. ? Socialite::driver($driver)->redirect()
  25. : redirect('/error?err=sso_disabled');
  26. }
  27. /**
  28. * Register (if needed) the user and authenticate him
  29. *
  30. * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
  31. */
  32. public function callback(Request $request, string $driver)
  33. {
  34. try {
  35. $socialiteUser = Socialite::driver($driver)->user();
  36. } catch (\Exception $e) {
  37. return redirect('/error?err=sso_failed');
  38. }
  39. /** @var User|null $user */
  40. $user = User::firstOrNew([
  41. 'oauth_id' => $socialiteUser->getId(),
  42. 'oauth_provider' => $driver,
  43. ]);
  44. if (! $user->exists) {
  45. if (User::count() === 0) {
  46. $user->is_admin = true;
  47. }
  48. else if (Settings::get('disableRegistration')) {
  49. return redirect('/error?err=no_register');
  50. }
  51. $user->password = bcrypt(Str::random());
  52. }
  53. $user->email = $socialiteUser->getEmail() ?? $socialiteUser->getId() . '@' . $driver;
  54. $user->name = $socialiteUser->getNickname() ?? $socialiteUser->getName() ?? $driver . ' #' . $socialiteUser->getId();
  55. $user->last_seen_at = Carbon::now()->format('Y-m-d H:i:s');
  56. $user->save();
  57. Auth::guard()->login($user);
  58. return redirect('/accounts');
  59. }
  60. }