-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSocialLoginController.php
More file actions
82 lines (65 loc) · 2.41 KB
/
SocialLoginController.php
File metadata and controls
82 lines (65 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Auth;
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
{
/**
* Redirect to Google OAuth.
*/
public function redirectToGoogle(): RedirectResponse
{
return Socialite::driver('google')->redirect();
}
/**
* Handle Google OAuth callback.
*/
public function handleGoogleCallback(): RedirectResponse
{
try {
$googleUser = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect()->route('login')->with('error', 'Unable to authenticate with Google. Please try again.');
}
// Check if user exists with this Google ID
$user = User::query()->where('google_id', $googleUser->getId())->first();
if ($user) {
// Ensure email is verified for existing Google users
if (!$user->hasVerifiedEmail()) {
$user->markEmailAsVerified();
}
Auth::login($user, true);
return redirect()->intended('/');
}
// Check if user exists with this email
$user = User::query()->where('email', $googleUser->getEmail())->first();
if ($user) {
// Link Google account to existing user and mark email as verified
$user->update([
'google_id' => $googleUser->getId(),
'avatar_url' => $googleUser->getAvatar(),
'email_verified_at' => $user->email_verified_at ?? now(),
]);
Auth::login($user, true);
return redirect()->intended('/');
}
// Create new user with email already verified (Google verified it)
// The Registered event listener checks hasVerifiedEmail() before sending
$user = User::query()->create([
'name' => $googleUser->getName(),
'email' => $googleUser->getEmail(),
'google_id' => $googleUser->getId(),
'avatar_url' => $googleUser->getAvatar(),
'email_verified_at' => now(),
'role' => User::ROLE_USER,
]);
event(new Registered($user));
Auth::login($user, true);
return redirect()->intended('/');
}
}