2012-03-19 89 views
2

我指的是這些railscasts在使用Twitter,omniauth並制定實現簽約:在使用Twitter,Omniauth實施註冊,並制定

  1. http://railscasts.com/episodes/235-omniauth-part-1?view=asciicast
  2. http://railscasts.com/episodes/236-omniauth-part-2?view=asciicast

方案:一個twitter用戶來到我的應用程序。點擊Twitter鏈接登錄並轉到/ auth/twitter。他允許我的應用程序在twitter網站上被重定向回我的應用程序。他在我的網站上輸入他的電子郵件ID,因爲這是強制性的。他使用該網站,然後註銷我的應用程序。然後他想重新登錄。他再次點擊Twitter登錄圖標。 我的問題:我預計他不必再次在twitter網站上授權我的應用程序。但事實並非如此。這一次再次,Twitter要求這個用戶授權。

我的代碼如下railscasts準確:從設計

<routes.rb> 
match '/auth/:provider/callback' => 'authentications#create' 


class AuthenticationsController < ApplicationController 
... 
def create 
    omniauth = request.env["omniauth.auth"] 

    authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid']) 

    if authentication 
     flash[:notice] = "Signed in successfully." 
     sign_in_and_redirect(:user, authentication.user) 
    elsif current_user 
     current_user.authentications.create(:provider => omniauth['provider'], :uid => omniauth['uid']) 
     flash[:notice] = "Authentication successful." 
     redirect_to authentications_url 
    else 
     user = User.new 
     user.apply_omniauth(omniauth) 
     if user.save 
     flash[:notice] = "Signed in successfully." 
     sign_in_and_redirect(:user, user) 
     else 
     session[:omniauth] = omniauth.except('extra') 
     redirect_to new_user_registration_url 
     end 
    end 
    end 
... 
end 

用戶模型修改爲:

class User < ActiveRecord::Base 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me 
    has_many :authentications 

    def apply_omniauth(omniauth) 
     authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid']) 
    end 

    def password_required? 
     (authentications.empty? || !password.blank?) && super 
    end 
end 

什麼我需要做的,以確保恢復不會向用戶詢問授權我的應用程序每次他/他被重定向到/ auth/twitter?

+0

而我的omniauth初始化器看起來像:'Rails.application.config.middleware.use OmniAuth :: Builder do provider:twitter, ******************* ****, *********************** end' – 2012-03-19 11:29:14

回答

0

如果您按照關於devise和omniauth的ryan bates強制轉換,則您的用戶模型應該在用戶和身份驗證之間建立關聯。

用戶模型需要的是這樣的: 的has_many:認證

你的routes.rb文件還需要的ressource:

匹配 '/ auth /中:供應商/回調'=> '認證#創建'

devise_for:用戶:控制器=> {:會話=> '會話',:註冊=> '註冊'}

資源:認證

希望這會有所幫助。

問候 月