Have a User model with these attributes:
- uid:string
- provider:string
- first_name:string
- last_name:string
- email:string
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
gem 'omniauth'
gem 'omniauth-facebook'
gem 'omniauth-linkedin'
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
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
class User < ActiveRecord::Base
include Authentication
end
get '/auth/:provider/callback' => 'sessions#handle_omniauth'
<a href="/auth/facebook">
<i class="fa fa-facebook"/>
Log In with Facebook
</a>