我正在尝试重构 railstutorial 授权机制。
我的 rails 版本是 3.2.0,我使用的是 ruby 1.9.3-p0 和 postrgresql 9.1。
到目前为止,当尝试登录失败但成功登录失败时,我的测试通过了。(原因是我必须重构旧的登录机制)
这是我的会话助手登录功能:
def sign_in(employee)
cookies.permanent.signed[:remember_token] = [employee.id, employee.salt]
self.current_employee = employee
end.
我立即看到sign_in 函数的一个问题是has_secure_password 已经处理了加密和salt 等……我的想法是也许我应该使用password_digest 而不是employee.salt,但这也失败了。
我想让我的 cookie 在两个小时后过期。我在 api.rubyonrails.org 的 cookie 下找到了这个选项。
cookies[:key] = {
value => "employee.id, employee.salt",
expires => 2.hours.from.now
}
我的另一个问题与 has_secure_password 已经有一个 authenticate 方法这一事实有关,这意味着我不必使用 rails 教程中定义的员工模型(用户模型)中定义的身份验证定义,但是当我评论它时我得到一个标志阅读:
NoMethodError: undefined method 'authenticate'
这是我的会话控制器创建操作:
def create
employee = Employee.authenticate(params[:session][:email],
params[:session][:password])
if employee.nil?
flash.now[:error] = "Invalid email/password combination."
@title = "Sign in"
render 'new'
else
sign_in employee
redirect_back_or employee
end
end
看来 Employee.authenticate 是个问题。
所以我基本上有三个问题,它们如下:
在 Rails 教程中,我们经历了一个相当长的过程,对员工密码进行加密和应用 salt 等。由于 has_secure_password 已经解决了这个问题,我将传递什么变量给我的函数或参数来捕获加密密码?
下一个问题与 cookie 的到期有关,我将如何在 sign_in 函数中使用它?
最后,我如何使用 authenticate 方法才能让 rails 将其识别为真正的方法?
只是为了记录,我搜索了 railsguide、api.rubyonrails.org 和其他关于 SO 的与此类似的问题。当然,这只是指出我对原理缺乏了解,但我正在学习并且确实很好地指导了方向。
感谢您与我分享的任何想法、建议和资源。
更新 我重新阅读了 has_secure_password 上的 api,并且 authenticate 只需要一个参数,即未加密的密码......所以我有一些东西可以使用。
我仍然需要您提供的任何帮助、想法或建议……谢谢。
更新 我发现这篇文章处理会话超时: http: //madkingsmusings.blogspot.com/2011/05/session-timeouts-on-rails.html 我仍在努力,看看我是否可以让它为我工作,但它是为 railstutorial 量身定制的。至于其他问题,Michael Hartl 正忙于推出 Ruby on Rails 教程的第二版,在该版本中,他将处理 has_secure_password。