2015-07-20 56 views
0

我用未認證用戶我如何可以驗證驗證用戶除了會話控制器

我怎麼能擺脫它訪問索引了一個無限循環的所有資源?感謝

錯誤

Started GET "/sessions/new" for 127.0.0.1 at 2015-07-20 18:24:58 +0800 
Processing by SessionsController#new as HTML 
Redirected to http://localhost:3000/sessions/new 
Filter chain halted as :verify_authenticity rendered or redirected 
Completed 302 Found in 5ms (ActiveRecord: 0.0ms) 
cache: [GET /sessions/new] miss 

片段

class ApplicationController < ActionController::Base 
    # Prevent CSRF attacks by raising an exception. 
    # For APIs, you may want to use :null_session instead. 
    protect_from_forgery with: :exception 
    before_action :verify_authenticity, except: [:session] 

    private 
    def verify_authenticity 
     redirect_to sessions_new_url unless current_user 
    end 
end 


class SessionsController < ApplicationController 
    skip_before_action :verify_authenticity 

    def new 
    redirect_to index_url if current_user 
    end 

end 
+0

我相信你有'current_user'的自定義實現,你可以顯示它嗎?如果沒有通過身份驗證的用戶,請確保它返回nil或false,而不是實際的對象! –

回答

1

我不喜歡你

redirect_to index_url if current_user 

檢查驗證用戶的方式,我寧願使用像一個布爾方法current_user?user_logged_in?,返回true或false顯式ely

爲什麼?那麼,因爲在大多數應用程序中,您仍然使用User實例處理未經身份驗證或訪客登錄......所以,你總是有一個current_user實例變量,但也許沒有字段(如login: nil,email: nil)。

current_user認證完全阻撓你if條件的實例:

def current_user 
    if @current_user 
    return @current_user 
    else 
    @current_user = User.new 
    @current_user.try_to_authenticate_with_params 
    end 
end 

因此,基本上,當你調用

redirect_to index_url if current_user 

它總是重定向,因爲current_user會返回一個User對象,這是然後解釋爲true

所以我建議如下:

class ApplicationController 

    before_action :verify_authenticity 

    def verify_authenticity 
     # Your code 
    end 

    def user_signed_in? 
     current_user.is_authenticated? # or whatever 
    end 
    alias :user_logged_in? :user_signed_in? 

class SessionController < ApplicationController 

    skip_before_filter :verify_authenticity 

    def new 
     redirect_to index_url if user_signed_in? 
    end 
+0

感謝您的幫助,我現在就試試。你的意思是'如果COND'是一種不好的風格,幹什麼?我沒有注意到這一點,但是我發現它使得代碼看起來很醜,儘管它保存了文字 – newBike

+0

Nono,'如果cond'不是一個糟糕的樣式,我自己就會使用它。相反,我相信這是你在Ruby中只能做的事情,有時候這樣寫就很自然。至少,處理非常短/簡單的條件時,它可以放在一行上,比如'redirect_to index_url if user_signed_in?'。 –