Cakephp

Single click login into LinkedIn use api with in PHP / CakePHP

Single click login into LinkedIn use api with in PHP / CakePHP


Single click login into LinkedIn use api with in PHP / CakePHP

LinkedIn Login API

We are going to login to our Cakephp 2 website (which does not use composer) with a LinkedIn api. We are going to update our Social user's table and our normal users table. Basically if a user exist we are going to update other wise add the user.

Our first table is:

CREATE TABLE IF NOT EXISTS `user_socials` (
  `id` int(11) NOT NULL,
  `oauth_provider` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `oauth_uid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Our users table is:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL,
  `user_role_id` int(1) NOT NULL,
  `firstname` varchar(100) NOT NULL,
  `lastname` varchar(100) NOT NULL,
  `google_id` varchar(255) DEFAULT NULL,
  `facebook_id` varchar(255) DEFAULT NULL,
  `linkedin_id` varchar(255) DEFAULT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `created` date NOT NULL,
  `modified` date NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=1334 DEFAULT CHARSET=latin1;

we have optained the linkedin api files at https://github.com/Skillbooker/linkedin_oauth

The linkedin function

This linkedin function has to go in your controller.

public function linkedin() {

define("SITEURL", "http://www.skillbooker.com/");    
define("LINKEDIN_KEY", "0000000000000000");
//your linkedin key
define("LINKEDIN_SECRET", "000000000000000");
//your linkedin secret key
define("LINKEDIN_REROUTE", "social/linkedin");

$callbackURL = SITEURL.LINKEDIN_REROUTE;
$linkedinApiKey = LINKEDIN_KEY;
$linkedinApiSecret = LINKEDIN_SECRET;
$linkedinScope = ;

require_once(APP . 'Vendor' . DS . 'linkedin' . DS . 'http.php');
require_once(APP . 'Vendor' . DS . 'linkedin' . DS .  'oauth_client.php');   

if (isset($_GET["oauth_problem"]) && $_GET["oauth_problem"] <> "") {
  // in case if user cancel the login. redirect back to home page.

  $this->Session->setFlash($_GET["oauth_problem"],'error');
  $this->redirect(array('plugin'=>false, 'controller'=>'social', 'action' => 'linkedin'));
}

$client = new oauth_client_class;

$client->debug = false;
$client->debug_http = true;
$client->redirect_uri = $callbackURL;

$client->client_id = $linkedinApiKey;
$application_line = __LINE__;
$client->client_secret = $linkedinApiSecret;

if (strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
  die('Please go to LinkedIn Apps page https://www.linkedin.com/secure/developer?newapp= , '.
			'create an application, and in the line '.$application_line.
			' set the client_id to Consumer key and client_secret with Consumer secret. '.
			'The Callback URL must be '.$client->redirect_uri).' Make sure you enable the '.
			'necessary permissions to execute the API calls your application needs.';

/* API permissions
 */
$client->scope = 'r_basicprofile r_emailaddress';
if (($success = $client->Initialize())) {
  if (($success = $client->Process())) {
    if (strlen($client->authorization_error)) {
      $client->error = $client->authorization_error;
      $success = false;
    } elseif (strlen($client->access_token)) {
      $success = $client->CallAPI(
					'http://api.linkedin.com/v1/people/~:(id,email-address,first-name,last-name,location,picture-url,public-profile-url,formatted-name)', 
					'GET', array(
						'format'=>'json'
					), array('FailOnAccessError'=>true), $userProfile);
    }
  }
  $success = $client->Finalize($success);
}
if ($client->exit) exit;
if ($success) { 
			           
		$social['oauth_provider'] = 'linkedin'; 
		$social['oauth_uid'] = $userProfile->id;        
        $social['picture']  = $userProfile->pictureUrl;
		$social['link']  = $userProfile->publicProfileUrl;
				
		$user['last_name'] = $userProfile->lastName;
		$user['first_name'] = $userProfile->firstName;
		$user['email']  = $userProfile->emailAddress;

		$email  = $userProfile->emailAddress;

        $this->socialcheck($social, $user, $email);		 
		 
} else {
   $this->Session->setFlash($client->error,'error');
}

$this->redirect(array('plugin'=>false, 'controller'=>'social', 'action' => 'linkedin'));

}

now the function that updates our social users tables and users tables

this function will be used for our facebook, google, linkedin, twitter and all other one click social login systems

function socialcheck($social, $user, $email) {
	
	$this->loadModel('UserSocial');
	$options = array('conditions' => array('UserSocial.oauth_uid' => $social['oauth_uid']));
	$findsocialuser = $this->UserSocial->find('first',$options);
	
	if(!empty($findsocialuser)){
	
		$userdata['id']	=	$findsocialuser['UserSocial']['id'];
		$userdata['modified']	=	date("Y-m-d H:i:s");
		
		$this->UserSocial->save($userdata,false);
		$social_id = $findsocialuser['UserSocial']['id'];
	
	} else {
		
		$userdata = $social;	
		$userdata['created']	=	date("Y-m-d H:i:s");
		$userdata['modified']	=	date("Y-m-d H:i:s");
		
		$this->UserSocial->save($userdata,false);      

	}
    
		$this->loadModel('User');
		
		$options = array('conditions' => array('User.email' => $email));
		$finduser = $this->User->find('first',$options);
		
		if($social['oauth_provider'] == 'google') { $data['google_id'] = $social['oauth_uid']; }
		if($social['oauth_provider'] == 'facebook') { $data['facebook_id'] = $social['oauth_uid']; }
		if($social['oauth_provider'] == 'linkedin') { $data['linkedin_id'] = $social['oauth_uid']; }
    
	if(!empty($finduser)){
		
		$data['id']	=	$finduser['User']['id'];
		$data['modified']	=	date("Y-m-d H:i:s");
	
		$this->User->save($data,false);
		
	} else {
			
		$data  = $user;
		// setting data to the user data that will contain the first names email addresses ect
		
		$data['password']	=	AuthComponent::password($user['firstname']);
		// creating a password for the user in our database -->this can be emailed to the user
	
		$this->User->save($data, false);
	
	}
}

 

Published: 11th May 2017 by

Adverts