admad/cakephp-hybridauth

CakePHP 插件,用于使用 HybridAuth 社交登录库

安装次数: 58,929

依赖项: 1

建议者: 0

安全: 0

星标: 79

关注者: 17

分支: 39

开放问题: 5

类型:cakephp-plugin

4.2.0 2018-07-11 14:16 UTC

This package is auto-updated.

Last update: 2024-09-13 10:41:15 UTC


README

CakePHP HybridAuth 插件

Total Downloads License

一个允许使用 HybridAuth 社交登录库的 CakePHP 插件。

要求

  • CakePHP 3.1+。

安装

运行

composer require --prefer-dist admad/cakephp-hybridauth

设置

在终端运行以下命令以加载插件:

bin/cake plugin load ADmad/HybridAuth -b -r

或手动将以下行添加到您的应用程序的 config/bootstrap.php

Plugin::load('ADmad/HybridAuth', ['bootstrap' => true, 'routes' => true]);

配置

创建一个配置文件 config/hybridauth.php

use Cake\Core\Configure;

return [
    'HybridAuth' => [
        'providers' => [
            'Google' => [
                'enabled' => true,
                'keys' => [
                    'id' => '<google-client-id>',
                    'secret' => '<secret-key>'
                ]
            ],
            'Facebook' => [
                'enabled' => true,
                'keys' => [
                    'id' => '<facebook-application-id>',
                    'secret' => '<secret-key>'
                ],
                'scope' => 'email, user_about_me, user_birthday, user_hometown'
            ],
            'Twitter' => [
                'enabled' => true,
                'keys' => [
                    'key' => '<twitter-key>',
                    'secret' => '<twitter-secret>'
                ],
                'includeEmail' => true // Only if your app is whitelisted by Twitter Support
            ]
        ],
        'debug_mode' => Configure::read('debug'),
        'debug_file' => LOGS . 'hybridauth.log',
    ]
];

有关 HybridAuth 配置数组的更多信息,请参阅 http://hybridauth.github.io/hybridauth/userguide/Configuration.html

数据库

插件期望您有一个包含至少 email 字段的用户表和一个 social_profiles 表。您可以使用以下命令生成 social_profiles 表:

bin/cake migrations migrate -p ADmad/HybridAuth

使用插件提供的迁移文件。

用法

请参阅 CakePHP 手册了解如何配置和使用具有所需认证处理器的 AuthComponent。您可以在 AppControllerinitialize() 方法中看到类似以下内容:

$this->loadComponent('Auth', [
    'authenticate' => [
        'Form',
        'ADmad/HybridAuth.HybridAuth' => [
            // All keys shown below are defaults
            'fields' => [
                'provider' => 'provider',
                'openid_identifier' => 'openid_identifier',
                'email' => 'email'
            ],

            'profileModel' => 'ADmad/HybridAuth.SocialProfiles',
            'profileModelFkField' => 'user_id',

            'userModel' => 'Users',

            // The URL Hybridauth lib should redirect to after authentication.
            // If no value is specified you are redirect to this plugin's
            // HybridAuthController::authenticated() which handles persisting
            // user info to AuthComponent and redirection.
            'hauth_return_to' => null
        ]
    ]
]);

注意:在指定 AuthComponent 的 loginRedirectloginAction URL 时,请确保将 'plugin' => false(或适当的插件名称)添加到 URL 数组中。

您的控制器登录操作应类似于以下内容

public function login() {
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('Invalid username or password, try again'));
    }
}

注意:当您的操作调用 $this->Auth->identify() 时,该方法可能不会返回。认证器可能需要重定向到提供者站点以完成身份验证过程。重要的是不要实现任何依赖于 identify() 方法返回值的重要业务逻辑。

在您的登录页面上,您可以创建链接以使用所需的提供者启动身份验证。使用名为 provider 的变量在查询字符串中指定提供者名称。

echo $this->Form->postLink(
    'Login with Google',
    ['controller' => 'Users', 'action' => 'login', '?' => ['provider' => 'Google']]
);

我们在这里使用 POST 链接而不是正常链接,以防止搜索引擎爬虫和其他爬虫跟踪链接。(给链接添加 "nofollow" 属性不足以解决问题,因为爬虫通常忽略它。)

一旦用户通过提供者进行身份验证,认证器就会从身份提供者获取用户配置文件,并使用该配置文件尝试在您的应用程序的用户表中找到相应的用户记录。如果没有找到用户,则触发 HybridAuth.newUser 事件。您必须设置一个监听器来处理此事件,该监听器将保存新的用户记录到您的用户表中,并返回新的用户实体。以下是如何将 UsersTable 的方法设置为事件回调的示例:

如果您还想监控所有登录 - 例如执行登录计数器 - 您可以监听 HybridAuth.login 事件。

public function initialize(array $config)
{
    $this->hasMany('ADmad/HybridAuth.SocialProfiles');

    \Cake\Event\EventManager::instance()->on('HybridAuth.newUser', [$this, 'createUser']);
    \Cake\Event\EventManager::instance()->on('HybridAuth.login', [$this, 'updateUser']);
}

public function createUser(\Cake\Event\Event $event) 
{
    // Entity representing record in social_profiles table
    $profile = $event->data()['profile'];

    // Make sure here that all the required fields are actually present

    $user = $this->newEntity(['email' => $profile->email]);
    $user = $this->save($user);

    if (!$user) {
        throw new \RuntimeException('Unable to save new user');
    }

    return $user;
}

public function updateUser(\Cake\Event\Event $event, array $user) 
{
    $this->updateAll(['logins = logins + 1', 'last_login' => new FrozenTime()], ['id' => $user['id']]);
}

此外,您还可以使用 HybridAuth.login 事件获取登录回闪消息

// In your AppController
    public function initialize()
    {
        EventManager::instance()->on('HybridAuth.login', [$this->MyComponent, 'updateUser']);
    }

// In your MyComponent
    public $components = [
        'Flash'
    ];

    public function updateUser(Event $event, array $user)
    {
        $this->Flash->success(__('You are now logged in'));
    }

Twitter 和电子邮件地址

如果您试图实现“使用 Twitter 登录”功能,并且您需要用户的 电子邮件地址,您需要使用此表单通过 Twitter 支持将您的应用程序 白名单,并选择“我需要访问特殊权限”。然后您可以使用 'includeEmail' => true 配置选项。

版权

版权 2016 ADmad

许可证

请参阅 LICENSE