Facebook CodeIgniter - can't log in on first attempt - php

I'm using the Facebook PHP integration with CodeIgniter.
I have a problem where I click on the login link, it brings me to the Facebook login, I log in successfully, and when it redirects back to my page, none of the Facebook information has come through. Then if I click the login link again, it immediately logs me in without the need for the Facebook login form. If I were to refresh the page instead of clicking the login link the second time, the Facebook information still wouldn't show.
I feel that it's something to do with the session.
$facebook = $this->facebook;
$user = $facebook->getUser();
$user is always 0 until I click the login link for the second time.
This is the login flow:
I feel as if it's failing at the GET /oath/authorize phase.
public function fb_login() {
$facebook = $this->facebook;
// Get User ID
$user = $facebook->getUser();
$this->session->set_userdata(array('user' => $user));
var_dump($user);
$profile = null;
$logoutUrl = null;
$loginUrl = null;
try {
$profile = $facebook->api('/me');
$this->session->set_userdata(array('profile' => $profile));
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
if ($user) {
$url = $this->uri->uri_string();
$url = str_replace('/', '-', $url);
$logoutUrl = $facebook->getLogoutUrl(array(
'next' => site_url('[omitted]/fb_logout'.'/'.$url)));
$this->session->set_userdata(array('logoutUrl' => $logoutUrl));
} else {
$loginUrl = $facebook->getLoginUrl(array('display' => 'touch'));
$this->session->set_userdata(array('loginUrl' => $loginUrl));
}
$facebook_array = array(
'user' => $user,
'profile' => $profile,
'logoutUrl' => $logoutUrl,
'loginUrl' => $loginUrl
);
return $facebook_array;
}
public function view_events($organiser_type) {
$this->load->helper('form');
$organiser_type = urldecode($organiser_type);
$data['organiser_type'] = $organiser_type;
$data['title'] = $organiser_type.' Events';
$data['events'] = $this->trinity_impulse_model->get_events_by_type(
$organiser_type,
array('event_start_date', 'event_start_time'),
array('asc', 'asc'));
$i = 0;
foreach ($data['events'] as $event) {
$data['events'][$i]['event_start_date'] = format_timestamp_to('dateFromDB', $event['event_start_date']);
$data['events'][$i]['event_end_date'] = format_timestamp_to('dateFromDB', $event['event_end_date']);
$data['events'][$i]['event_start_date'] = humanise_date($data['events'][$i]['event_start_date']);
$data['events'][$i]['event_end_date'] = humanise_date($data['events'][$i]['event_end_date']);
$data['events'][$i]['event_start_time'] = format_timestamp_to('shorttime', $event['event_start_time']);
$data['events'][$i++]['event_end_time'] = format_timestamp_to('shorttime', $event['event_end_time']);
}
$facebook_array = $this->fb_login();
var_dump($this->session->userdata('user'));
// Get session values.
/*$data['user'] = $this->session->userdata('user');
$data['profile'] = $this->session->userdata('profile');
$data['loginUrl'] = $this->session->userdata('loginUrl');
$data['logoutUrl'] = $this->session->userdata('logoutUrl');
*/
$data['user'] = $facebook_array['user'];
$data['profile'] = $facebook_array['profile'];
$data['loginUrl'] = $facebook_array['loginUrl'];
$data['logoutUrl'] = $facebook_array['logoutUrl'];
$this->load->view('[omitted]/view_events', $data);
}
EDIT: The other pages in my application work as normal. The login displays Facebook data on first attempt. There is nothing different in the other pages. They all use the fb_login() function in the same manner.
EDIT2: I did var_dump($facebook) to see what was different about the variable on the failed login. I found that the state is set when I encounter the problem. If it is not set, it logs in with no problem. I still don't know how to resolve that though. Here is the var_dump():
["state":protected]=> string(32) "ac816d6fa8fba908b6bd01f3e7f0ec75"

I have resolved this.
I don't know what the cause of the problem was, but I modified the code and now it works. The offending piece of code was:
try {
$profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
I wrapped an if around it so that it was only called if the $user variable was instantiated. Code is like so:
if ($user) {
try {
$profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}

Related

Magento API : How to load customer session by ID

I'm working on magento module to log in customer with API.
I can log in customer and get frontend sessionId,
but when I want to load session with this sessionId to check if the customer is already logged in I can't.
Here the API function I used:
public function login($email,$password,$storecode){
$result = array();
$result['code'] = '';
$result['messages'] = '';
try{
$session = Mage::getSingleton('customers/session');
$storemodel = Mage::getModel('core/store')->load($storecode);
$store_id = $storemodel->getId();
$websiteId = $storemodel->getWebsiteId();
if($session->loginByApi($email, $password,$websiteId)){
$result['code'] = 'SUCCESS';
$result['sessionId'] = $session->getSessionId();
$customer = $session->getCustomer();
$result['customer']= array(
'customerid' => $customer->getId(),
'firstname' => $customer->getFirstname(),
'lastname' => $customer->getLastname(),
);
}
} catch (Mage_Core_Exception $e) {
$result['code'] = 'ERRORS';
$result['messages'] = $e->getMessage();
}
return $result;
}
public function isloggedin($customerId,$customersessionId ,$storecode){
if(!isset($storecode)){
$storecode = 'default';
}
Mage::app($storecode, 'store');
$core_session = Mage::getSingleton('core/session', array('name'=>'frontend'));
if($customersessionId != null){
$core_session->setSessionId($customersessionId);
$core_session->start('frontend');
}
$session = Mage::getSingleton('customer/session', array('name'=>'frontend'));
$customer = Mage::getModel('customer/customer')->load($customerId);
$session->setCustomer($customer);
if($session->isLoggedIn()){
$session->setCustomerAsLoggedIn($customer);
$result['sessionId'] = $session->getSessionId();
}else{
$result['logged'] = false;
}
return $result;
}
Anyone have an idea?
Not sure if this helps too much, but this code:
Mage::app('2', 'store');
$s = Mage::getSingleton('customer/session', array('name'=>'frontend'));
$c = Mage::getModel('customer/customer')->load(1);
$s->setCustomer($c);
if($s->isLoggedIn()){
echo $c->getName()." is logged in, session: ".$s->getSessionId().PHP_EOL;
} else {
echo "not logged in".PHP_EOL;
}
Did seem to work for me:
John Smith is logged in, session: d3rcgvd56md4u3cfctcvnt2ou6
If you have the Session ID, you can get at the data with the following call to the core session singleton:
$sessId = 'sn1q4ndvr1kieumsmplhd39n83';
$sess = Mage::getSingleton('core/session', array( 'value' => $sessId ));
That will retrieve the session for any user, logged-in or not. From there you can determine whether the session belongs to a customer with a check for the customer object:
$sessionCustomerId = $sess->getCustomer()->getId();
if ( $sessionCustomerId ) {
// yay, they are a customer!
echo $sessionCustomerId;
}
Hope that helps.
Edit:
You can get the session id from the core session (in a chicken-and-egg style) using Mage::getSingleton('core/session')->getEncryptedSessionId()

Facebook login with php sdk

Everything works great when I log in, I get the users id and Name, however when I click on "Logout" button, it just logs me out of facebook, nothing else happens. Button doesn't wan't to change to "Login". Why? It just ignores the else part of the statement...
public function fblogin() {
require_once '../application/libraries/facebook.php';
//Create our Application instance
$facebook = new Facebook(array(
'appId' => '**********', // Facebook App ID
'secret' => '*******************', // Facebook App Secret
));
//Get User ID
$user = $facebook->getUser();
if (isset($user)) {
try {
$me = $facebook->api("/me");
} catch (FacebookApiException $e) {
$user = null;
echo $e-> getMessage();
}
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
echo $me["id"];
echo $me["name"];
echo ("<a href='$logoutUrl'>Logout</a>");
}
}
else {
$loginUrl = $facebook->getLoginUrl();
echo ("<a href='$loginUrl'>Login</a>");
}
}
Maybe if you add the else at the end of this fraction
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
echo $me["id"];
echo $me["name"];
echo ("<a href='$logoutUrl'>Logout</a>");
} else {
$loginUrl = $facebook->getLoginUrl();
echo ("<a href='$loginUrl'>Login</a>");
}

Facebook PHP SDK session variable not passing

fbconnect.php
include('functions.php');
connect();
require 'src/facebook.php';
if (!isset($_SESSION['user'])) {
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
));
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me', 'GET');
$ret = $facebook->api( array(
'method' => 'fql.query',
'query' => 'SELECT affiliations FROM user WHERE uid = me()',
));
$network = $ret['0']['affiliations']['0']['name'];
//echo $network;
$data = $facebook->api('/me', 'get', array("fields"=>"location"));
$location = $data['location']['name'];
$sql = mysql_query("SELECT * FROM xx_users WHERE user_id=$user_profile[id]");
if (mysql_num_rows($sql) == 0) {
mysql_query("INSERT INTO xx_users (name, user_id, email, network, location)
VALUES ('$user_profile[name]', '$user_profile[id]', '$user_profile[email]', '$network', '$location')");
}
else {
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
// $loginUrl = $facebook->getLoginUrl();
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email, user_location, user_work_history, user_education_history', // Permissions to request from the user
'redirect_uri' => 'http://comfyshoulderrest.com/socialexchange/home.php', // URL to redirect the user to once the login/authorization process is complete.
));
}
}
else {
$_SESSION['user'] = $user;
$_SESSION['friends'] = $facebook->api('/me/friends');
// $_SESSION['friends'] = $facebook->api('/$user/friends'); THIS GIVES THE SAME RESULT
}
data.php
include('functions.php');
connect();
session_start();
$friends = $_SESSION['friends'];
$user = $_SESSION['user'];
$arr = $friends['data'];
$friend_ids_arr = array();
foreach ($arr as $friend) { // THIS IS LINE 14
$friend_ids_arr[] = $friend['id'];
}
error:
Warning: Invalid argument supplied for foreach() in /blah/data.php on line 14
Is there anything I'm doing that's preventing the variable from passing?
EDIT
$_SESSION['user'] prints just fine, so I presume the problem lies with this line:
$_SESSION['friends'] = $facebook->api('/me/friends');
I'm not sure how data.php ties into fbconnect.php but maybe you want to use
$friends = $_SESSION['friends'];
before
$arr = $friends['data'];
From what I've seen, on fbconnect.php you didn't start the session. Try inserting session_start(); after connect().

facebook->api('/me') not working on localhost.

<?php
require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';
define('APP_ID', '******************');
define('APP_SECRET', '***********************');
$facebook = new Facebook(array(
'appId' => '******************',
'secret' => '***********************',
'cookie' => true
));
$session = $facebook->getSession();
if (!empty($session)) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try {
$uid = $facebook->getUser();
print_r($uid);
$user = $facebook->api('/me');
facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;
} catch (Exception $e) {
}
if ($user) {
# User info ok? Let's print it (Here we will be adding the login and registering routines)
echo '<pre>';
print_r($user);
echo '</pre><br/>';
$username = $user['name'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
header("Location: home.php");
}
} else {
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
} else {
# There's no active session, let's generate one
// $login_url = $facebook->getLoginUrl();
$loginUrl = $facebook->getLoginUrl( array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,publish_stream',
'next' => 'http://localhost/login_twitbook/',
'cancel_url' => 'http://localhost/login_twitbook/'
) );
header("Location: " . $login_url);
}
?>
The $user = $facebook->api('/me'); doesnot working properly its always returns nothing. pls help me to solve this problem. I'm working on localhost.$uid = $facebook->getUser() its returns the value but the $user doesnt return
Try changing the getCode function in the base_facebook.php file change all the $_REQUEST to $_GET. Not sure why this hasn't been fixed yet but I was pulling my hair out trying to figure out why it was returning 0 for the user until I did this, now it works flawlessly.
Should be on or around line 680 of the file and there are 4 to change.
protected function getCode() {
if (isset($_GET['code'])) {
if ($this->state !== null &&
isset($_GET['state']) &&
$this->state === $_GET['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $_GET['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}

Not getting $fbme['email'] in the facebook $fbme object

I want to get the facebook $fbme email information using the facebook php SDK.I am getting rest of the information like Firstname,Lastname,Gender but not getting the Email.I have even tried giving the Extended email permissions but that did not help.Please help as soon as possible.
Here is my code
/*
* Sign up procees for facebook login
*/
if (array_key_exists("facebook", $_GET)) {
/*
* Distroy all sesion data
*/
$this->objSession->unsetAll();
/*
* Distroy all api session data
*/
$this->objAPISession->unsetAll();
/*
* if seesion data is not present then facebook login
*/
if (0 == $this->objSession->USRlKey) {
try {
include_once "library/facebook/facebook.php";
} catch (Exception $strError) {
echo "facebook.php File not found on server";
}
$arrConfigSetting['appid' ] = FACEBOOK_API_ID;
$arrConfigSetting['secret'] = FACEBOOK_SECRET_KEY;
$facebook = new Facebook(array(
'appId' => $arrConfigSetting['appid'],
'secret' => $arrConfigSetting['secret'],
'cookie' => true ,
));
$strFacebookUser_id = $facebook->getUser();
$fbme = null;
if ($strFacebookUser_id) {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
if ('' != $fbme['id']) {
$this->objAPISession->arrAPIUser['intUsrID'] = $fbme['id'];
$this->objAPISession->arrAPIUser['strFirstName'] = isset($fbme['first_name']) ? $fbme['first_name'] : "";
$this->objAPISession->arrAPIUser['strLastName'] = isset($fbme['last_name']) ? $fbme['first_name'] : "";
$this->objAPISession->arrAPIUser['intUserType'] = 3;
$this->objAPISession->arrAPIUser['strSignUpType'] = "Facebook";
$this->_redirect('/login/emailaddress');
die;
}
} catch (FacebookApiException $e) {
echo $e;
}
} else {
$loginUrl = $facebook->getLoginUrl(array('next' => "http://www.mywebsite.com/facebooklogin_success", 'req_perms' => 'email,read_stream,publish_stream,offline_access'));
//echo("<br>login url=".$loginUrl);
return $this->_redirect($loginUrl);
//return $this->_redirect('login/index');
}
} else {
return $this->_redirect('myprofile/index');
}
}
You need to be using version 3 of the PHP SDK which supports the new OAuth authentication.
Also with version 3 this line should be:
$loginUrl = $facebook->getLoginUrl(array('redirect_uri' => "http://dev.popsip.com/facebooklogin_success", 'scope' => 'email,read_stream,publish_stream,offline_access'));

Categories