如何在CakePHP 3.x中使用hybridauth插件? [英] How to use hybridauth plugin with CakePHP 3.x?

查看:80
本文介绍了如何在CakePHP 3.x中使用hybridauth插件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 CakePHP 3.x 创建可以进行社交登录的页面.我发现HybridAuth插件可以做到这一点.但是,我不了解配置和流程.谁习惯使用此插件?

I use CakePHP 3.x to create a page can make a social sign in. I found HybridAuth plugin can do that. But, I can't understand about configuration and flow. Who is used to on this plugin?

请帮助我.

推荐答案

首先,我必须感谢我的朋友帮助我解决了cakephp 3中的这个难题.

First of all, I must thank my friend for helping me solve this mystery in cakephp 3.

我提供了如何在cakephp 3中使用插件的完整选项,可能会为您提供解决方案并探索该插件的更多改进.

I'm providing the complete options how to use the plugin in cakephp 3 may this give a solution and explore more improvements in that plugin.

第1步: 在作曲家中运行

php composer.phar require hybridauth/hybridauth:~2.5.0

这必须在以下路径中安装插件

This must install plugin in the following path,

/your-app-folder/vendor/hybridauth/..

步骤2:初始化插件.

A.修改以下文件夹中的config.php文件,

A. Modify the config.php file in the following folder,

/your-app-folder/vendor/hybridauth/hybridauth/hybridauth/config.php

添加到所需方法中,例如添加应用程序ID和密码ID等.

to the required method, like add the app id and secret id, etc.

$config = array(
            "base_url" => "http://localhost/your-app-folder/users/social_redirect/",//You have to change the above according to yours

            "providers" => array(
                // openid providers
                "OpenID" => array(
                    "enabled" => true
                ),
                "Yahoo" => array(
                    "enabled" => true,
                    "keys" => array("key" => "", "secret" => ""),
                ),
                "AOL" => array(
                    "enabled" => true
                ),
                "Google" => array(
                    "enabled" => true,
                    "keys" => array("id" => "", "secret" => ""),
                ),
                "Facebook" => array(
                    "enabled" => true,
                    "keys" => array("id" => "", "secret" => ""),
                    "scope" => "email, user_about_me, user_birthday, user_hometown",
                    "trustForwarded" => false
                ),
                "Twitter" => array(
                    "enabled" => true,
                    "keys" => array("key" => "", "secret" => "")
                ),
                // windows live
                "Live" => array(
                    "enabled" => true,
                    "keys" => array("id" => "", "secret" => "")
                ),
                "LinkedIn" => array(
                    "enabled" => true,
                    "keys" => array("key" => "", "secret" => "")
                ),
                "Foursquare" => array(
                    "enabled" => true,
                    "keys" => array("id" => "", "secret" => "")
                ),
            ),
            // If you want to enable logging, set 'debug_mode' to true.
            // You can also set it to
            // - "error" To log only error messages. Useful in production
            // - "info" To log info and error messages (ignore debug messages)
            "debug_mode" => false,
            // Path to file writable by the web server. Required if 'debug_mode' is not false
            "debug_file" => "",
);

第3步: 现在在您的用户控制器中,(我已将用户控制器用于 http://localhost/your-app-folder/users/social -满足我的需求

Step 3: Now in yours users controller, (I have used users controller for http://localhost/your-app-folder/users/social - for my needs)

现在您的控制器应如下所示,

Now your controller should look like this,

<?php 

namespace App\Controller;

use App\Controller\AppController;

class UsersController extends AppController {

    public function beforeFilter(\Cake\Event\Event $event) {
      parent::beforeFilter($event);
      $this->Auth->allow(['register','social', 'social_redirect']);
    }

    public function index() {
        return $this->redirect(['controller' => 'Users', 'action' =>  'add']);
    }

    public function social($provider) {

    /* Include the Config File */
    require_once(ROOT . DS . 'vendor' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'config.php');
    require_once(ROOT . DS . 'vendor' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'Hybrid' . DS . 'Auth.php');

    /* Initiate Hybrid_Auth Function*/
    $hybridauth = new \Hybrid_Auth($config);
    $authProvider = $hybridauth->authenticate($provider);
    $user_profile = $authProvider->getUserProfile();

    /*Modify here as per you needs. This is for demo */
    if ($user_profile && isset($user_profile->identifier)) {
        echo "<b>Name</b> :" . $user_profile->displayName . "<br>";
        echo "<b>Profile URL</b> :" . $user_profile->profileURL . "<br>";
        echo "<b>Image</b> :" . $user_profile->photoURL . "<br> ";
        echo "<img src='" . $user_profile->photoURL . "'/><br>";
        echo "<b>Email</b> :" . $user_profile->email . "<br>";
        echo "<br> <a href='logout.php'>Logout</a>";
    }
    exit;

   /*Example Demo For FB authorize Action*/
   #Facebook authorize
    if ($this->request->params['pass'][0] == 'Facebook') {
        if ($user_profile && isset($user_profile->identifier)) {
            $this->authorize_facebook($user_profile);
        }
    } 
}

public function social_redirect() {
    $this->layout = false;
    $this->autoRender = false;
    require_once(ROOT . DS . 'vendor' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'config.php');
    require_once(ROOT . DS . 'vendor' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'Hybrid' . DS . 'Auth.php');
    require_once(ROOT . DS . 'vendor' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'hybridauth' . DS . 'Hybrid' . DS . 'Endpoint.php');
    $hybridauth = new \Hybrid_Auth($config);
    \Hybrid_Endpoint::process();
}


public function authorize_facebook($user_profile) {

        $provider = "Facebook";
        $provider_uid = $user_profile->identifier;

        $userExist = $this->Users->find('all')->where(['Users.provider' => $provider, 'Users.provider_uid' => $user_profile->identifier])->first();


        if ((isset($userExist)) && ($userExist)) {

            $session = $this->request->session();
            $session->delete('auth_sess_var');
            $session->destroy();
            $this->Auth->setUser($userExist->toArray());
            $session->write('auth_sess_var', $userExist);
            return $this->redirect($this->Auth->redirectUrl());
        } else {

            /* Create new user entity */
            $user = $this->Users->newEntity();
            $tmp_hash = md5(rand(0, 1000));
            $tmp_id = time();

            /* Save individual data */
            $user->tmp_id = $tmp_id;
            $user->firstname = (!empty($user_profile->firstName)) ? $user_profile->firstName : "";
            $user->lastname = (!empty($user_profile->lastName)) ? $user_profile->lastName : "";
            $user->username = (!empty($user_profile->lastName) && !empty($user_profile->lastName)) ? strtolower($user_profile->firstName) . "." . strtolower($user_profile->lastName) : "";
            $user->avatar = (!empty($user_profile->photoURL)) ? $user_profile->photoURL : "";
            $user->role = "public";
            $user->provider = $provider;
            $user->provider_uid = $user_profile->identifier;
            $user->gender = !empty($user_profile->gender) ? (($user_profile->gender == 'male') ? 'm' : 'f' ) : "";
            $user->provider_email = !empty($user_profile->email) ? $user_profile->email : "";
            $user->password = $user_profile->identifier;
            $user->confirm_password = $user_profile->identifier;
            $user->tmp_hash = $tmp_hash;
            $user->isverified = (!empty($user_profile->emailVerified)) ? 1 : 0;
            $user = $this->Users->patchEntity($user, $this->request->data);
            $this->Users->save($user);

            $userDetails = $this->Users->find('all')->where(['Users.provider' => $provider, 'Users.provider_uid' => $user_profile->identifier])->first();

            /* Destroy previous session before setting new Session */
            $session = $this->request->session();
            $session->delete('auth_sess_var');
            $session->destroy();

            /* Set user */
            $this->Auth->setUser($userDetails->toArray());
            $session->write('auth_sess_var', $userDetails);
            return $this->redirect($this->Auth->redirectUrl());
        }
    }

}

注意:根据需要修改事物并根据需要设计表.

Note: Modify The Things according to your needs and design the table as per you requirement.

第4步

呼叫混合身份验证:

For Ex: <a href="/users/social/Facebook">Facebook<a>

用于Facebook登录;

for facebook login;

尤里卡.它将像魅力一样工作.

Eureka. It will works like a charm.

有关更多信息,请点击此处.

示例登录操作(默认身份验证控制)

Example Login Action (Default Auth Control)

在App Controller中,

In App Controller,

public function initialize() {
        parent::initialize();
        $this->loadComponent('Flash');

        /* Authentication */
        $this->loadComponent('Auth', [
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginRedirect' => [
                'controller' => 'controller',
                'action' => 'action'
            ],
            'logoutRedirect' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ]
        ]);

    }

这篇关于如何在CakePHP 3.x中使用hybridauth插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆