Today I Learned

Login to Ruby on Rails console with email and password

If you ever need to protect your rails console (or need to authenticate for any other reason) you can create a new file in config/initializers with code like this:

module Rails
  module ConsoleMethods
    def self.included(_base)
      puts 'Enter your email:'
      email = gets
      user = User.find_by(email: email.strip)
      unless user
        puts 'Email not found in database! Exiting...'
        exit
      end

      puts 'Enter your password:'
      pass = $stdin.noecho(&:gets)
      if user.valid_password?(pass.strip)
        puts "Welcome #{user.email}!"
      else
        puts 'Provided password is not correct! Exiting...'
        exit
      end
    end
  end
end

You can of course add condition so this code will be executed only on production and/or staging.

Note 1: If you are using devise for authentication as it is is done in my example above please make sure that your file is loaded after config/initializers/devise.rb which means that your file’s name should be “bigger” than devise.rb, for example: perform_authentication_in_console.rb

Note 2: with ruby version “2.3” or higher you are able to use IO::console.getpass instead of $stdin.noecho(&:gets)