【问题标题】:Whitelisting with devise使用设计列入白名单
【发布时间】:2011-03-02 12:40:01
【问题描述】:

我正在使用 devise 来管理我的 rails 应用程序中的用户身份验证。设计非常适合。

但是我对我的应用程序有一个特殊要求:用户必须被列入白名单才能注册为用户。

所以有一个管理员可以创建允许的电子邮件列表。用户使用电子邮件注册,如果该电子邮件在白名单表中,他将被注册。但是,如果该邮件不在白名单中,则应中止注册,并显示“您尚未被邀请”之类的消息。

你知道如何用设计解决这个问题吗?

提前致谢。

【问题讨论】:

    标签: ruby-on-rails authentication devise whitelist


    【解决方案1】:

    我只会使用模型验证。我假设您的 User 类具有设计方法

    class User < ActiveRecord::Base
      devise :database_authenticatable, :registerable #etc
    
      before_validation :whitelisted
    
      def whitelisted
        unless celebrityemail.include? email
          errors.add :email, "#{email} is not on our invitation list"  
        end
      end 
    
    end
    

    【讨论】:

    • 如果您想在错误消息中显示实际的电子邮件,您将如何更改此代码?
    • @Magne errors.add :email, "is not on our invitation list: #{email}"
    【解决方案2】:

    您可以做的是创建自己的注册控制器并扩展设备,例如:

    class MyRegistrationController < Devise::RegistrationsController
      def create
        # do your checks
        super
      end
    end
    

    见:https://github.com/plataformatec/devise/blob/master/app/controllers/devise/registrations_controller.rb 还有:https://github.com/plataformatec/devise/wiki/How-to:-Customize-routes-to-user-registration-pages

    祝你好运!

    【讨论】:

      【解决方案3】:

      我确实按照建议创建了自己的控制器:

      class Users::RegistrationsController < Devise::RegistrationsController
          def create
              email = params[:user][:email]
              if Admin::Whitelist.find_by_email(email) != nil
                  super
              else
                  build_resource
      
                  set_flash_message :error, "You are not permitted to sign up yet. If you have already payed your registration fee, try again later."
                  render_with_scope :new
              end
          end
      end
      

      我把它放在app/users/registrations_controller.rb。然后我不得不将设计注册视图复制到app/views/users/registrations,因为没有使用默认视图。

      现在可以了,谢谢你的帮助

      【讨论】:

        猜你喜欢
        • 2015-01-04
        • 2015-03-29
        • 2017-10-05
        • 2012-10-06
        • 2018-12-24
        • 2021-12-08
        • 2012-05-15
        • 2017-02-25
        • 1970-01-01
        相关资源
        最近更新 更多