ECOMMERCE/app/Http/Controllers/Auth/GoogleController.php

83 lines
2.3 KiB
PHP

<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Customer;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Laravel\Socialite\Facades\Socialite;
use App\Repositories\Member\Auth\MemberAuthRepository;
class GoogleController extends Controller
{
protected $memberAuthRepository;
public function __construct(MemberAuthRepository $memberAuthRepository)
{
$this->memberAuthRepository = $memberAuthRepository;
}
/**
* Redirect the user to the Google authentication page.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
/**
* Obtain the user information from Google.
*
* @return \Illuminate\Http\RedirectResponse
*/
public function handleGoogleCallback()
{
try{
$googleUser = Socialite::driver('google')->stateless()->user();
// Log::info($googleUser);
$email = $googleUser->email;
$name = $googleUser->name;
$google_id = $googleUser->id;
$avatar = $googleUser->avatar;
// $user = User::updateOrCreate(
// ['email' => $googleUser->email],
// [
// 'name' => $googleUser->name,
// 'google_id' => $googleUser->id,
// 'avatar' => $googleUser->avatar,
// ]
// );
$user = $this->memberAuthRepository->check(['email' => $email]);
if (!$user) {
// auto register
$customer = $this->memberAuthRepository->register([
'email' => $email,
'name' => $name,
]);
$user = $customer->user;
}
Auth::login($user, true);
return redirect()->route('home')->with('info', __('signin.google_coming_soon'));
} catch (\Exception $e) {
Log::error('Google callback failed: '.$e->getMessage());
Log::info($e);
return redirect()->route('login')->with('error', __('signin.google_failed'));
}
}
}