SEO

October 13, 2010

Facebook Connect | How Authentic? | One more guy NOT addressing third-party users - Nettuts+

Lately, there’s been quite a fuzz about lazy registration. It turns out that the less the user has to think, the higher the conversion rates are! What a thought! If everybody seems to have a Facebook profile, why not add a one-click user registration? I’ll show you how to do that today.


Step 1. The Setup

MySQL Table

Let’s begin by creating a database table.

  1. CREATE TABLE `users` (  
  2.     `id` int(10) unsigned NOT NULL AUTO_INCREMENT,  
  3.     `oauth_provider` varchar(10),  
  4.     `oauth_uid` text,  
  5.     `username` text,  
  6.     PRIMARY KEY (`id`)  
  7. ) ENGINE=MyISAM  DEFAULT CHARSET=latin1;  
CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `oauth_provider` varchar(10), `oauth_uid` text, `username` text, PRIMARY KEY (`id`) ) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

Quite simple: we will be setting up a table for user information with id, username, first and last name, the URL to the user’s picture, and registered date. Also, we’re adding both an oauth_provider and oauth_uid fields, to distinguish between different third party open authentication protocols and their identifiers. For example, let’s say that, next week, you decide that it’s a good idea to also let Twitter users in. Easy; you just set another value to the oauthprovider, and avoid duplicating oauthuid values.

The Facebook App

Let’s begin by creating a new application. Give it a name and agree to the terms and conditions. Next, grab both the API Key and Secret in the basic tab as shown below.

On the canvas tab, set both the Canvas URL and Post-Authorize Redirect URL to your localhost and path that the script will process — something like http://localhost.com/login_facebook.php?. Note the question mark at the end and the domain; both are required by Facebook. Simply set your hosts file to a valid domain name.

On the connect tab, set the Connect URL to the same value and set localhost.com (or the one you are using) as the Base Domain.

Now save, download the client library, and unzip facebook.php in the srcdir to a new directory created in the root.


Step 2. The Callback

The authentication flow has three steps:

  1. The local script generates a URL asking the user for permission
  2. Facebook returns to the Canvas URL specified with a GET parameter
  3. The GET parameter authenticates the session

Let’s make a quick test before registering and login.

  1. # We require the library  
  2. require("facebook.php");  
  3.   
  4. # Creating the facebook object  
  5. $facebook = new Facebook(array(  
  6.     'appId'  => 'YOUR_APP_ID',  
  7.     'secret' => 'YOUR_APP_SECRET',  
  8.     'cookie' => true  
  9. ));  
  10.   
  11. # Let's see if we have an active session 
  12. $session = $facebook->getSession(); 
  13.  
  14. if(!empty($session)) { 
  15.     # Active session, let's try getting the user id (getUser()) and user info (api->('/me'))  
  16.     try{  
  17.         $uid = $facebook->getUser();  
  18.         $user = $facebook->api('/me');  
  19.     } catch (Exception $e){}  
  20.   
  21.     if(!empty($user)){  
  22.         # User info ok? Let's print it (Here we will be adding the login and registering routines) 
  23.         print_r($user); 
  24.     } else { 
  25.         # For testing purposes, if there was an error, let's kill the script  
  26.         die("There was an error.");  
  27.     }  
  28. else {  
  29.     # There's no active session, let's generate one  
  30.     $login_url = $facebook->getLoginUrl();  
  31.     header("Location: ".$login_url);  
  32. }  
# We require the library require("facebook.php");  # Creating the facebook object $facebook = new Facebook(array( 'appId'  => 'YOUR_APP_ID', 'secret' => 'YOUR_APP_SECRET', 'cookie' => true ));  # Let's see if we have an active session $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(); $user = $facebook->api('/me'); } catch (Exception $e){}  if(!empty($user)){ # User info ok? Let's print it (Here we will be adding the login and registering routines) print_r($user); } 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(); header("Location: ".$login_url); }

Now, go to http://localhost.com/login_facebook.php, and let’s see what happens. If you are redirected to Facebook and requested for permission, we are on the right track.

However, there might be two issues. The first one: if you’re redirected to Facebook, but it shows an error, there might be a missing value in the configuration. Go back to your application settings and check both the Connect and Canvas tabs and make sure the fields are ok as described above.

There might be another issue, where you see an error, like “Uncaught CurlException: 60: SSL certificate problem, verify that the CA cert is OK.” This happens because of the CURL settings. You’ll have to open facebook.php, find the makeRequest() method, and, inside the function, find this line:

  1. $opts = self::$CURL_OPTS;  
$opts = self::$CURL_OPTS;

Immediately following it, add:

  1. $opts[CURLOPT_SSL_VERIFYPEER] = false;  
$opts[CURLOPT_SSL_VERIFYPEER] = false;

I hate hacking libraries, but I haven’t found another way. Well, let’s continue with user registration. I’ve also added a try/catch statement, because, if there’s an old session keys in the GET params in the URL, the script will die with a horrible error.


Step 3. Registration and Authentication

We’ll next be working with MySQL. Please note that I will not implement a data sanitizer, since I want to keep the code as short and on task as possible. Please keep this in mind: always sanitize your data.

First, let’s connect to the database.

  1. mysql_connect('localhost''YOUR_USERNAME''YOUR_PASSWORD');  
  2. mysql_select_db('YOUR_DATABASE');  
mysql_connect('localhost', 'YOUR_USERNAME', 'YOUR_PASSWORD'); mysql_select_db('YOUR_DATABASE');

Now, let’s work on the $session conditional, in case we have a session.

  1. # We have an active session; let's check if we've already registered the user  
  2. $query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND oauth_uid = "$user['id']);  
  3. $result = mysql_fetch_array($query);  
  4.   
  5. # If not, let's add it to the database 
  6. if(empty($result)){ 
  7.     $query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username) VALUES ('facebook', {$user['id']}, '{$user['name']}')");  
  8.     $query = msyql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());  
  9.     $result = mysql_fetch_array($query);  
  10. }  
# We have an active session; let's check if we've already registered the user $query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND oauth_uid = ". $user['id']); $result = mysql_fetch_array($query);  # If not, let's add it to the database if(empty($result)){ $query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username) VALUES ('facebook', {$user['id']}, '{$user['name']}')"); $query = msyql_query("SELECT * FROM users WHERE id = " . mysql_insert_id()); $result = mysql_fetch_array($query); }

Note that I’m querying the database, looking for facebook as a oauth_provider; it’s generally a good idea, if you want to accept other OAuth providers (as twitter, Google Accounts, Open ID, etc.) and a oauth_uid, since it’s the identifier the provider gives to its user accounts.

The oauth_provider field could potentially lead to bad performance if we leave it as a text field type. As such, the best option is setting it to an ENUM type.

We have now a $result var with the values queried from the database. Let’s next add some sessions. Add this line at the beginning of your script.

  1. session_start();  
session_start();

After the empty($result) conditional, append the following:

  1. if(!empty($user)){  
  2.     # ...  
  3.   
  4.     if(empty($result)){  
  5.         # ...  
  6.     }  
  7.   
  8.     # let's set session values 
  9.     $_SESSION['id'] = $result['id']; 
  10.     $_SESSION['oauth_uid'] = $result['oauth_uid']; 
  11.     $_SESSION['oauth_provider'] = $result['oauth_provider']; 
  12.     $_SESSION['username'] = $result['username'];  
  13. }  
if(!empty($user)){ # ...  if(empty($result)){ # ... }  # let's set session values $_SESSION['id'] = $result['id']; $_SESSION['oauth_uid'] = $result['oauth_uid']; $_SESSION['oauth_provider'] = $result['oauth_provider']; $_SESSION['username'] = $result['username']; }

As it makes little sense to authenticate a user who is already logged in, just below the session_start() line, add:

Posted to See Ya At What Gets Me Hot via Dogmeat