Rails会在24小时内过期密码

在我的rails 3.1应用程序中,我想为用户创建并过期随机密码。我正在使用devise gem.Any插件可用于expiring password吗?
或者请给我一些合理的建议来实现这个function。
请认为我是新手。

听起来你只想让密码失效一次。 如果您希望定期(例如每隔几个月)进行一次,或者如果您想阻止用户重新使用密码,则会变得更加复杂。

取自我正在开发的应用程序:

app / models / user.rb(假设你的名字是你的名字):

 def password_should_expire? # your logic goes here, remember it should return false after the password has been reset end 

应用程序/控制器/ application_controller.rb

 before_filter :check_password_expiry def check_password_expiry return if !current_user || ["sessions","passwords"].include?(controller_name) # do nothing if not logged in, or viewing an account-related page # otherwise you might lock them out completely without being able to change their password if current_user.password_should_expire? @expiring_user = current_user # save him for later @expiring_user.generate_reset_password_token! # this is a devise method sign_out(current_user) # log them out and force them to use the reset token to create a new password redirect_to edit_password_url(@expiring_user, :reset_password_token => @expiring_user.reset_password_token, :forced_reset => true) end end 

创建密码时,请记下创建密码的时间。 然后,在使用密码时,请检查密码是否在24小时前创建。

根据您使用的框架,此function(或类似的function)可能已存在于框架内,或者可能已作为插件存在。 如果不是,则实施起来并不是特别困难。 您需要的只是数据存储中的一个额外列,用于保存密码创建日期/时间,以及在密码创建和密码使用方面的一些额外逻辑。

查看Devise Security Extension gem:

https://github.com/phatworx/devise_security_extension

我一直在使用它来过期密码和存档密码(以确保旧密码不被重复使用)没有问题。

@ Jeriko的答案包含一些旧代码,这里是编辑

在model / user.rb中:

  def password_should_expire? if DateTime.now() > password_changed_at + 30.seconds return true; else return false; end end 

在Application Controller中:

  before_filter :check_password_expiry def check_password_expiry return if !current_user || ["sessions","passwords"].include?(controller_name) # do nothing if not logged in, or viewing an account-related page # otherwise you might lock them out completely without being able to change their password if current_user.password_should_expire? @expiring_user = current_user # save him for later @expiring_user.set_reset_password_token! # this is a devise method sign_out(current_user) # log them out and force them to use the reset token to create a new password redirect_to edit_password_url(@expiring_user, :reset_password_token => @expiring_user.reset_password_token, :forced_reset => true) end end