trypost/app/Http/Controllers/Auth/SocialLoginController.php

74 lines
1.9 KiB
PHP
Raw Normal View History

2026-03-31 00:18:07 +00:00
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Auth;
use App\Actions\User\CreateUser;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
class SocialLoginController extends Controller
{
public function redirect(): RedirectResponse
{
return Socialite::driver('google-auth')->redirect();
}
public function callback(): RedirectResponse
{
try {
$googleUser = Socialite::driver('google-auth')->user();
} catch (\Exception) {
return redirect()->route('login');
}
2026-03-31 00:18:07 +00:00
$user = User::where('google_id', $googleUser->getId())
->orWhere('email', $googleUser->getEmail())
->first();
2026-03-31 00:18:07 +00:00
if ($user) {
return $this->loginExistingUser($user, $googleUser->getId());
2026-03-31 00:18:07 +00:00
}
return $this->registerNewUser($googleUser);
}
private function loginExistingUser(User $user, string $googleId): RedirectResponse
2026-03-31 00:18:07 +00:00
{
if (! $user->google_id) {
$user->update(['google_id' => $googleId]);
}
2026-03-31 00:18:07 +00:00
if (! $user->hasVerifiedEmail()) {
$user->markEmailAsVerified();
}
Auth::login($user, remember: true);
return redirect()->route('app.home');
}
private function registerNewUser(\Laravel\Socialite\Contracts\User $googleUser): RedirectResponse
{
$user = CreateUser::execute([
'name' => $googleUser->getName(),
'email' => $googleUser->getEmail(),
'google_id' => $googleUser->getId(),
2026-03-31 00:18:07 +00:00
'email_verified_at' => now(),
]);
event(new Registered($user));
Auth::login($user, remember: true);
2026-03-31 00:32:43 +00:00
session()->flash('auth_provider', 'google');
return redirect()->route('register.success');
2026-03-31 00:18:07 +00:00
}
}