使用Devise for Rails禁止/阻止用户的最佳方法是什么?

rxb*_*rxb 13 ruby authentication ruby-on-rails registration devise

我在我的rails应用程序中使用Devise进行身份验证,我希望能够阻止某些帐户并阻止用户使用阻止的电子邮件重新注册.我只是不确定最好的方法是什么.

我的第一个想法是覆盖会话和注册控制器来检查具有阻塞位的用户的模型,但我感觉可能有更优雅的方式.

sam*_*mpi 24

最好的方法是以Devise方式执行:

下面假设您正在使用Devise database_authenticable模块,并且您的应用程序的用户模型名称为User.

1.实施account_active?方法.

account_active在users表中添加boolean 列或account_active?在User模型中定义方法(您可以选择自己的方法名称).例如:

    # app/models/user.rb
    def account_active?
      blocked_at.nil?
    end
Run Code Online (Sandbox Code Playgroud)

2.覆盖active_for_authentication?模型中的方法(用户).

    # app/models/user.rb
    def active_for_authentication?
      super && account_active?
    end
Run Code Online (Sandbox Code Playgroud)

3.添加返回flash消息翻译的方法.

每当active_for_authentication?返回false时,Devise会使用该inactive_message方法询问模型处于非活动状态的原因.

    # app/models/user.rb 
    def inactive_message
      account_active? ? super : :locked
    end
Run Code Online (Sandbox Code Playgroud)

就是这样.您无需关心sign_outredirect_to使用.

此外,用户会在下次请求时立即锁定,而不是在下次登录后锁定.

更多:devise/authenticatable.rb.


小智 12

我会这样做:

def after_sign_in_path_for(resource)
  if resource.is_a?(User) && resource.banned?
    sign_out resource
    banned_user_path
  else
   super
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这有一个缺点:如果用户在他们已经登录时被禁止,禁令将在他们退出并重新登录之后才会生效(这可能需要很长时间.)因此要么强迫用户在禁用它们时注销,或者将此逻辑移动到控制器中的`before_action`而不是使用`after_sign_in_path_for`. (2认同)

iwi*_*nia 5

更好的解决方案是覆盖active_for_authentication?设计模型上的方法(用户).像这样:

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