Search code examples
ruby-on-railsrubydevise

How can I configure my app to allow only specific emails to register with devise?


I'm setting up a CRUD feature and I only want a few people (entire email addresses) to be able to register through devise.

I've gone through countless posts but they mostly use email domains or single person login. I've also tried creating my own validation method in my User.rb but I can't seem to get it.

validate :check_email

  private

  def check_email
    @users = User.all

    if @users == '123.example@gmail.com')
        events_path
    else
        errors.add(:email, 'is not authorized')
    end
  end

I don't get an explicit error but the app seems to skip my 'if' condition and outputs the 'else' condition.


Solution

  • To allow only users with certain email addresses you could simply add an inclusion validation.

    class User < ApplicationRecord
      ALLOWED_EMAILS = %w[
        123.example@gmail.com
        456.example@gmail.com
        789.example@gmail.com
      ].freeze
    
      validates :email, inclusion: { in: ALLOWED_EMAILS, message: :invalid }
    
      # ...
    end
    

    You could also opt to load the ALLOWED_EMAILS from the settings or a file.


    To load from the Rails config you have to define the email addresses in a config file.

    config.allowed_user_emails = %w[
      123.example@gmail.com
      456.example@gmail.com
      789.example@gmail.com
    ]
    

    Then load them in the controller using:

    ALLOWED_EMAILS = Rails.configuration.allowed_user_emails.freeze
    

    To load from for example a yaml file you could do something like:

    ALLOWED_EMAILS = YAML.load_file(Rails.root.join('config', 'allowed_user_emails.yml')).freeze
    

    Having the following in the file:

    - 123.example@gmail.com
    - 456.example@gmail.com
    - 789.example@gmail.com