2014年7月1日 星期二

devise omniauth-fb carrierwave 登入


安裝 gem
/Gemfile
gem "devise" gem "omniauth-facebook"
設定 devise
/config/initializiers/devise.rb
config.omniauth :facebook, Settings.story.fb_app_id, Settings.story.fb_secret, {:provider_ignores_state => true}
add the omniauthable model to the devise method in our User model.
/app/models/user.rb
class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :omniauthable, :recoverable, :rememberable, :trackable, :validatable end
如此會產生兩個routes
user_omniauth_authorize
GET|POST /users/auth/:provider(.:format) omniauth_callbacks#passthru {:provider=>/facebook/}
user_omniauth_callback GET|POST /users/auth/:action/callback(.:format) omniauth_callbacks#(?-mix:facebook)
建立一個omniauth_callbacks的controller來處理以上的這些資訊
設定
/routes.rb
devise_for :users, controllers: {omniauth_callbacks: "omniauth_callbacks"}
/app/controllers/omniauth_callbacks_controller.rb
1 class OmniauthCallbacksController < Devise::OmniauthCallbacksController 2 3 def all 4 user = User.from_omniauth(request.env["omniauth.auth"]) 5 if user.persisted? 6 sign_in_and_redirect user, notice: "Signed in!" 7 else 8 session["devise.user_attributes"] = user.attributes 9 redirect_to new_user_registration_url 10 end 11 end 12 13 alias_method :facebook, :all 14 end
user要多增加欄位來存provider和uid
增加上述的from_omniauth
/app/models/user.rb
19 def self.from_omniauth(auth) 20 where(auth.slice(:provider, :uid)).first_or_create do |user| 21 user.provider = auth.provider 22 user.uid = auth.uid 23 user.email = auth.info.email 24 user.name = auth.info.name 25 user.remote_image_url = auth.info.image.gsub('http://','https://') 26 end 27 end
增加new_with_session
/app/models/user.rb
29 def self.new_with_session(params, session) 30 if session["devise.user_attributes"] 31 new(session["devise.user_attributes"], without_protection: true) do |user| 32 user.attributes = params 33 user.valid? 34 end 35 else 36 super 37 end 38 end
password_required?
/app/models/user.rb
40 def update_with_password(params, *options) 41 if encrypted_password.blank? 42 update_attributes(params, *options) 43 else 44 super 45 end 46 end 47 48 def password_required? 49 super && provider.blank? 50 end 51 52 def email_required? 53 super && provider.blank? 54 end

沒有留言:

張貼留言