any one know how to find a session by a session_id on RoR? I'm using Authlogic in my project i don't know if that is correlated
问问题
769 次
1 回答
1
我自己不必这样做,而且我不确定为什么有人可能需要这样做。
通过查看源代码,我可以看到可能有一种方法可以做到这一点。
在 Authlogic::Session::Persistence 模块中有一个 find 方法。您可以使用 UserSession.find 调用此方法,它似乎可以根据 session_id 进行搜索
# This is how you persist a session. This finds the record for the current session using
# a variety of methods. It basically tries to "log in" the user without the user having
# to explicitly log in. Check out the other Authlogic::Session modules for more information.
#
# The best way to use this method is something like:
#
# helper_method :current_user_session, :current_user
#
# def current_user_session
# return @current_user_session if defined?(@current_user_session)
# @current_user_session = UserSession.find
# end
#
# def current_user
# return @current_user if defined?(@current_user)
# @current_user = current_user_session && current_user_session.user
# end
#
# Also, this method accepts a single parameter as the id, to find session that you marked with an id:
#
# UserSession.find(:secure)
#
# See the id method for more information on ids.
def find(id = nil, priority_record = nil)
session = new({:priority_record => priority_record}, id)
session.priority_record = priority_record
if session.persisting?
session
else
nil
end
end
end
该方法的文档是指 Authlogic::Session 类。
在 Authlogic::Session::Session::Config 中,它表示会话密钥可以是 cookie 密钥、字符串或符号。
module Config
# Works exactly like cookie_key, but for sessions. See cookie_key for more info.
#
# * <tt>Default:</tt> cookie_key
# * <tt>Accepts:</tt> Symbol or String
def session_key(value = nil)
rw_config(:session_key, value, cookie_key)
end
alias_method :session_key=, :session_key
end
因此,在下面的方法中,它试图找到当前会话,我们可以看到如果 record_id 不为零,那么它会使用该键查找会话。
def persist_by_session
persistence_token, record_id = session_credentials
if !persistence_token.nil?
# Allow finding by persistence token, because when records are created the session is maintained in a before_save, when there is no id.
# This is done for performance reasons and to save on queries.
record = record_id.nil? ?
search_for_record("find_by_persistence_token", persistence_token) :
search_for_record("find_by_#{klass.primary_key}", record_id)
self.unauthorized_record = record if record && record.persistence_token == persistence_token
valid?
else
false
end
end
record_id 是使用 session_credentials 方法创建的。这似乎是根据提供给控制器的密钥构建会话密钥
def session_credentials
[controller.session[session_key], controller.session["#{session_key}_#{klass.primary_key}"]].compact
end
def session_key
build_key(self.class.session_key)
end
我通过浏览Github上的源代码收集了大部分内容。如果您需要更多帮助,那可能是开始寻找的最佳地点。
希望这可以帮助
于 2009-11-12T21:13:33.090 回答