2023-05-10 00:14:28 -07:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
|
|
|
|
use Illuminate\Http\Request;
|
|
|
|
use App\Models\User;
|
|
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
use Laravel\Socialite\Facades\Socialite;
|
|
|
|
use Laravel\Socialite\Two\InvalidStateException;
|
2023-05-10 01:37:03 -07:00
|
|
|
use App\Models\Setting;
|
2023-05-10 00:14:28 -07:00
|
|
|
|
|
|
|
|
|
|
|
class GoogleAuthController extends Controller
|
|
|
|
{
|
2023-05-10 01:37:03 -07:00
|
|
|
/**
|
|
|
|
* We need this constructor so that we override the socialite expected config variables
|
|
|
|
*/
|
|
|
|
public function __construct()
|
|
|
|
{
|
|
|
|
parent::__construct();
|
|
|
|
$setting = Setting::getSettings();
|
|
|
|
config(['services.google.redirect' => config('app.url').'/google/callback']);
|
|
|
|
config(['services.google.client_id' => $setting->google_client_id]);
|
|
|
|
config(['services.google.client_secret' => $setting->google_client_secret]);
|
|
|
|
}
|
|
|
|
|
2023-05-10 00:14:28 -07:00
|
|
|
public function redirectToGoogle()
|
|
|
|
{
|
|
|
|
return Socialite::driver('google')->redirect();
|
|
|
|
}
|
|
|
|
|
|
|
|
public function handleGoogleCallback()
|
|
|
|
{
|
|
|
|
try {
|
|
|
|
$socialUser = Socialite::driver('google')->user();
|
2023-05-10 01:58:36 -07:00
|
|
|
\Log::debug('Google user found');
|
2023-05-10 00:14:28 -07:00
|
|
|
} catch (InvalidStateException $exception) {
|
2023-05-10 01:58:36 -07:00
|
|
|
\Log::debug('Google user NOT found');
|
2023-05-10 00:14:28 -07:00
|
|
|
return redirect()->route('login')
|
|
|
|
->withErrors(
|
|
|
|
[
|
2023-05-10 01:47:52 -07:00
|
|
|
'username' => [
|
2023-05-10 02:18:05 -07:00
|
|
|
trans('auth/general.google_login_failed')
|
2023-05-10 00:14:28 -07:00
|
|
|
],
|
|
|
|
]
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-05-10 01:58:36 -07:00
|
|
|
$user = User::where('username', $socialUser->getEmail())->first();
|
2023-05-10 00:14:28 -07:00
|
|
|
|
|
|
|
|
|
|
|
if ($user) {
|
2023-05-10 01:59:33 -07:00
|
|
|
|
2023-05-10 00:14:28 -07:00
|
|
|
Auth::login($user, true);
|
2023-05-10 00:54:14 -07:00
|
|
|
return redirect()->route('home');
|
2023-05-10 00:14:28 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
return redirect()->route('login')
|
|
|
|
->withErrors(
|
|
|
|
[
|
|
|
|
'email' => [
|
|
|
|
trans('admin/users/message.user_not_found'),
|
|
|
|
],
|
|
|
|
]
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|