Search code examples
ruby-on-railscallbackomniauth

What are callbacks doing in omniauth-facebook integration?


Documentation on omniauth-facebook mentions callbacks a lot, but I don't see callbacks inside the documentation, and I didn't need to write any callbacks (in the Javascript sense I'm used to) to make the authentication work.

Documentation: https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview

For example:

By clicking on the above link, the user will be redirected to Facebook. (If this link doesn't exist, try restarting the server.) After inserting their credentials, they will be redirected back to your application's callback method.

devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }

Callbacks Controller

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

  def failure
    redirect_to root_path
  end
end

I don't see any explicitly written callbacks here so I assume there is something going on behind the scenes.

But I'm kind of confused - what are the callbacks actually doing and what part of this code is a callback?

Apologies in advance if this is a super newbie question.


Solution

  • A callback in OmniAuth is the return url where the user is redirected after authentication - its the endpoint where the external service calls your application back. The term "callback" is quite frequently used this way when it comes to server side programming.

    So in this case Users::OmniauthCallbacksController#facebook is the 'callback' handler for this authentication provider.

    This is quite a different concept than the JavaScript concept of callbacks which is event oriented programming by passing functions around.