php CodeIgniter 4,带有防护罩和Google Oauth2

vmdwslir  于 2022-10-30  发布在  PHP
关注(0)|答案(1)|浏览(143)

因此,我只想在我的工作身份验证Web应用程序(使用Codeigniter Shield包)上添加使用google功能登录。我已经在Login控制器上创建了一个login_google函数,它扩展了Shield包中的LoginController,如下所示:

登录控制器

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\Shield\Controllers\LoginController;

class Login extends LoginController
{
    function __construct()
    {
        require_once __DIR__ . '/../../vendor/autoload.php';
        $this->userModel = new \App\Models\UserModel();
        $this->google_client = new \Google_Client();
        $this->google_client->setClientId(getenv('OAuth2.clientID'));
        $this->google_client->setClientSecret(getenv('OAuth2.clientSecret'));
        $this->google_client->setRedirectUri('http://localhost:8080/login_google');
        $this->google_client->addScope('email');
        $this->google_client->addScope('profile');           
    }
    public function loginView()
    {
        if (auth()->loggedIn()) {
            return redirect()->to(config('Auth')->loginRedirect());
        }

        /**@var Session $authenticator */
        $authenticator = auth('session')->getAuthenticator();

        // If an action has been defined, start it up.
        if ($authenticator->hasAction()) {
            return redirect()->route('auth-action-show');
        }

        $data['google_button'] = "<a href='".$this->google_client->createAuthUrl()."'><img src='https://developers.google.com/identity/images/btn_google_signin_dark_normal_web.png' /></a>";
        return view('login', $data);
    }

    public function loginAction(): RedirectResponse
    {
        // Validate here first, since some things,
        // like the password, can only be validated properly here.
        $rules = $this->getValidationRules();

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $credentials             = $this->request->getPost(setting('Auth.validFields'));
        $credentials             = array_filter($credentials);
        $credentials['password'] = $this->request->getPost('password');
        $remember                = (bool) $this->request->getPost('remember');

        /**@var Session $authenticator */
        $authenticator = auth('session')->getAuthenticator();

        // Attempt to login
        $result = $authenticator->remember($remember)->attempt($credentials);
        if (! $result->isOK()) {
            return redirect()->route('login')->withInput()->with('error', $result->reason());
        }

        /**@var Session $authenticator */
        $authenticator = auth('session')->getAuthenticator();

        // If an action has been defined for login, start it up.
        if ($authenticator->hasAction()) {
            return redirect()->route('auth-action-show')->withCookies();
        }

        return redirect()->to(config('Auth')->loginRedirect())->withCookies();
    }

    public function login_google() {
        $token = $this->google_client->fetchAccessTokenWithAuthCode($this->request->getVar('code'));
        if (!isset($token['error'])) {
            $this->google_client->setAccessToken($token['access_token']);
            $this->session->set('access_token', $token['access_token']);

            $google_service = new \Google\Service\Oauth2($this->google_client);
            $data = $google_service->userinfo->get();

            $userdata = array();
            if ($this->userModel->isAlreadyRegister($data['id'])) {
                $userdata = [
                    'first_name' => $data['givenName'],
                    'last_name' => $data['familyName'],
                    'email' => $data['email'],
                    'avatar' => $data['picture'],
                ];
                $this->userModel->updateUserData($userdata, $data['id']);
            } else {
                $userdata = [
                    'first_name' => $data['givenName'],
                    'last_name' => $data['familyName'],
                    'email' => $data['email'],
                    'avatar' => $data['picture'],
                    'oauth_id' => $data['id'],
                ];
                $this->userModel->insertUserData($userdata);
            }
            $this->session->set('LoggedUserData', $userdata);
        } else {
            $this->session->set("error", $token['error']);
            return redirect('/register');
        }

        return redirect()->to('/profile');
    }
}

用户模型如下:

用户模式

<?php

namespace App\Models;

use CodeIgniter\Model;
use CodeIgniter\Shield\Models\UserModel as ModelsUserModel;

class UserModel extends ModelsUserModel
{
    protected $allowedFields = [
        'username',
        'status',
        'status_message',
        'active',
        'last_active',
        'deleted_at',
        'gender',
        'first_name',
        'last_name',
        'avatar',
        'phone_number',
        'full_address',
        'oauth_id',
    ];

    function isAlreadyRegister($authid){
        return $this->db->table('users')->getWhere(['id'=>$authid])->getRowArray()>0?true:false;
    }
    function updateUserData($userdata, $authid){
        $this->db->table("users")->where(['id'=>$authid])->update($userdata);
    }
    function insertUserData($userdata){
        $this->db->table("users")->insert($userdata);
    }
}

但每次我点击登录与谷歌按钮,它不会工作(界面选择谷歌帐户进行身份验证是工作),总是返回登录页面
在将CodeIgniter Shield与Google Oauth结合使用时,我是否遗漏了一些东西?任何人都可以提供帮助?TIA

sqserrrh

sqserrrh1#

已为带有Shield的OAuth包创建了一个新包:https://github.com/datamweb/shield-oauth
你可以用它来代替你自己的。

相关问题