Я интегрирую вход Google OAuth в свой проект CodeIgniter, но столкнулся с проблемой с URI перенаправления после успешной аутентификации в Google. Вот краткое описание проблемы: Мой контроллер
namespace App\Controllers\Home;
use App\Controllers\BaseController;
use App\Models\Front\UserModel;
use App\Models\Front\HomeModel;
use Google_Client;
use Google\Service\Oauth2;
class Login extends BaseController
{
public function googleLogin()
{
$client = new Google_Client();
$client->setClientId('id');
$client->setClientSecret('secrete key');
// Set redirect URI dynamically using the base URL
$redirectUri = $this->baseURL . 'home/googleCallback';
$client->setRedirectUri($redirectUri);
// Add required scopes for Google login
$client->addScope('email');
$client->addScope('profile');
// Redirect user to Google's OAuth consent screen
return redirect()->to($client->createAuthUrl());
}
public function googleCallback()
{
$client = new Google_Client();
$client->setClientId('id');
$client->setClientSecret('secrete key');
// Set redirect URI dynamically using the base URL
$redirectUri = $this->baseURL . 'home/googleCallback';
$client->setRedirectUri($redirectUri);
if ($this->request->getVar('code')) {
try {
// Fetch the OAuth 2.0 token using the authorization code
$token = $client->fetchAccessTokenWithAuthCode($this->request->getVar('code'));
if (isset($token['error'])) {
throw new Exception('Google Authentication Error: ' . $token['error']);
}
$client->setAccessToken($token);
// Fetch user profile info from Google
$googleService = new Oauth2($client);
$googleUser = $googleService->userinfo->get();
// Handle user data (login or registration)
$userModel = new \App\Models\Front\UserModel();
$existingUser = $userModel->where('email', $googleUser->email)->first();
if (!$existingUser) {
// New user registration
$newUser = [
'google_id' => $googleUser->id,
'name' => $googleUser->name,
'email' => $googleUser->email,
'created_at' => date('Y-m-d H:i:s'),
];
$userModel->insert($newUser);
$user = $userModel->where('email', $googleUser->email)->first();
} else {
// Existing user login
$user = $existingUser;
}
// Set session data for logged-in user
session()->set([
'isLoggedIn' => true,
'userID' => $user['id'],
'userEmail' => $user['email'],
'userName' => $user['name'],
'createdAt' => $user['created_at'],
]);
// Redirect to the user admin page
return redirect()->to('/home/useradmin');
} catch (Exception $e) {
// Handle authentication errors
return redirect()->to('/home/login')->with('error', 'Google authentication failed: ' . $e->getMessage());
}
} else {
// If no code is returned, handle the error
return redirect()->to('/home/login')->with('error', 'Google authentication failed.');
}
}
}
Я интегрирую вход Google OAuth в свой проект CodeIgniter, но столкнулся с проблемой с URI перенаправления после успешной аутентификации в Google. Вот краткое описание проблемы: [b]Мой контроллер[/b] [code]namespace App\Controllers\Home;
use App\Controllers\BaseController; use App\Models\Front\UserModel; use App\Models\Front\HomeModel; use Google_Client; use Google\Service\Oauth2;
class Login extends BaseController { public function googleLogin() { $client = new Google_Client(); $client->setClientId('id'); $client->setClientSecret('secrete key');
// Set redirect URI dynamically using the base URL $redirectUri = $this->baseURL . 'home/googleCallback'; $client->setRedirectUri($redirectUri);
// Add required scopes for Google login $client->addScope('email'); $client->addScope('profile');
// Redirect user to Google's OAuth consent screen return redirect()->to($client->createAuthUrl()); }
public function googleCallback() {
$client = new Google_Client(); $client->setClientId('id'); $client->setClientSecret('secrete key');
// Set redirect URI dynamically using the base URL $redirectUri = $this->baseURL . 'home/googleCallback'; $client->setRedirectUri($redirectUri);
if ($this->request->getVar('code')) { try { // Fetch the OAuth 2.0 token using the authorization code $token = $client->fetchAccessTokenWithAuthCode($this->request->getVar('code')); if (isset($token['error'])) { throw new Exception('Google Authentication Error: ' . $token['error']); } $client->setAccessToken($token);
// Fetch user profile info from Google $googleService = new Oauth2($client); $googleUser = $googleService->userinfo->get();
// Handle user data (login or registration) $userModel = new \App\Models\Front\UserModel(); $existingUser = $userModel->where('email', $googleUser->email)->first();
if (!$existingUser) { // New user registration $newUser = [ 'google_id' => $googleUser->id, 'name' => $googleUser->name, 'email' => $googleUser->email, 'created_at' => date('Y-m-d H:i:s'), ]; $userModel->insert($newUser); $user = $userModel->where('email', $googleUser->email)->first(); } else { // Existing user login $user = $existingUser; }
// Set session data for logged-in user session()->set([ 'isLoggedIn' => true, 'userID' => $user['id'], 'userEmail' => $user['email'], 'userName' => $user['name'], 'createdAt' => $user['created_at'], ]);
// Redirect to the user admin page return redirect()->to('/home/useradmin'); } catch (Exception $e) { // Handle authentication errors return redirect()->to('/home/login')->with('error', 'Google authentication failed: ' . $e->getMessage()); } } else { // If no code is returned, handle the error return redirect()->to('/home/login')->with('error', 'Google authentication failed.'); }
} }
[/code] если я нажму ссылку «Войти с помощью Google» [code][url=