Unable to destroy session after clicking logout link in codeigniter(facebook integration) - facebook

Session is not destroying after clicking the logout link on home page. Here is my code
public function login()
{
$config['appId'] = '405802852809513';
$appid=$config['appId'];
$config['secret'] = 'b873cf1c00e9e1554cb0eede34d252d5';
$secret=$config['secret'];
$this->load->library('facebook', $config);
$user = $this->facebook->getUser();
if ($user) {
try {
$user_profile = $this->facebook->api('/me'); print_r($user_profile);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
echo"<br>";
echo $data['logoutUrl']=$this->facebook->getLogouturl(array("next"=>site_url('/user/logout')));
} else {
$scope = array(
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown'
);
$data['loginUrl'] = $this->facebook->getLoginUrl($scope);
}
if ($user) {
$logoutUrl=$data['logoutUrl'] ;
$user_info = array(
'name' => $user_profile["name"],
'app_id'=>$appid,
'secret'=>$secret,
'id' =>$user_profile["id"],
'logoutUrl'=> $logoutUrl,
);
$this->load->library('session');
$this->session->set_userdata($user_info);
redirect('user/home') ;
} else {
$this->load->view('frm_login',$data);
}
}
After filling email and passoward user will be redirect to home page and home method will be called
public function home(){
$this->load->library('session');
$user_info=$this->session->all_userdata();
if(isset($user_info['name'])){
$data['name']=$user_info['name'];
if(isset($user_info['logoutUrl']))$data['logoutUrl']=$user_info['logoutUrl'];
$this->load->view("home",$data);
}
else{
redirect("user/login");
}
}
And here is the view for my home page
<html>
<body>
Welcome <?php echo $name;?>
<?php
if(isset($logoutUrl))
{?>
Fb_Logout
<?php }
else
{?>
Logout
<?php
}
?>
</body>
</html>
And here is my logout for destroying the session but the prob is that session is not destroying. I tried everything to destroythe session but still it exists.
And if I call user/loggin in the url then it show my directly the home page with my facebook name displayed on it.If the session is successfully destroyed then it must show the login screen of facebook, but it is not showing that. Please help me out got stucked in this for almost 2 days. Your replies are totally welcome.
public function logout(){
$this->load->library('session');
$this->load->library('facebook', $config);
$this->session->unset_userdata($user_info);
$this->facebook->destroysession();
$this->session->sess_destroy();
redirect("user/login");
}

I do not know in which class do you have your logout method. It is a class right? (otherwise it would be strange to see the usage of $this inside). Do you have a session object in that class? What class does your session object have in your class? Is the class of your session object having a sess_destroy method? If so, is it public? If so, what does it contain? Also, where do you call your logout() method? Is it even executed?
These should have been the questions you should have asked yourself.
This is a reference about how to destroy the session in php.

Related

zf2 navigation, how to hide some items based on session

My zendframwork 2 application contains a navigation in my application/module.php , this navigation contains many items from which some of them are ( login - logout - register )
I don't need to show the three all the time In the navigation menu.. when the user is n't logged in I must show him : login- register , after he logs-in, I must show him only logout link
How can I do that?
Removing pages
Module.php
public function onBootstrap(MvcEvent $e)
{
$application = $e->getApplication();
$serviceManager = $application->getServiceManager();
if (user not login) {
$container = $serviceManager ->get('navigation');
$logoutPage = $container->findBy('route' , 'logout');
$container->removePage($logoutPage);
}
}
<?php if (isset($_SESSION["login"]) { ?>
Logout
<?php } else { ?>
Login
Register
<?php } ?>
or something similar to this might work. Replace the "login" key with whatever yours is.

Get the facebook accounts value in a particular file

I have used the facebook php sdk and I want to get the value in another file, so I give the redirection path, after login it is going on the page but $user is blank, when I am refreshing the page then I got the values. my code is like below
From where the login page is calling :
$facebook = new Facebook(array('appId' =>FB_APP_ID ,'secret' => FB_APP_SECRET));
$scope='email,user_birthday,user_location,user_work_history,user_about_me,user_hometown';
$parameters=array("redirect_uri"=>"http://www.xyz.com//test.php","scope"=>$scope);
$login_url= $facebook->getLoginUrl($parameters);
and the test.php is like below
$facebook = new Facebook(array(
'appId' => '224402951020359' ,
'secret' => 'd2731260cdd7425dc11eee5f265a3dee'
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_data = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
print_r($user_data);
How can I get the value in first time.
On your test.php page, put a test for !$user and if true then redirect again to the loginurl... something like the following is what I do in my code to avoid this same problem.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,publish_stream,user_birthday,user_location'
)
);
if ($user) {
try {
//get user basic description
$userInfo = $facebook->api("/$user");
$fb_access_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
error_log('Sharebox: '.$e); // d is a debug function defined at the end of this file
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
Hope this helps.

unable to to open redirected page after facebook authentication

i am using facebook connect under codeigniter.after authentication i want to redirect on success method of my controller
here is my controller:
class Welcome extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Facebook_model');
}
function index()
{
$fb_data = $this->session->userdata('fb_data');
$data = array(
'fb_data' => $fb_data,
);
$this->load->view('welcome', $data);
}
function topsecret()
{
$fb_data = $this->session->userdata('fb_data');
if((!$fb_data['uid']) or (!$fb_data['me']))
{
redirect('welcome');
}
else
{
$data = array(
'fb_data' => $fb_data,
);
$this->load->view('topsecret', $data);
}
}
function success()
{
$this->load->view('welcome_message');
}
}
my model for facebook api access:
class Facebook_model extends CI_Model {
public function __construct()
{
parent::__construct();
$config = array(
'appId' => '261066574000678',
'secret' => ' 79e11f65449988965362f58e9a4aabd7',
'fileUpload' => true, // Indicates if the CURL based # syntax for file uploads is enabled.
);
$this->load->library('Facebook', $config);
$user = $this->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.
$profile = null;
if($user)
{
try {
// Proceed knowing you have a logged in user who's authenticated.
$profile = $this->facebook->api('/me?fields=id,name,link,email');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
$fb_data = array(
'me' => $profile,
'uid' => $user,
'loginUrl' => $this->facebook->getLoginUrl(
array(
'scope' => 'email,user_birthday,publish_stream', // app permissions
'redirect_uri' => 'https://sanjay.localhost.com/index.php/welcome/success' // URL where you want to redirect your users after a successful login
)
),
'logoutUrl' => $this->facebook->getLogoutUrl(),
);
$this->session->set_userdata('fb_data', $fb_data);
}
}
since i am testing this on localhost host,i also edited my host file and changed my localhost hostname to sanjay.localhost.com.redirect happens but not happens..i think may be because of querystring.when redirects happens redirect uri is
=">https://sanjay.localhost.com/index.php/welcome/success?state=ff5712299510defa&code=AQCaD-FAd1shuW#=
i am not understanding how to handle state and code inside of query string.
please help.
Thank you for contacting me on my blog. First of all, Facebook is discontinued the localhost support. Her is the link https://developers.facebook.com/bugs/128794873890320.
I have not developed any app using codeigniter, I use CakePHP but the auth follow should be same.
1. Create a fb_login function in user controller.
2. This function will follow this logic.
a. Use $facebook->getUser() to get user id.
b. Then use $facebook->api('/me') to be sure.
3.If you get FacebookApiException then send user to login with Facebook. If you use official SDK then the current url will be added to redirect url.
4.the Facebook will redirect your user after sign in. so you will get data using $facebook->getUser(). Save this data in session for further use in you app. then redirect user to you control page or any other page. CakePHP has setFlash() function wich show what ever msg set in the control panel in view. I think Codeignator should have some thing like this. If not you can simply set a msg in session and redirect user. Then unset the msg after showing the msg.
Here is full code
$uid = $facebook->getUser();
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//echo $e->getMessage();
$uid = null;
}
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'publish_stream,offline_access,email'
),''
);
if (!$uid) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
//search using uid on your user table to check if the use is returnign user or new user.
if($new_user ==1)
{
$this->Session->setFlash('please sign up');
//redirect to sign up
}
else
{
$this->Session->setFlash('you are good lad');
//reditect to control panel
}

redirect to facebook app page after grant permissions

My app is inside a fan page, when i request permission it will show the dialog.
The problem is after user accept, they are redirected to real app page (url here app is hosted)
for understand better i have the url generated with facebook PHP SDK
https://www.facebook.com/dialog/oauth?client_id=341572315885516&redirect_uri=https%3A%2F%2Fmywebapp.com%2Fyii%2Folivi%2Ffacebook%2Fapp%2Fid%2F1%2F&state=40e532d364f67631cfc1ef6061609157&canvas=1&fbconnect=0&scope=user_about_me%2Cuser_birthday
As we can see will redirect outside of facebook, i want redirect back
in that case: https://www.facebook.com/mypage/app_341572315885516
Any way to solve this situation? I have tried a lot of things nothing works...
Wheres my code:
<?php $userid = Yii::app()->facebook->getUser(); ?>
<?php $results = NULL;//$results = Yii::app()->facebook->api('/me'); ?>
<?php
$signed_request = Yii::app()->facebook->getSignedRequest();
if(!isset($signed_request['page']) || !isset($signed_request['page']['liked']))
{
$this->renderPartial('_nofan', array('model'=>$model));
}
else
{
if(!$signed_request['page']['liked'])
{
$this->renderPartial('_nofan', array('model'=>$model));
}
else
{
try
{
$results = Yii::app()->facebook->api('/me');
}
catch (FacebookApiException $e) {
}
if(!$userid || !$results)
{
$loginUrl = Yii::app()->facebook->getLoginUrl(array('scope'=>'user_about_me,user_birthday'));
/*echo "<script type='text/javascript'>top.location.href = '{$loginUrl}';</script>";*/
Yii::app()->clientScript->registerScript('login-perm', 'top.location.href = "'.$loginUrl.'";', CClientScript::POS_HEAD);
//$this->redirect($loginUrl);
/*Yii::app()->facebook->addJsCallback("FB.login(function(response) {
if (response.authResponse) {
// user is logged in and granted some permissions.
} else {
// User cancelled login or did not fully authorize.
}
}, {scope:'user_about_me,user_birthday'});");*/
}
// FAN
//echo 'Olá';
}
}
?>
Thanks
You can try redirect_uri paramaeter,
Ex:
$redirecturl = https://www.facebook.com/mypageonfacebook/app_APPID;
$params = array('scope' => 'email, publish_actions', 'redirect_uri' => $redirecturl);
$loginUrl = $facebook->getLoginUrl($params);
echo("<script> top.location.href='".$loginUrl."'</script>");
hope this will help you.. thanks..

How to handle Facebook's signed_request for iFrame Canvas applications?

I'm developing an iFrame Canvas application for Facebook using CakePHP, its Auth component, WebTechNick's Facebook plugin and OAuth for canvas pages (I've enabled this in the Facebook Developer app options). I would like users to be able to use the application after adding it to their profile (by requesting email and publish_stream permissions) by visiting http://apps.facebook.com/myapp/ or as a tab in their profile.
Requesting permissions is not the problem. The user is redirected to the permissions request page and then redirected to a callback method which requests an access_token, as per this tutorial.
After this callback the user is redirected back to http://apps.facebook.com/myapp/ which shows their personal index page. This is also where the problems start. As soon as the aforementioned URI is loaded, the browser asks for a form resubmission, this happens every time I reload http://apps.facebook.com/myapp/. This is the case because Facebook wants to pass the (expected) signed_request parameter and I'm wondering what to do with it. It's not an empty variable, so do I need another validation method or redirect, perhaps?
How should I handle the procedure for the signed_request parameter and, more importantly how to get rid of this form resubmission dialog?
Some of my methods, they might be a bit of a mess due to all the experimentation of the past day.
beforeFilter, login and callback methods, in my UserController.php:
function beforeFilter() {
parent::beforeFilter();
if (empty($this->permissions)) {
$this->Auth->allow('login', 'logout', 'callback');
}
}
function login() {
$session = $this->facebook->getSession();
$login_url = 'https://graph.facebook.com/oauth/authorize?client_id=' . FACEBOOK_APP_ID . '&redirect_uri=' . MY_APP_URL . '/users/callback/&type=user_agent&&display=page&scope=' . FACEBOOK_APP_PERMISSIONS;
if($session){
try {
$uid = $facebook_client->getUser();
$me = $facebook_client->api('/me', $params);
print($me);
} catch (FacebookApiException $e) {
error_log($e);
}
} else {
$this->set('authorise', true);
$script = '$(document).ready(function() { facebookRequestPermissions("'.$login_url.'");});';
$this->set('script', $script);
}
}
function callback() {
function callFb($url, $params) {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$params=array('client_id'=>FACEBOOK_APP_ID, 'type'=>'client_cred', 'client_secret'=>FACEBOOK_APP_SECRET);
$url = "https://graph.facebook.com/oauth/access_token";
$access_token = callFb($url, $params);
$access_token = substr($access_token, strpos($access_token, "=")+1, strlen($access_token));
if ($access_token) {
$this->redirect(FACEBOOK_APP_URL);
} else {
echo 'An error has occurred';
}
}
The JavaScript in the login method refers to this jQuery function, the Facebook JavaScript SDK is initialised in $(document).ready():
function facebookRequestPermissions(login_url) {
FB.getLoginStatus(function(response) {
if (response.status !== 'unknown') {
top.location.href=login_url;
}
});
}
The JavaScript function should only fire when a user is logged in, if not, a different landing page is shown.
I use some methods in an overall AppControler:
class AppController extends Controller {
var $components = array('RequestHandler', 'Session', 'Auth', 'Facebook.Connect');
var $helpers = array('Form', 'Time','Html','Javascript', 'Session', 'Facebook.Facebook');
protected $facebook;
protected $permissions;
private $user;
function beforeRender() {
//Save the username if it isn't already present
if ((int)$this->Auth->user('id') != '' && (string)$this->Auth->user('username') == '') {
$data = array('id' => (int)$this->Auth->user('id'), 'username' => (string)$this->user['username']);
$this->loadModel('User');
$this->User->save($data);
}
if (!empty($this->user) && !empty($this->permissions)) {
$this->set('currentUser', $this->Auth->user());
}
}
function beforeFilter() {
$this->Auth->autoRedirect = false;
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'index');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
App::import('Lib', 'Facebook.FB');
$this->facebook = new FB();
$this->user = $this->facebook->api('/me');
$this->permissions = $this->facebook->api('/me/permissions');
}
}
EDIT:
This only seems an issue with Firefox. Chrome doesn't display the dialog, but instead does a silent refresh after which the signed_request parameter is empty, strangely enough. This isn't the case with Firefox, where the signed_request parameter remains the same after every prompted refresh (unless the iFrame content is cached), which is looping infinitely, it seems.
EDIT 2:
Still struggling with this, but I ended up disabling the OAuth 2.0 for Canvas option in the Facebook Developer application, which has resolved the form resubmission issue. Of course this is not a real solution, because OAuth 2.0 is becoming mandatory for canvas application on Facebook, I believe.
Since I can't test the whole thing I am not sure if this is right, but on the first sight your JavaScript function looks strange to me. It looks like you always redirect to the login url, although the user gave permission.
Refering to Facebook JavaScript SDK, the function should look like this:
function facebookRequestPermissions(login_url) {
FB.getLoginStatus(function(response) {
if (!response.session) {
top.location.href=login_url;
}
});
}
or, if you want to call .status:
if (response.status == 'unknown')
About your question concerning the signed_request: it is used to get some information, look at Authentication - Signed Request to see what exactly. You don't need another validation method.