Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

Facebook Connect

Junior Spellweaver
Joined
Nov 26, 2008
Messages
196
Reaction score
62
This is just a quick tutorial as I don't have much time left..

The target is to add facebook connect functionality with small changes to your code, we also want to make very small changes to your database and to your normal login process.

INDEX, SEVEN STEPS:
1. Create an application on Facebook
2. Create the xd_receiver.htm file
3. Download the PHP apis for facebook and copy them to your site
4. Modify your users’ table
5. Create a PHP page for log in with facebook connect
6. Link the fbclogin.php file to your login
7. Further implementations in the next posts/pages of this blog

So let’s start:

Create an application on Facebook

This means that you have to be registered and logged-in on Facebook, than you have to go to the developer page on facebook and click on the “set up new application” button.
In the set up page you have different fields to enter, but only these ones are needed to make a facebook-connect application for our purpose:
a. “name of the application” and your developer contact in the Main Panel;
b. “Connect url” in the Facebook Connect Panel, you should enter the root of your community site, for the example:
c. you can customize log (not necessary)

Save the changes.
This will create a couple of keys that you will use inside your PHP login page: API Key and secret. Copy them or leave this window open to copy them later.

xd_receiver.htm file

This file is also called “cross domain communication channel” and it’s a static file which include some javascript from facebook servers. The job of this file is set up cookie of Facebook on your domain. It’s necessary because cookies are linked to the domain of the site that write them, so Facebook cannot add cookies on your site without this. And cookies are necessary because the PHP script that will do the work will read cookies setted up by this file. Your site will call facebook, facebook will ask for password if the user isn’t yet logged in, and facebook will call xd receiver to set up cookies on your domain. Finally the PHP script will read the cookie that say “logged on facebook ok!”.

Save this as xd_reciever.html.

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Cross-Domain Receiver Page</title>
</head>
<body>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js?2" type="text/javascript"></script>
</body>
</html>

Download the PHP apis for Facebook

You can download the PHP API on Facebook servers.

You can get started

Modify database table

This is important: we want to let connect the guys of facebook, but we also want to make new users, so we create new users on our community for every new guy coming from facebook. We suppose that you already have a users’ table on your db:

PHP:
TABLE users (something like this):
 
id  ID INT AUTOINCREMENT PRIMARY
username    VARCHAR
password    VARCHAR
email       VARCHAR
status      ENUM ('active','pending','deactivated')
activationdate  DATETIME

If you have the primary key on the email field, than you will have to remove it and use an autoincrement key because you will not receive the email from facebook, the users coming from facebook do not have the email field filled at the beginning. So they are “different”.

Add these fields to your users table:

PHP:
fb_userid   VARCHAR
fl_facebook ENUM ('new','normal','registered') DEFAULT = 'registered'

the fb_userid will store the facebook user id.
the fl_facebook is a flag and the values can be:

registered = is the default value that identify your users normally registered on your db
new = for new users just created
normal = for users that have been transformed into normal users (this could happen later, when you will ask the email to those users to make some action that only registered users can make on your site… for example buy a thing, subscribe to a newsletter, create a new item…), when they become ‘normal’ they are no longer ‘different’.

Login Page

Here it is the code of the facebook login file (fbclogin.php):

PHP:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>
</head>
<body>
<?
//
// this file includes FB_API_KEY and FB_SECRET constants and the ConnectDB function
// to connect to your mysql database.
include("settings-and-functions.php");

//
// the php facebook api downloaded at step 3
include("fb/php/facebook.php");

if(!ConnectDB()) die;

//
// start facebook api with the codes defined in step 1.
$fb=new Facebook( FB_API_KEY , FB_SECRET );
$fb_user=$fb->get_loggedin_user();

$out="";
if($fb_user) {
	//
	// if we already have a user ID cookie than we link
	// in the database this user with his facebook account
	// using the fb_userid field.
	// this code assumes that when a user login in your
	// community you set up a value in a cookie called "myid".
	// this cookie is the one that you use when you want
	// to remember the user:
	if ($_COOKIES["myid"]) {
		$rs = mysql_query( "select * from users where id <>'".$_COOKIES["myid"]."' and fb_userid='".$fb_user."'" );
		$r = mysql_fetch_array($rs);
		mysql_query("update users set fb_userid='{$fb_user}' where id='".$_COOKIES["myid"]."'");
	}
	//
	// with the user id from facebook retrived with the API,
	// search for a user already registered with this process:
	$rs = mysql_query( "select * from users where fb_userid='$fb_user'" );
	if (mysql_num_rows($rs)) $u = mysql_fetch_array($rs); else $u="";
	if (is_array($u)) {
		//
		// this is a user connected with facebook
		// and already existing on your community.
		// So, log in automatically with user and password of
		// your community. These lens print a form and submit it
		// to your real login page:
		// (change the address in the action to match your normal login page)
		$out.="log in...";
		$out.="<form id='loginform' method='post' action=\"http://www.your-site-url.com/login.php\">";
		$out.="<input type='hidden' name='user' value=\"".$u['username']."\"/>";
		$out.="<input type='hidden' name='pass' value=\"".$u['password']."\"/>";
		$out.="</form>";
		$out.="<script type=\"text/javascript\">document.getElementById('loginform').submit();</script>";

	} else {
		//
		// this is a user logged in on facebook
		// but it doesn't exists on your community,
		// it's new!
		// So let's create automatically the user and log in!
		$out = '<fb:profile-pic class="fb_profile_pic_rendered FB_ElementReady"' .
		'facebook-logo="true" size="square" uid="' . $fb_user . '"></fb:profile-pic>';
		//
		// get some user details from facebook api
		$user_details = $fb->api_client->users_getInfo($fb_user, array('last_name','first_name'));
		//
		// write out some message to welcome the new user:
		$out.= $user_details[0]['first_name']." ".$user_details[0]['last_name'].", welcome on your-site-url.com<br/>";
		$out.= "creating your account on your-site-url.com... wait...";
		$tempuser = preg_replace("/[^a-z0-9]/i","",strtolower( $user_details[0]['first_name'].$user_details[0]['last_name'] ));
		$found = false;
		$i=0;
		while (!$found) {
			//
			// search for a valid username
			// not already used in your community
			// this username is created with first name and last name
			// from facebook and with a counter:
			$user = $tempuser.($i==0?"":$i);
			$rs = mysql_query("select count(*) from users where username='$user'");
			$c = mysql_fetch_row($rs);
			if ( $c[0] >0 ) $i++; else $found = true;
		}
		//
		// generate random password for new user:
		$pass = "fb".rand(1000,2000);
		//
		// empty email:
		$email = "";
		//create the user on your table
		$sql = "INSERT INTO users (" .
			"username, password, name, surname, email, status, activationdate, fb_userid, fl_facebook".
			") VALUES ('{$user}','{$pass}','".addslashes($user_details[0]['first_name'])."',".
			"'".addslashes($user_details[0]['last_name'])."','".$email."',".
			"'active',NOW(),'','".
			$fb_user."','new')";
		mysql_query($sql);
		//
		// new user created, log him in:
		$out.="log in...";
		$out.="<form id='loginform' method='post' action=\"http://www.your-site-url.com/login.php\">";
		$out.="<input type='hidden' name='user' value=\"".$user."\"/>";
		$out.="<input type='hidden' name='pass' value=\"".$pass."\"/>";
		$out.="</form>";
		$out.="<script type=\"text/javascript\">document.getElementById('loginform').submit();</script>";
	}
} else {
	//
	// the user probably isn't logged in on facebook, put out
	// the facebook button and clicking on it it will open a pop uo
	// that requires the login on facebook to proceed.
	// the "onlogin" command refreshes the page.
	$out = '
	<div">Click to log on your-site-url.com with your facebook account.<br/><fb:login-button size="medium" onlogin="document.location.href=document.location.href;"></fb:login-button><br/>
	</div>';
}
?>
<?=$out?>
<script type="text/javascript">  FB.init("<?=FB_API_KEY?>", "/xd_receiver.htm"); </script>
</body>
</html>

Link fbclogin.php

Near your login fields, add a link to the fbclogin.php file so users will notice suddenly that you give a facebook connect functionality.

I don't have a demo, so if someone can do, it'd be sex for you.
 
Last edited:
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
I like the thought, but you have SQL injections

Placing the cookie variable directly in a sql query is bad.. injection.

Also this:
PHP:
mysql_query("update users set fb_userid='{$fb_user}' where id='".$_COOKIES["myid"]."'");
can allow a malicious user who changes their cookie "myid" to their desired user's id will hijack their account.... Sure looks like it needs some more thought-out security.

Anything delivered from the client is a security risk. The client provides cookies, be aware of that.
 
Last edited:
Junior Spellweaver
Joined
Nov 26, 2008
Messages
196
Reaction score
62
Like I said, it was only a quicky. =P

not hard to patch or filter out injections anyway.
 
Joined
Mar 2, 2008
Messages
764
Reaction score
9
You could put an IP with the Cookie?

And then just check if REMOTE_ADDR matches the ip of the cookie.

If not, error, if yes, the cookie isn't hijacked.

Correct if wrong plox.
 
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
Like I said, it was only a quicky. =P

not hard to patch or filter out injections anyway.

Once you get an injection, it could be impossible to repair. Not everyone keeps up-to-date back-ups of their database. Also, not everyone can find the SQL injections when they do this tutorial.

You could put an IP with the Cookie?

And then just check if REMOTE_ADDR matches the ip of the cookie.

If not, error, if yes, the cookie isn't hijacked.

Correct if wrong plox.
REMOTE_ADDR and cookies are both supplied by the client, so neither can be trusted.

Forget about the REMOTE_ADDR, the problems can be solved by moving the cookie to a session instead.
 
Junior Spellweaver
Joined
Nov 26, 2008
Messages
196
Reaction score
62
Facebook connect also allows you to pull certain information from the users profile page. Have to watch out because it may violate their TOS.
 
Rip Akaruz
Loyal Member
Joined
Dec 18, 2007
Messages
934
Reaction score
12
I think its like an external facebook page; meaning you connect to facebook by there servers but your script... so you should still need an account.
 
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
I'm not understanding, don't you still need an account on the site? or are you only allowed certain things from a specific site if you login via Facebook?

Well it depends on the webmaster implementing the facebook connection what they do with the data.

In usual cases, a facebook connection will substitute a registration and login. There's often a way for users to register at the site either normally, or via facebook connection.

It's much easier to register at a site with a facebook connection- to the end-user.

The data facebook gives out during this connection isn't any different than what one can find around your profile. They aren't giving away your password, and facebook will ask you when the third-party requires your email address. Whether or not you agree to give it out is your choice. Their terms of service explain more on this.

Facebook does give out your name, interests, your pics- even your friend's names, interests and pics. But if you look on your profile, you'll notice all of that stuff can be acquired one way or another in any case (at least by your friends). If you connect with a site or facebook application, it's sort of like adding them to your friends. Of course they aren't in your friends, they show as "applications" on facebook.

You'll have to ask somebody like Foxx, john_d, or Exiled Hero how it works for the application developer.
 
Back
Top