Beta (Whitelisted) Email List for Registration on Devise

空扰寡人 提交于 2019-12-23 05:19:32

问题


I'm Using Devise and i'm trying to build a requirement that only emails that are included in my white list can actually Sign Up.

Over Time emails will be added to that list. Meaning that Today there are 10 emails, tomorrow another 20+.

But i don't know quite yet how to achieve this.

I know that i have to Create my own Registrations Controller, and for the Validation i think i need something similar to this:

before_validation :whitelisted?

def whitelisted?
  unless WhiteList.exists?(:email => email)
    errors.add :email, "is not on our beta list"  
  end
end 

However, i am clueless on how to start or continue this. I don't even know if that's the best Practice.

How do i add emails to that whitelist and where is even that whitelist?

If someone could be noob-friendly enough to explain this to me.


回答1:


Try the following i think this could help you.

create new registration controller

class RegistrationsController < Devise::RegistrationsController

  def create
    unless WhiteList.exists?(:email => params[:user][:email])
      errors.add :email, "is not on our beta list"
    else
      super  
    end
  end
end

and in routes file replace existing with following

devise_for :users, controllers: { registrations: "registrations" }

Create new model WhiteList using following

rails g model whitelist email:string

and run rake db:migrate command.

after this start Rails console add email's using following command.

Whitelist.create(email: "test@user.com")



回答2:


I found @Amit Sharma's answer useful, but it doesn't work straight out of the box. Here's what I came up with:

class RegistrationsController < Devise::RegistrationsController
  def create
    if WhiteList.exists?(:email => params[:user][:email].downcase)
      super
    else
      flash[:error] = "Your email is not on our beta list."
      redirect_to new_user_registration_path
    end
  end
end

class WhiteList < ActiveRecord::Base
  before_save :downcase_email
  validates :email, presence: true

  def downcase_email
    self.email = email.downcase
  end
end

This solves for case sensitivities when whitelisting an email and produces a flash error message when a Whitelisted email isn't matched.



来源:https://stackoverflow.com/questions/19131220/beta-whitelisted-email-list-for-registration-on-devise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!