|
<?php |
|
|
|
// App/Http/Controllers/SocialLoginController.php |
|
|
|
namespace App\Http\Controllers; |
|
|
|
use App\Models\User; |
|
use Carbon\CarbonImmutable; |
|
use Illuminate\Contracts\Auth\StatefulGuard; |
|
use Illuminate\Http\RedirectResponse as LaravelRedirectResponse; |
|
use Illuminate\Support\Facades\Auth; |
|
use Illuminate\Support\Str; |
|
use Laravel\Nova\Nova; |
|
use Laravel\Socialite\Facades\Socialite; |
|
use Laravel\Socialite\Two\InvalidStateException; |
|
use Symfony\Component\HttpFoundation\RedirectResponse as SymfonyRedirectResponse; |
|
|
|
class SocialLoginController extends Controller |
|
{ |
|
public string $domain = 'YOUR-GSUIT-DOMAIN.com'; // <-- foobar.com in the credentials.md example |
|
|
|
public function redirectToGoogle(): SymfonyRedirectResponse|LaravelRedirectResponse |
|
{ |
|
/* @phpstan-ignore-next-line */ |
|
return Socialite::driver('google')->with(['hd' => $this->domain])->redirect(); |
|
} |
|
|
|
public function processGoogleCallback(): LaravelRedirectResponse |
|
{ |
|
try { |
|
/* @phpstan-ignore-next-line */ |
|
$socialUser = Socialite::driver('google')->user(); |
|
} catch (InvalidStateException $exception) { |
|
return redirect()->route('nova.login') |
|
->withErrors([ |
|
'oauth2' => [ |
|
__('Login with Google failed. Please try again.'), |
|
], |
|
]); |
|
} |
|
|
|
// Very Important! Stops anyone with a random google account |
|
if (! Str::endsWith($socialUser->getEmail(), $this->domain)) { |
|
return redirect()->route('nova.login') |
|
->withErrors([ |
|
'oauth2' => [ |
|
__('Only :domain accounts can login.', ['domain' => $this->domain]), |
|
], |
|
]); |
|
} |
|
|
|
$user = User::firstOrCreate( |
|
[ |
|
'email' => $socialUser->getEmail() |
|
], |
|
[ |
|
'name' => $socialUser->getName(), |
|
'password' => 'only-social-login_google_'.Str::random(10), // <-- Hash:make(Str::random)) could be guessed, this is not a valid hash for the "password to hash" compare method of the LoginController |
|
] |
|
); |
|
|
|
if ($user->wasRecentlyCreated) { |
|
$user->email_verified_at = CarbonImmutable::now('UTC'); |
|
$user->save(); |
|
} |
|
|
|
$this->guard()->login($user, remember: true); |
|
|
|
return redirect()->intended(Nova::path()); // <-- or any other path where the user should be redirected to after login |
|
} |
|
|
|
/** |
|
* Get the guard to be used during authentication. |
|
*/ |
|
protected function guard(): StatefulGuard |
|
{ |
|
$guard = is_string(config('nova.guard')) ? config('nova.guard') : 'web'; // <-- just use 'web' if you don't use nova |
|
|
|
return Auth::guard($guard); |
|
} |
|
} |