Facebook OAuth Login Using CakePHP
In this tutorial we are going to see how to implement facebook login in cakephp. In one of my previous tutorial I had implemented Facebook OAuth Login using PHP, where I had berifly explained Facebook app creation and integration. I will helpful for you to refer that tutorials before continuing this.
Here is my previous tutorials on Facebook login.
Create Facebook Application:
In Facebook login integration using CakePHP first and foremost thing we need to is to create Facebook Application to get Facebook App ID and App Secret. I had briefly explained creation of Facebook Application on Facebook OAuth 2 Login Using PHP Tutorial. So please follow the step 1 & step 2 of this tutorial to create Facebook Application. Here is the Link.
Once you completed Step 1 & step 2 of the above tutorial successfully, then you will get Facebook App ID and App Secret to integrate Facebook login in your CakePHP webapplication.
Crate Sample Table For Facebook Login Using CakePHP:
Create following sample users table in your Database for this cakephp login with google.
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(60) DEFAULT NULL, `last_name` varchar(60) DEFAULT NULL, `email` varchar(80) DEFAULT NULL, `password` varchar(64) DEFAULT NULL, `social_id` varchar(45) DEFAULT NULL, `picture` varchar(100) DEFAULT NULL, `gender` char(1) DEFAULT NULL, `created` datetime DEFAULT NULL, `updated` datetime DEFAULT NULL, `uuid` varchar(70) DEFAULT NULL, `status` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `email_idx` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Facebook Login Integration In CakePHP:
To integrate Facebook Login in your CakePHP Webapplications, we need Facebook PHP SDK to make OAuth request to Facebook. I have downloaded recent version Facebook PHP SDK from Facebook.
Note : It’s best advisable to use Facebook PHP SDK i had used in this tutorial to successfully integrate Facebook login in your CakePHP webapplication. Please download source file using above download link.
https://developers.facebook.com/docs/php/gettingstarted/4.0.0
Now I have created a folder name fb in the app/Vendor directory, then from downloaded Facebook PHP SDK copied only src directory and autoload.php file and pasted it in the app/Vendor/fb directory. Now it is app/Vendor/fb/src..
Include Facebook PHP SDK In Your CakePHP Application:
Create site_config.php file in the app/Config directory to keep all your application wide constants. Here is my site_config.php file. Where please replace your app id and app secret.
<?php require_once 'messages.php'; //db config define('DB_HOST', 'localhost'); define('DB_NAME', 'cakelogin'); define('DB_USER', 'root'); define('DB_PASS', ''); define('DB_PREFIX', ''); //site config define('BASE_PATH', 'http://localhost/cakelogin/'); //Social Logins define('FACEBOOK_APP_ID', 'YOUR APP_ID'); define('FACEBOOK_APP_SECRET', 'YOUR APP_SECRET'); define('FACEBOOK_REDIRECT_URI', 'http://localhost/cakelogin/fb_login');
Please include this site_config.php file in your bootstrap.php file in the app/Config directory.
Before we are going to make any OAuth API request to Facebook we must include that Facebook PHP SDK in our file. For that I am creating fb.php file in the app/Config directory and including following files. Here is my fb.php file.
<?php define('FACEBOOK_SDK_V4_SRC_DIR','../Vendor/fb/src/Facebook/'); require_once("../Vendor/fb/autoload.php"); use Facebook\FacebookSession; use Facebook\FacebookRedirectLoginHelper; use Facebook\FacebookRequest; use Facebook\FacebookResponse; use Facebook\FacebookSDKException; use Facebook\FacebookRequestException; use Facebook\FacebookAuthorizationException; use Facebook\GraphObject; use Facebook\GraphUser; use Facebook\GraphSessionInfo;
Note: If it throughs FacebookSession class not found error, then copy above lines and include in your UsersController.php file at the top.
OR
<?php define('FACEBOOK_SDK_V4_SRC_DIR','../Vendor/fb/src/Facebook/'); require_once("../Vendor/fb/autoload.php"); use Facebook\FacebookSession; use Facebook\FacebookRedirectLoginHelper; use Facebook\FacebookRequest; use Facebook\FacebookResponse; use Facebook\FacebookSDKException; use Facebook\FacebookRequestException; use Facebook\FacebookAuthorizationException; use Facebook\GraphObject; use Facebook\GraphUser; use Facebook\GraphSessionInfo; class UsersController extends AppController { // }
Use only either one of the method to add Facebook PHP SDK in your CakePHP webapplication.
Making Facebook Oauth API Request:
To make Facebook OAuth Login API request as well as handle Facebook OAuth response I am creating following two functions. where fblogin() function which makes Facebook OAuth login request, and fb_login() function which handles Facebook OAuth login response from the Facebook.
This following two functions I had kept it in UsersController.php file. So here is the my CakePHP scripts of the two functions.
Note : I had directly included Facebook PHP SDK files at the top of the UsersController
/** * Facebook Login */ public function fblogin() { $this->autoRender = false; if (session_status() == PHP_SESSION_NONE) { session_start(); } FacebookSession::setDefaultApplication(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET); $helper = new FacebookRedirectLoginHelper(FACEBOOK_REDIRECT_URI); $url = $helper->getLoginUrl(array('email')); $this->redirect($url); } public function fb_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.'index'); } }else{ $this->Session->setFlash(FACEBOOK_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' ); $this->redirect(BASE_PATH.'index'); } } }else{ $this->Session->setFlash(FACEBOOK_LOGIN_FAILURE, 'default', array( 'class' => 'message error'), 'error' ); $this->redirect(BASE_PATH.'index'); } } }
CakePHP Facebook Login Auth Link:
Finally we need to give Facebook Login link to user to use Facebook login. Here is my html markup.
<a class="btn btn-default facebook" href="<?php echo BASE_PATH.'fblogin'; ?>"> <i class="fa fa-facebook modal-icons"></i> Signin with Facebook </a>
CakePHP Routing for Google Login:
I had modified url string for our Facebook login to look nice. So please add the following lines of code in your routes.php file in the app/Config directory.
Router::connect('/fb_login', array('controller' => 'users', 'action' => 'fb_login')); Router::connect('/fblogin', array('controller' => 'users', 'action' => 'fblogin'));
CakePHP Auth Allow() for Google Login:
Final thing we need to allow user to access following two functions fblogin() and fb_login() without logging in our system in the beforeFilter() of UsersController.
public function beforeFilter() { $this->Auth->allow('fblogin', 'fb_login'); parent::beforeFilter(); }
You may also like some of my tutorial on CakePHP
Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts
If you want any of my script need to be customized according to your business requirement,
Please feel free to contact me [at] muni2explore[at]gmail.com
Note: But it will be charged based on your customization requirement