Jump to content

fb login resend/retry issue in facebook iframe


dflow

Recommended Posts

this script works without a problem outside

facebook

 

when included in an facebook iframe

it doesnt redirect correctly

in firefox i am prompted with resend

and IE 8.9 retry window.

 

something with the flow? :confused:

 

<?php
/*
	UserCake Version: 1.4
	http://usercake.com

	Developed by: Adam Davis
*/
require_once("../userCake/models/config.php");

//Prevent the user visiting the logged in page if he/she is already logged in
//if(isUserLoggedIn()) { header("Location: account.php"); die(); }
?>
<?php
define('YOUR_APP_ID', 'xxxxxxxxxxxxxxx');
define('YOUR_APP_SECRET', 'xxxxxxxxxxxxxx');

function get_new_facebook_cookie($app_id, $app_secret) {
$signed_request = parse_signed_request($_COOKIE['fbsr_' . $app_id], $app_secret);
// $signed_request should now have most of the old elements
$signed_request[uid] = $signed_request[user_id]; // for compatibility
if (!is_null($signed_request)) {
	// the cookie is valid/signed correctly
	// lets change "code" into an "access_token"
	$access_token_response = @file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=$app_id&redirect_uri=&client_secret=$app_secret&code=$signed_request[code]");
	parse_str($access_token_response);
	$signed_request[access_token] = $access_token;
	$signed_request[expires] = time() + $expires;
}
return $signed_request;
}

function get_facebook_cookie($app_id, $app_secret) {
  $args = array();
  parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
  ksort($args);
  $payload = '';
  foreach ($args as $key => $value) {
    if ($key != 'sig') {
      $payload .= $key . '=' . $value;
    }
  }
  if (md5($payload . $app_secret) != $args['sig']) {
    return null;
  }
  return $args;
}
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);

// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);

if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
	error_log('Unknown algorithm. Expected HMAC-SHA256');
	return null;
}

// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
	error_log('Bad Signed JSON signature!');
	return null;
}

return $data;
}

function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
$cookie = get_new_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);
if (!empty($cookie['access_token'])) {
$fb = array();
$fb['access_token'] = $cookie['access_token'];	
$fb['uid'] = $cookie['uid'];
$fb['sig'] = $cookie['sig'];
$fb['session_key'] = $cookie['session_key'];
$user = json_decode(@file_get_contents('https://graph.facebook.com/me?access_token=' .$cookie['access_token']));
//$user = json_decode(file_get_contents('https://graph.facebook.com/me?access_token=' .$cookie['access_token']));
$fb['email'] = $user->email;	
/**
 * After getting all the facebook parameters (need to check if we got email the access_token is ok
 * if we don't have email the access_token is not valid and we need to unset it and make the user
 * login again.
 * 
 * Now we need to check if the user is in the usercake DB.
 * If the user exists we just need to log him in into usercake without a password.
 * If the user don't exists we will need to add him to usercake database.
 * Then we will need to log him in.
 * 
 */	
//email not empty
if (!empty($fb['email'])) {
	require_once '../database_connection.php';
	$password = 'fb_user';
	$username = $fb['uid'];
	$email = $fb['email'];		
	$query = 'SELECT User_ID from userCake_Users WHERE Email = \''.$fb['email'].'\'';
	$results = mysql_query($query);		
	if (mysql_num_rows($results) == 0) {
		//user doesn't exists need to create him
		//$query = 'INESRT INTO userCake_Users(Username,Username_Clean,Password,Email,ActivationToken,LastActivationRequest,LostPasswordRequest,Active,Group_ID,SignUpDate,LastSignIn,fb_token,fb_uid,fb_sig,fb_session_key) values('
		//.'\''.$fb['uid'].'\',\''.$fb['email'].'\','
		//.'\''.$fb['uid'].'\',\''.$fb['email'].'\','			
		$user = new User($username,$password,$email);
		if(!$user->userCakeAddUser()) {
			//an error has occured
			die("error 112413");
		}
		$userdetails = fetchUserDetails($username);
		//need to activate the user and update the facebook parameters after we added the user.
		$update = 'UPDATE userCake_Users SET Active = 1, fb_token = \''.$fb['access_token'].'\','
				.'fb_uid = \''.$fb['uid'].'\', fb_sig = \''.$fb['sig'].'\', fb_session_key = \''.$fb['session_key'].'\' WHERE User_ID=\''.$userdetails['User_ID'].'\'';	
		mysql_query($update);					
	} else {
		//user already exists.
		//lets just update the facebook data	
		$userdetails = fetchUserDetails($username);
		$update = 'UPDATE userCake_Users SET Active = 1, fb_token = \''.$fb['access_token'].'\','
				.'fb_uid = \''.$fb['uid'].'\', fb_sig = \''.$fb['sig'].'\', fb_session_key = \''.$fb['session_key'].'\' WHERE User_ID=\''.$userdetails['User_ID'].'\'';	
		mysql_query($update);			
	}		
	//make user logged-in according to userCake.
	$loggedInUser = new loggedInUser();						
	$loggedInUser->email = $userdetails["Email"];
	$loggedInUser->user_id = $userdetails["User_ID"];
	$loggedInUser->hash_pw = $userdetails["Password"];
	$loggedInUser->display_username = $userdetails["Username"];
	$loggedInUser->clean_username = $userdetails["Username_Clean"];

	//Update last sign in
	$loggedInUser->updateLastSignIn();

	$_SESSION["userCakeUser"] = $loggedInUser;
	//move user to logged in page..		
	header("Location: /apartmentsManagment.php");
	die("");
}

} else {
//unset cookie if there is no uid and access token
unset($cookie);
$cookie = false;
}
?>
<html>
  <head>
  <script id="facebook-jssdk" src="//connect.facebook.net/en_US/all.js"></script>
  </head>
  <body>
    <?php if ($cookie) { ?>
      Welcome <?= $user->name ?>
    <?php } else { ?>
      <fb:login-button scope="email,offline_access"></fb:login-button>
    <?php } ?>
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId      : '<?= YOUR_APP_ID ?>',
          status     : true, 
          cookie     : true,
          xfbml      : true,
          oauth      : true
        });

        FB.Event.subscribe('auth.login', function(response) {
          window.location.reload();
        });
      };

      (function(d){
         var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
         js = d.createElement('script'); js.id = id; js.async = true;
         js.src = "//connect.facebook.net/en_US/all.js";
         d.getElementsByTagName('head')[0].appendChild(js);
       }(document));
      window.fbAsyncInit();
    </script>
  </body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.