Feat: Login with Google
This commit is contained in:
44
app/Http/Controllers/Auth/GoogleController.php
Normal file
44
app/Http/Controllers/Auth/GoogleController.php
Normal 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.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user