Implementing Login With Facebook

24 / Sep / 2012 by vineet 5 comments

Hi,

In my recent grails project i had a requirement to allow an user to login into my site using his Facebook credentials
To achieve it , here is what is required to be done :


1) Create an application in facebook :
Create an application in facebook from the application dashboard (https://developers.facebook.com/apps).


2) Provide the App Domain and Site Url :
After providing the required appname now it is needed to provide the App Domain and Site Url,

i) Set App Domain to your domain eg. ‘myDomain.com’.

ii) Now , go to the section ‘Select how your app integrates with Facebook’ and select ‘Website with Facebook Login’ and provide
your site URL eg. ‘http://www.myDomain.com’.

Note the App ID value , it would be required later.


3) Load the javascript sdk :
Load the javascript sdk now by writing this script in the login page of the application :

[javascript]

<script>
window.fbAsyncInit = function() {
FB.init({
appId : ‘YOUR_APP_ID’, // App ID
channelUrl : ‘//WWW.YOUR_DOMAIN.COM/channel.html’, // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(function (data) {
var jse, id = ‘facebook-jssdk’, ref = data.getElementsByTagName(‘script’)[0];
if (data.getElementById(id)) {
return;
}
jse = data.createElement(‘script’);
jse.id = id;
jse.async = true;
jse.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=YOUR_APP_ID";
ref.parentNode.insertBefore(jse, ref);
}(document));
</script>

[/javascript]

4) Add facebook login button :
Now we are Good to go. We would want that when a user is logged in on facebook , he gets logged in on our site as well.
We can authenticate the user from the information which he has on facebook rather than forcing the user to register for
our site.For this we need facebook to do the authentication part for us.
To do authentication we have to add a Facebook login button in our login page as :

[html]

<div class="fb-login-button">Login with Facebook</div>

[/html]
This provides us the access to user’s basic information.For getting access to more information as Email we need to ask
permissions from the user by mentioning it in a scope attribute as :
[html]
<div class="fb-login-button" scope="email,user_checkins">
Login with Facebook
</div>

[/html]

5) Get information of the authenticated user :
When the user is logged in facebook ,we have the information of the authenticated user.To get that information we do:

[javascript]

FB.Event.subscribe(‘auth.login’, function () {
FB.getLoginStatus(function (response) {
if (typeof(response) == ‘undefined’) {
return
}
else {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
getProfileInfoAndLogin(accessToken);
}

});
});

function getProfileInfoAndLogin(token) {
var url = "${createLink(controller: ‘controllerName’, action: ‘actionName’)}";
FB.api("/me", "GET", function (response) {
$.ajax({
type:"GET",
url:url,
dataType:"html",
data:{fbEmail:response.email}
}).done(function (data) {
alert(data);
if (data == "true") {
// redirect user to his homepage
// eg. window.location = "http://www.example.com/user/home";
}
else {
alert("failure")
}
});
});
}
[/javascript]
In the getProfileInfoAndLogin function, ‘function(response)’ is a callback function through which we can access the data facebook sends after passing validation.When we have the data we can manipulate it as we want.
I have send the user’s email to the server using an Ajax call and checked whether that
Email exists in database and then logged the user into my site as :
[javascript]
def fbLoginCheck() {
String userEmail = params.fbEmail
if (User.countByEmail(userEmail)) { // User is already stored in database
session.userEmail = userEmail
render true
}
}
[/javascript]


6) Logout user :
To log the user out of our site we add this script to the HOME page of user along with the javascript SDK :

[javascript]

function fbLogout(){
FB.logout(function (response) {
// Do what we want to do when user logs out from facebook like call our logout action.
// eg. window.location = "http://www.example.com/logout";
});
}
[/javascript]

The logout button can be added as :
[html]
<span id="fbLogout" onclick="fbLogout()"><a class="fb_button fb_button_medium"><span class="fb_button_text">Logout</span></a></span>
[/html]

Hope this helps.
Cheers. 🙂

Vineet Mishra
Intelligrape software

FOUND THIS USEFUL? SHARE IT

comments (5)

  1. sujata padhi

    My fb account was blocked how can i login. My phone no my email is not work. I think somebody misusing. Please help me

    Reply
  2. 1 Megapixel

    This connectivity will allow you to easily transfer
    photos on to your laptop for storage. If the horse is a good model and stands well
    during his photo op, then work it. As you will see later other considerations like lenses, flash
    and battery are no less important.

    Reply
  3. Gilda

    Equally problematic is Mattie Hawkinson’s Desdemona: nasal of voice and flat in affect, she comes across more as a spoiled suburban brat than the daughter of a criminal kingpin’which is possible.
    Excuse me, I need to go shovel about 18″ of global warming out of my driveway. You’ll be surprised at to how much this small step can help you through your healing process.

    Reply
  4. bagaznik rowerowy

    I have read a few good stuff here. Definitely price bookmarking for revisiting. I surprise how a lot attempt you place to create this sort of excellent informative site.

    Reply
  5. Roxann Osier

    Hey this blog is fantastic i really like studying your posts. Keep up the good paintings! You already know, lots of people are hunting around for this info, you can help them a lot.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *