【问题标题】:What is the best way to ban/block users with Devise for Rails?使用 Devise for Rails 禁止/阻止用户的最佳方法是什么?
【发布时间】:2010-10-08 23:14:14
【问题描述】:

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

我的第一个想法是重写会话和注册控制器,以检查模型是否存在阻塞位的用户,但我觉得可能有更优雅的方法。

【问题讨论】:

    标签: ruby-on-rails ruby authentication registration devise


    【解决方案1】:

    最好的方法是设计方式

    下面假设您正在使用设计 database_authenticable 模块和您的应用程序的用户模型名称 User。

    1.实现一个 account_active? 方法。

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

        # app/models/user.rb
        def account_active?
          blocked_at.nil?
        end
    

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

        # app/models/user.rb
        def active_for_authentication?
          super && account_active?
        end
    

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

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

        # app/models/user.rb 
        def inactive_message
          account_active? ? super : :locked
        end
    

    就是这样。您无需关心sign_outredirect_to 用户。

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

    更多:devise/authenticatable.rb.

    【讨论】:

    • 请你告诉每个代码块的每个文件是什么?
    • @AymanSalah 按要求完成。所有三个方法都需要放在app/models/user.rb 中(假设 user.rb 是你的模型负责应用程序的用户)
    • 完美运行!
    【解决方案2】:

    我会这样做:

    def after_sign_in_path_for(resource)
      if resource.is_a?(User) && resource.banned?
        sign_out resource
        banned_user_path
      else
       super
      end
    end
    

    【讨论】:

    • 请注意,这有一个弱点:如果用户在已经登录的情况下被禁止,则该禁止将在他们退出并重新登录之前生效(这可能需要很长时间.) 因此,要么在您禁止用户时强制用户注销,要么将此逻辑移至控制器中的before_action,而不是使用after_sign_in_path_for
    • 当你禁止用户时,只需再添加一行即可将其注销
    【解决方案3】:

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

        def active_for_authentication?
          super && !self.banned?
        end
    

    【讨论】:

      猜你喜欢
      • 2011-01-21
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多