Перенаправление входа в Google не работает в CodeIgniter 4: ошибка «Страница не существует» при обратном вызовеPhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Перенаправление входа в Google не работает в CodeIgniter 4: ошибка «Страница не существует» при обратном вызове

Сообщение Anonymous »

Я интегрирую вход 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»

Код: Выделить всё

[url=

Подробнее здесь: [url]https://stackoverflow.com/questions/79804323/google-login-redirect-not-working-in-codeigniter-4-page-does-not-exist-error[/url]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»