Feat: Login with Google

This commit is contained in:
Sallu9007
2025-05-10 15:15:01 +05:30
parent 5ad34b8794
commit 6b84de9472
7 changed files with 544 additions and 3 deletions

View File

@@ -0,0 +1,44 @@
<?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.']);
}
}
}