Rails + Devise - 有没有办法让用户无法登录或重置密码?

AnA*_*ice 34 ruby-on-rails devise ruby-on-rails-3

由于设计我有很多用户,我想禁止一些问题制定者.Devise是否内置了这种支持?

谢谢

小智 85

authenticatable doku for authenticatable.rb:

在验证用户和每个请求之前,Devise通过调用model.active_for_authentication?来检查您的模型是否处于活动状态.其他设计模块会覆盖此方法.例如,:确认覆盖.active_for_authentication?如果您的模型已确认,则仅返回true.

你自己覆盖这个方法,但是如果你这样做,别忘了给super打电话:

def active_for_authentication?
  super && special_condition_is_valid?
end
Run Code Online (Sandbox Code Playgroud)

因此,当您blocked在用户数据库中有一个标志时,用户模型中的方法如下所示:

def active_for_authentication?
  super && !self.blocked
end
Run Code Online (Sandbox Code Playgroud)

  • 是的,我认为这种方法是最好的一种"阻止"策略,谢谢弗兰克! (3认同)
  • 要使用此方法自定义向用户显示的错误消息,请编辑`config/locales/devise.en.yml`并编辑en> devise> failure> inactive下的值 (3认同)
  • 如果您不想使用`inactive`失败消息,您也可以通过覆盖`inactive_message`来添加自定义消息,如[here]所示(https://github.com/plataformatec/devise/blob/master/ LIB /色器件/模型/ authenticatable.rb#L50). (2认同)

Sha*_*non 31

我自己在项目中实现了这一点.我所做的与上面的Kleber类似,我在app/controllers/sessions_controller.rb(重写Devise)中定义了这个...

class SessionsController < Devise::SessionsController

protected

  def after_sign_in_path_for(resource)
    if resource.is_a?(User) && resource.banned?
      sign_out resource
      flash[:error] = "This account has been suspended for violation of...."
      root_path
    else
      super
    end
   end

end
Run Code Online (Sandbox Code Playgroud)

然后我向用户添加了一个名为'banned'的布尔列,以便主持人在后端编辑用户时选中复选框,布尔值将返回true.

但是有一个缺陷......如果用户已经登录然后被禁止,他们仍然可以访问网站上的内容(评论等),至少在他们的会话到期或他们退出之前.所以我在app/controllers/application_controller.rb中做了这个...

class ApplicationController < ActionController::Base
  before_filter :banned?

  def banned?
    if current_user.present? && current_user.banned?
      sign_out current_user
      flash[:error] = "This account has been suspended...."
      root_path
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

如果检测到禁令,它会自动注销.无论如何,不​​确定这整个事情是影响整个事情的"最佳"方式,因为我对Rails更新,但整个事情对我有用,并希望它至少会给你一个良好的开端.

  • +1很棒!我认为不必覆盖after_sign_in_path_for。只需在应用程序控制器中实现before_filter,但after_sign_in_path_for可能对某些人有用。谢谢。 (2认同)