我正在为一个rails应用程序开发一个基本的身份验证系统。 身份验证是使用 net-ldap 类验证来自 Active Directory 的帐户信息(此部分工作正常)。
然而,我的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?
!@current_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
您应该使用 session for 来保存此类数据(对于每个请求都可以评估),它是用户数据。但我强烈建议您使用类似 设计宝石 的东西,它可以为您完成所有身份验证以及更多操作。为什么要重新发明右边?
我相信这对你有用。
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