Files
memefast/app/Http/Controllers/SocialAuthController.php
2025-07-01 20:54:26 +08:00

94 lines
2.7 KiB
PHP

<?php
namespace App\Http\Controllers;
use App;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
class SocialAuthController extends Controller
{
public function redirectToGoogle()
{
return Socialite::driver('google')
->with(['prompt' => 'consent'])
->redirect();
}
public function handleGoogleCallback()
{
try {
if (App::environment('production')) {
$googleUser = Socialite::driver('google')->user();
} else {
$googleUser = Socialite::driver('google')->user();
// /$googleUser = $this->getMockGoogleUser();
}
// First, check if the user exists by google_id
$user = User::where('google_id', $googleUser->id)->whereNotNull('google_id')->first();
if ($user) {
$this->setupUser($user);
Auth::login($user);
} else {
// If no user found by google_id, check by email
$user = User::where('email', $googleUser->email)->first();
if ($user) {
// If the google_id is empty, update it
if (empty($user->google_id)) {
$user->google_id = $googleUser->id;
$user->save();
}
$this->setupUser($user);
Auth::login($user);
} else {
// Create a new user if neither exists
$user = User::create([
'email' => $googleUser->email,
'google_id' => $googleUser->id,
]);
$this->setupUser($user);
Auth::login($user);
$intended_route = route('home');
}
}
return redirect()->intended(route('home'));
} catch (\Exception $e) {
throw $e;
$error_message = 'Google login failed. Please try again.';
if (config('app.debug')) {
$error_message = $e->getMessage();
}
return redirect()->route('home')->with('error', $error_message);
}
}
private function setupUser($user) {}
private function getMockGoogleUser()
{
// Create a mock user object that mimics Socialite's user structure
return new class
{
public $email = 'memeaigen.com@gmail.com';
public $id = 'xxx';
// public $email = 'patrick.christener@gmail.com';
// public $id = '104771940181889934768';
};
}
}