2012-04-23 76 views
2

我正在開發基於Rails應用程序的身份驗證系統。身份驗證使用net-ldap類從Active Directory驗證帳戶信息(此部分工作正常)。基本ruby on rails身份驗證問題

但是,我的session_helper似乎有問題。即使ActiveDirectoryUser.authenticate成功,signed_in助手始終返回false。登錄後,腳本重定向到root_path(default_controller的主目錄),然後再次重定向到signin_path--由於signed_in助手返回false。

請參閱下面的代碼。我錯過了什麼?

感謝

application_controller.rb

class ApplicationController < ActionController::Base 
    protect_from_forgery 
    include SessionsHelper 
end 

default_controller.rb

class DefaultController < ApplicationController 
    before_filter :signed_in_user 

    def home 
    end 

    private 
    def signed_in_user 
     redirect_to signin_path, notice: "Please sign in." unless signed_in? 
    end 
end 

sessions_helper.rb

module SessionsHelper 
    def sign_in(user) 
    @current_user = user 
    end 

    def current_user 
    @current_user ||= nil 
    end 

    def signed_in? 
    [email protected]_user.nil? 
    end 

    def sign_out 
    @current_user = nil 
    end 
end 

sessions_controller.rb

class SessionsController < ApplicationController 
    def new 
    end 

    def create  
    user = ActiveDirectoryUser.authenticate(params[:session][:username],params[:session][:password]) 

    if user.nil? 
     # authentication failed 
     flash.now[:error] = 'Invalid email/password combination' 
     render 'new' 
    else 
     # authentication succeeded 
     sign_in @user 
     flash[:error] = 'Great success' 
     redirect_to root_path 
    end 
    end 

    def destroy 
    sign_out 
    redirect_to root_path 
    end 
end 
+1

你如何保存用戶登錄成功的事實?我沒有看到任何會話存儲此信息的調用。 – heavysixer 2012-04-23 22:01:01

+0

由於我對rails的理解有限,是不是通過sessions_controller.rb中的'sign_in user'來傳遞?用戶對象是從LDAP類輸出創建的,然後傳遞給sign_in幫助器 - sign_in幫助器應該創建一個全局範圍爲 – samJL 2012-04-23 22:35:17

+1

的current_user對象是的,你必須在會話內部保存一些信息,通過存儲它在數據庫或餅乾。 – heavysixer 2012-04-23 23:17:01

回答

0

您應該使用會話堅持那種數據(將課稅爲每個請求),它的用戶數據。但我強烈建議你使用諸如設計寶石,這些寶石可以爲你做所有的認證事情。爲什麼重塑這個偉大的權利?

我相信這會適合你。

module SessionsHelper 
    def sign_in(user) 
    session[:user_id] = user.id 
    end 

    def current_user 
    ActiveDirectoryUser.find(session[:user_id]) ||= nil 
    end 

    def signed_in? 
    !session[:user_id].nil? 
    end 

    def sign_out 
    session[:user_id] = nil 
    end 
end 
+0

這個傢伙剛剛起步,所以我猜他是在學習。儘管如此,我並不是設計師的忠實粉絲 – andy 2013-01-21 09:06:46