如何使用Devise停止软删除用户的登录

我目前在Rails项目中使用Devise进行用户注册/身份validation。 当用户想要取消其帐户时,将以如下方式软删除用户对象。

如何用Devise“软删除”用户

我的implmenetation这种方式有一点不同。 用户模型具有属性’deleted_flag’。 并且,soft_delete方法执行“update_attribtue(:deleted_flag,true)”

但是,我必须实施sign_in行动。 我的主要内容如下。

class SessionsController  resource_name, :recall => "#{controller_path}#new") if resource.deleted_flag p "deleted account : " + resource.deleted_flag.to_s sign_out(resource) render :controller => :users, :action => :index else if is_navigational_format? if resource.sign_in_count == 1 set_flash_message(:notice, :signed_in_first_time) else set_flash_message(:notice, :signed_in) end end sign_in(resource_name, resource) respond_with resource, :location => redirect_location(resource_name, resource) end end end 

我认为这段代码有点奇怪。

如果已删除的用户尝试进入,则系统会允许记录并立即注销。 并且,系统无法显示flash [:alert]消息…

我想知道两点。

  1. 如何实施禁止已删除的用户登录?
  2. 当被删除的用户尝试登录时,如何实现显示flash [:alert]?

要停止已被“软删除”的用户,最好的方法是覆盖用户模型上的find_for_authentication类方法。 如:

 Class User < ActiveRecord::Base def self.find_for_authentication(conditions) super(conditions.merge(:deleted_flag => false)) end 

这将通过设计生成无效的电子邮件或密码flash消息(因为它无法找到用户进行身份validation)

至于你的第二个问题,你需要一些控制器中的方法来添加特定的flash消息。 但是,在我看来,您应该将“软”删除的用户视为完全不存在于数据库中。 因此,如果他们尝试登录,他们应该只获得有效的电子邮件或密码消息。

请在此处查看我的解决方案: https : //stackoverflow.com/a/24365051/556388基本上您需要覆盖active_for_authentication? 设计模型上的方法(用户)。

我没有尝试过类似的东西,但似乎你想在认证之前抓住用户,你要么必须编写一个Devise认证策略,要么在authenticate_user!之前运行before_filter authenticate_user! 。 就像是:

 before_filter :no_deleted_users def no_deleted_users if User.find(params[:email]).deleted? redirect_to root_path, :flash => { :error => "Your user was deleted. You cannot log in." } end end 

虽然获得用户可能比这更复杂。 我没有玩过Devise预认证。