Skip to content

Instantly share code, notes, and snippets.

@MatthewRDodds
Last active January 20, 2016 22:27
Show Gist options
  • Save MatthewRDodds/d438aae5f0f6411e1197 to your computer and use it in GitHub Desktop.
Save MatthewRDodds/d438aae5f0f6411e1197 to your computer and use it in GitHub Desktop.
Rails 4 Omniauth Facebook and Linkedin Recipe (Clearance)

Prereqs:

Have a User model with these attributes:

  • uid:string
  • provider:string
  • first_name:string
  • last_name:string
  • email:string

Authentication Concern

module Authentication
  extend ActiveSupport::Concern

  included do
    include Clearance::User
  end

  module ClassMethods
    def from_omniauth(auth)
      @user   = User.find_by(provider: auth.provider, uid: auth.uid)
      @user ||= create_new_user_from_auth(auth)

      @user
    end

    def create_new_user_from_auth(auth)
      user = User.where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
        user.provider = auth.provider 
        user.uid = auth.uid
        user.first_name = auth.info.first_name
        user.email = auth.info.email
        user.last_name = auth.info.last_name
      end
    end
  end
end

Gemfile

gem 'omniauth'
gem 'omniauth-facebook'
gem 'omniauth-linkedin'

Omniauth Initializer

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_APP_SECRET'], info_fields: 'first_name,last_name,email'
  provider :linkedin, ENV['LINKEDIN_APP_ID'], ENV['LINKEDIN_APP_SECRET']
end

Controller

class SessionsController < Clearance::SessionsController
  skip_before_action :require_login, only: :handle_omniauth

  def handle_omniauth
    @user = User.from_omniauth(request.env['omniauth.auth'])

    sign_in(@user)

    redirect_to url_for_signed_in_users
  end
end

User Model

class User < ActiveRecord::Base
  include Authentication
end

Route

get '/auth/:provider/callback' => 'sessions#handle_omniauth'

Link in UI

<a href="/auth/facebook">
  <i class="fa fa-facebook"/>
  Log In with Facebook
</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment