MIF_E31230266/app/Http/Controllers/GoogleAuthController.php

50 lines
1.3 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
class GoogleAuthController extends Controller
{
// Redirect ke halaman login Google
public function redirect()
{
return Socialite::driver('google')
->with(['prompt' => 'select_account'])
->redirect();
}
// Callback setelah login Google berhasil
public function callback()
{
try {
$googleUser = Socialite::driver('google')->user();
$user = User::where('email', $googleUser->getEmail())->first();
if ($user) {
// Email sudah ada, update google_id saja
$user->update(['google_id' => $googleUser->getId()]);
} else {
// Email baru, buat akun baru
$user = User::create([
'name' => $googleUser->getName(),
'email' => $googleUser->getEmail(),
'google_id' => $googleUser->getId(),
'password' => null,
]);
}
Auth::login($user);
return redirect()->route('halaman.prediksi');
} catch (\Exception $e) {
return redirect()->route('login')
->with('error', $e->getMessage());
}
}
}