intridea-omniauth
#config/intitializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter, 'CONSUMER_KEY', 'CONSUMER_SECRET'
provider :facebook, 'APP_ID', 'APP_SECRET'
provider :linked_in, 'CONSUMER_KEY', 'CONSUMER_SECRET'
end
# config/routes.rb
match '/auth/:provider/callback', :to => 'sessions#create'
rails g controller sessions
class SessionsController < ApplicationController
def create
render :text => request.env['rack.auth'].inspect
end
end
rails g model authorization provider:string uid:string user_id:integer
class User < ActiveRecord::Base
scope :authorization, ->(param) {joins(:authorizations).readonly(false).where(['authorizations.provider = ? and authorizations.uid = ?', param[:provider],param[:uid]])}
has_many :authorizations, :dependent => :destroy
def create_oauth_user(param= {})
if param[:provider].present? and param[:uid].present?
ActiveRecord::Base.transaction do
self.save
authorization = self.authorizations.new(provider: param[:provider], uid: param[:uid])
authorization.save
end
end
end
end
class Authorization < ActiveRecord::Base
belongs_to :user
validates_presence_of :user_id, :uid, :provider
validates_uniqueness_of :uid, :scope => :provider
end
#is omniauth user
@user=User.authorization(provider: session[:omniauth],uid: session[:uid]).first and @user.present?
#create omniauth user
@user=User.new(:email => params[:email], :password => Devise.friendly_token[0,20])
@user.create_oauth_user({provider: session[:omniauth], uid: session[:uid]})#return true or false