Files
Faculty-Documentation/app/Http/Controllers/Auth/GoogleController.php
2025-05-10 15:15:01 +05:30

45 lines
1.2 KiB
PHP

<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Str;
use App\Models\User;
class GoogleController extends Controller
{
/**
* Redirect the user to the Google authentication page.
*/
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
/**
* Obtain the user information from Google.
*/
public function handleGoogleCallback()
{
try {
$googleUser = Socialite::driver('google')->user();
$user = User::firstOrCreate(
['email' => $googleUser->getEmail()],
[
'name' => $googleUser->getName(),
'password' => bcrypt(Str::random(16)), // Generate a random password
]
);
Auth::login($user);
return redirect()->route('dashboard');
} catch (\Exception $e) {
return redirect()->route('login')->withErrors(['error' => 'Unable to login using Google. Please try again.']);
}
}
}