如何将Facebook SDK登录与cakephp 2.x集成?

shx*_*fee 10 integration cakephp facebook-graph-api cakephp-2.0 facebook-php-sdk

似乎很少甚至没有关于Facebook登录与cakephp Auth组件在线集成的最新资源.我找到了以下资源:

  1. 使用cakephp 1.3的旧面包店文章?和旧版本的Facebook SDK
  2. 似乎正在开发的webtechnick的Cakephp插件

除此之外,我没有找到明确的资源.我希望集成尽可能灵活(不使用魔术插件).经过大量研究后,我终于提出了一个体面的解决方案,我今天在这里分享.因为我对蛋糕很新,请提供帮助.

shx*_*fee 30

Cakephp 2.x Auth与Facebook Auth的集成,实现无缝的用户身份验证

首先,你应该阅读梦幻般的cakePHP Auth组件,并按照cakephp book 2.x中的简单认证和授权应用程序教程进行操作(假设你也遵循了系列的前两个教程.完成之后,你应该已经设法使用用户身份验证和授权构建一个简单的cakePHP应用程序.

接下来,您应该下载facebook SDK并从Facebook 获取应用程序ID.


首先,我们将Facebook sdk复制到App/Vendors.然后我们将在AppController beforeFilter方法中导入并初始化它.

//app/Controller/AppController.php

public function beforeFilter() {
    App::import('Vendor', 'facebook-php-sdk-master/src/facebook');
    $this->Facebook = new Facebook(array(
        'appId'     =>  'App_ID_of_facebook',
        'secret'    =>  'App_Secret'

    ));

    $this->Auth->allow('index', 'view');
}
Run Code Online (Sandbox Code Playgroud)

我们正在AppController中初始化Facebook SDK,以便我们可以通过应用程序访问它.接下来,我们将使用SDK生成Facebook登录URL并将其传递给视图.我通常在beforeRender方法中执行此操作.

注意:上述配置详细信息(appId&secret)最好保存在App/Config/facebook.php中.然后你应该使用蛋糕配置.

//app/Controller/AppController.php

public function beforeRender() {
    $this->set('fb_login_url', $this->Facebook->getLoginUrl(array('redirect_uri' => Router::url(array('controller' => 'users', 'action' => 'login'), true))));
    $this->set('user', $this->Auth->user());
}
Run Code Online (Sandbox Code Playgroud)

我们将更新我们的布局,以便我们可以为所有尚未登录的用户显示此登录链接.请注意我们如何设置redirect_uri我们的应用程序用户/登录操作.这样一旦facebook验证了用户,我们也可以使用cake :: Auth登录.这有很多好处,包括这个问题的解决方案.

<!-- App/Views/Layouts/default.ctp just after <div id="content"> -->
<?php
    if($user) echo 'Welcome ' . $user['username'];
    else {
        echo $this->Html->link('Facebook Login', $fb_login_url) . ' | ';
        echo $this->Html->link('Logout', array('controller' => 'user', 'action' => 'logout'));
?>
Run Code Online (Sandbox Code Playgroud)

当用户点击登录链接时,facebook SDK将登录用户并将其重定向到我们的应用程序用户/登录.我们将更新此操作以处理此问题:

// App/Controller/UsersController.php
// Handles login attempts from both facebook SDK and local
public function login()
{
    // If it is a post request we can assume this is a local login request
    if ($this->request->isPost()){
        if ($this->Auth->login()){
            $this->redirect($this->Auth->redirectUrl());
        } else {
            $this->Session->setFlash(__('Invalid Username or password. Try again.'));
        }
    } 

    // When facebook login is used, facebook always returns $_GET['code'].
    elseif($this->request->query('code')){

        // User login successful
        $fb_user = $this->Facebook->getUser();          # Returns facebook user_id
        if ($fb_user){
            $fb_user = $this->Facebook->api('/me');     # Returns user information

            // We will varify if a local user exists first
            $local_user = $this->User->find('first', array(
                'conditions' => array('username' => $fb_user['email'])
            ));

            // If exists, we will log them in
            if ($local_user){
                $this->Auth->login($local_user['User']);            # Manual Login
                $this->redirect($this->Auth->redirectUrl());
            } 

            // Otherwise we ll add a new user (Registration)
            else {
                $data['User'] = array(
                    'username'      => $fb_user['email'],                               # Normally Unique
                    'password'      => AuthComponent::password(uniqid(md5(mt_rand()))), # Set random password
                    'role'          => 'author'
                );

                // You should change this part to include data validation
                $this->User->save($data, array('validate' => false));

                // After registration we will redirect them back here so they will be logged in
                $this->redirect(Router::url('/users/login?code=true', true));
            }
        }

        else{
            // User login failed..
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我们完成了!你可以看到,大部分繁重都是通过这个动作完成的.您最好将上面的一些代码移到UserModel中.所以这里是对正在发生的事情的总结.

首先,我们检查登录请求是否从我们的应用程序@ Users/login的登录表单发送.如果是,那么我们只需登录用户.否则我们检查用户是否存在于我们的数据库中,以及他是否登录他或创建新用户,然后登录他.

请小心在这里验证用户的电子邮件,比如他们的facebook_id.否则,用户可能会更改他们的Facebook电子邮件并劫持您的应用程序的另一个用户.

快乐的编码!