Search code examples
ruby-on-rails-3facebook-javascript-sdksorcery

How to use the Facebook JavaScript SDK with the sorcery gem


I followed the guide provided here by Sorcery about handling user logins with Facebook.

# callback method called by Facebook after getting the authorization by the user
if user = login_from(provider) # provider == "facebook"
  redirect_to root_path #, :notice => "Logged in from #{provider.titleize}!"
else
  begin
    user = create_from(provider)
    ...

However it only requires that my users leave my site to go to the Facebook page and then get redirected here.

What I would like to achieve is what I see when using the Facebook JavaScript SDK which is a clean popup right in my page. To achieve this I followed a tutorial on Railscasts:

$('#sign_in').click (e) ->
  e.preventDefault()
  FB.login (response) ->
    window.location = '/auth/facebook/callback' if response.authResponse

However, the authResponse only contains an accessToken and a signedRequest and a userid while Sorcery requires a code.

Is there anyway to do this properly (or get the code using the accessToken?).


Solution

  • However, the authResponse only contains an accessToken and a signedRequest and a userid while Sorcery requires a code.

    Is there anyway to do this properly (or get the code using the accessToken?).

    In the server-side flow, the code is just an intermediate step in getting the access token – app gets code, and exchanges code for an access token.

    Since in the client-side flow you already get an access token when it’s finished – it does not get any more “proper” than that.

    So you have two options:

    • either refactor your Sorcery-thingie, so that it skips the step where it gets a code and exchanges that for an access token, and directly “set” the access token yourself after getting it (wherever Sorcery might want it to be set); or

    • stick to the server-side flow, but open that yourself in a popup window. Then you’ll still get the code, but you’ll get it inside the popup window. So you’d have to close the popup window and maybe reload your original window yourself afterwards.