Skip to content

Authlogic Omniauth Facebook

brunopgalvao edited this page Dec 25, 2014 · 1 revision

Thought this would be helpful as I ran into some obstacles implementing this on Rails 3. Here is how I did it:

Followed these resources:

https://github.com/mkdynamic/omniauth-facebook

http://raycodingdotnet.wordpress.com/2013/10/03/using-omniauth-and-authlogic-for-user-registration-creating-social-network-on-ruby-on-rails-day-12/

https://coderwall.com/p/bsfitw

http://richonrails.com/articles/facebook-authentication-in-ruby-on-rails

This seemed to work for me.

acts_as_authentic do |c|
  c.login_field = :email
  c.validate_email_field = true
  c.validate_login_field = false
  c.ignore_blank_passwords  = true
  c.validate_password_field = false
end

....

def self.from_omniauth(auth)
  where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
    user.provider = auth.provider
    user.uid = auth.uid
    user.first_name = auth.info.first_name
    user.last_name = auth.info.last_name
    user.name = auth.info.name
    user.email = auth.info.email
    user.oauth_token = auth.credentials.token
    user.oauth_expires_at = Time.at(auth.credentials.expires_at)
    user.save!
  end
end

def self.existing_user_from_omniauth(auth, user)
  user.provider = auth.provider
  user.uid = auth.uid
  user.oauth_token = auth.credentials.token
  user.oauth_expires_at = Time.at(auth.credentials.expires_at)
  user.save
end

Had to change these columns:

change_column :users, :crypted_password, :string, :default => nil, :null => true
change_column :users, :password_salt, :string, :default => nil, :null => true

Also had to tweak validations in the user model i.e. validates_presence_of :password

Then had to change my controller to look like this:

def create
  if current_user
    # add facebook to their already existing account
    User.existing_user_from_omniauth(env["omniauth.auth"], current_user)
    user = UserSession.find.user
    if user
      flash[:notice] = 'You successfully connected your Facebook account!'
    end
  elsif params.has_key?(:user_session)
    # email/password authentication
    @user_session = UserSession.new(params[:user_session])
    if @user_session.save
      user = UserSession.find.user
      flash[:notice] = 'You successfully logged in. Welcome back!'
    end
  else
    # facebook authentication
    begin
      user = User.from_omniauth(env["omniauth.auth"])
    rescue
      flash[:notice] = 'An account with this email already exists. Please login with your email and click "Connect with Facebook"'
      redirect_to new_session_path and return
    end
    @user_session = UserSession.create(user, true)
    if @user_session.save
      flash[:notice] = 'Welcome!'
    end
  end

Also had to change my before_filter to allow existing users to connect with facebook using the create action.

Clone this wiki locally