Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Facebook login using CakePHP

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 668
    Comment on it

    To create a Facebook login using cakephp we need facebook app with appId, apiKey and secret key which are required for facebook login to work. Facebook connect and enables users to authenticate your application instantly with a Facebook Account.

    Copy facebook library "app/plugins/facebook/config/facebook.php.example" and rename to "app/config/facebook.php". Now update facebook.php file using the obtained key and secret:

    Configure::write('Facebook.key', '225779920770351'); 
    Configure::write('Facebook.secret', '97ca91bc203b39d2f598fccf58eaed15');
    

    Create UserController and use following steps for authentication:- - Include "Connect" component from Facebook Plugin and "Auth" from core files.

    var $components = array('Facebook.Connect','Auth'); 
    - Include "Facebook" helper from Facebook Plugin.
    var $helpers    = array('Facebook.Facebook');
    - We optate utilizer to be redirected to index page after prosperously authenticate and layout file for our views.
    function beforeFilter() {
             $this->Auth->loginRedirect = array('action' => 'home');   
             $this->layout='facebook';  
    }
    
    • home(){} will be the home page after users has authenticate.
    • login(){} function to make Facebook OAuth Login API request as well as handle Facebook OAuth response.

    Following are complete authentication code:-

    class UsersController extends AppController {
        var $name = 'Users';
        var $components = array('Facebook.Connect','Auth');
        var $helpers    = array('Facebook.Facebook');      
    
        function beforeFilter() {
             $this->Auth->loginRedirect = array('action' => 'home');
             $this->layout='facebook';                                 
        }
    
        function home() {                                 
    
        }
    
        function login()
        {
            $this->layout = 'ajax';
            FacebookSession::setDefaultApplication(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET);
            $helper = new FacebookRedirectLoginHelper(FACEBOOK_REDIRECT_URI);
            $session = $helper->getSessionFromRedirect();
    
            if(isset($_SESSION['token'])){
                $session = new FacebookSession($_SESSION['token']);
                try{
                    $session->validate(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET);
                }catch(FacebookAuthorizationException $e){
                    echo $e->getMessage();
                }
            }
    
            $data = array();
            $fb_data = array();
    
            if(isset($session)){
                $_SESSION['token'] = $session->getToken();
                $request = new FacebookRequest($session, 'GET', '/me');
                $response = $request->execute();
                $graph = $response->getGraphObject(GraphUser::className());
    
                $fb_data = $graph->asArray();
                $id = $graph->getId();
                $image = "https://graph.facebook.com/".$id."/picture?width=100";
    
                if( !empty( $fb_data )){
                    $result = $this->User->findByEmail( $fb_data['email'] );
                    if(!empty( $result )){
                        if($this->Auth->login($result['User'])){
                            $this->Session->setFlash(FACEBOOK_LOGIN_SUCCESS, 'default', array( 'class' => 'message success'), 'success' );
                            $this->redirect(BASE_PATH);
                        }else{
                            $this->Session->setFlash(FACEBOOK_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' );
                            $this->redirect(BASE_PATH.'login');
                        }
    
                    }else{
                        $data['email'] = $fb_data['email'];
                        $data['first_name'] = $fb_data['first_name'];
                        $data['social_id'] = $fb_data['id'];
                        $data['picture'] = $image;
                        $data['uuid'] = String::uuid ();
                        $this->User->save( $data );
                        if($this->User->save( $data )){
                            $data['id'] = $this->User->getLastInsertID();
                            if($this->Auth->login($data)){
                                $this->Session->setFlash(FACEBOOK_LOGIN_SUCCESS, 'default', array( 'class' => 'message success'), 'success' );
                                $this->redirect(BASE_PATH);
                            }else{
                                $this->Session->setFlash(FACEBOOK_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' );
                                $this->redirect(BASE_PATH.'home');
                            }
    
                        }else{
                            $this->Session->setFlash(FACEBOOK_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' );
                            $this->redirect(BASE_PATH.'home');
                        }
                    }
    
                }else{
                    $this->Session->setFlash(FACEBOOK_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' );
                    $this->redirect(BASE_PATH.'home');
                }
    
    
            }
        }
    
        function logout() {                               
            $this->Session->destroy();
            $this->redirect($this->Auth->logout());
        }
    }
    
    

    View file for facebook login button:

    echo $this->Html->image("login-facebook.png", array(
        "alt" => "Signin with Facebook",
        'url' => array('action'=>'login', 'Facebook')
    ));
    
    

    Thats all there, we will be able to authenticate to a CakePHP App utilizing gregarious authenticate.

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: