Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify the user logged via Facebook api?

Tags:

facebook

i I can not understand one thing..

On my website there is a button with FB.login method from facebook's api JS SDK.

When the user first visits my website, clicks on the button - get some data from his facebook's profile, and then we'll check at my server in the database is there user with this id, or not? If no - write a new row. Also we create the user's profile on my website.

Now the question, when the next time the user visits our website (and clicks on a button, if he is not logged in) - how to identify him to combine with his profile on our website? For example, to show him his profile, or that he could change anything in it...

In the usual authorization we compare the password and user's login in the database, here is no such possibility. AccessToken changes all the time. Thought just check user's FB id, but then, perhaps, anyone will be able to substitute his FB id, and enter in his profile, is not it?

What tricks are used in this case?

like image 782
Denis Avatar asked Mar 26 '12 16:03

Denis


2 Answers

Regardless if user visits your site first time or not you always use the FB.login method. This method validates if the user has relation with your application and gives you an access token when the user has accepted your app.

When using facebook login to authenticate users, the user register in your database does not contain password, you only have facebookid to relate facebook account with the profile of your website. The facebook id can be obtained using the accesstoken provided by FB.login method in the server side or through javascript like next example taken of facebook docs.

FB.login(function(response) {
if (response.authResponse) {
   console.log('Welcome!  Fetching your information.... ');
   FB.api('/me', function(response) {
      console.log('Good to see you, ' + response.name + '.');
   });
 } else {
   console.log('User cancelled login or did not fully authorize.');
 }
});

In the response object you can get the facebook id (response.id).

like image 95
diegoe Avatar answered Sep 18 '22 02:09

diegoe


If you query the Graph API https://graph.facebook.com/me?access_token=USER_ACCESS_TOKEN you will get the UID and then compare with your DB. You are using the Javascript API so, you should use the FB.getLoginStatus method in order to get the UID for the connected user.

https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

This method is run by default when initializing the SDK with FB.init (status: true). It enables your site to recognize already connected user.

https://developers.facebook.com/docs/reference/javascript/FB.init/

like image 32
Alexcode Avatar answered Sep 20 '22 02:09

Alexcode