Saturday, December 31, 2011

HTTP basic authentication using email address

In my previous article, I have written about HTTP basic authentication in rails using a plain user access YML.

Last few days ago, I have modified the logic to log-in using email address and password. So that anyone don't need to remember another new password. Hope it might help you...

Written a news private method
def login_by_email(user_name, password)
    is_logged_in = false
    if (user_name.match(/.+\b@yourdomain.com$\b/i))
      require 'net/imap'
      require 'openssl'
      client = Net::IMAP.new(host, port, true, nil, false)
      begin
        client.login(user_name, password)
        client.logout
        is_logged_in = true
      rescue Exception => error
        logger.error "Unable to log-in :: #{error.message}"
      end
      client.disconnect
    end
    return is_logged_in
  end
On line#3 I have checked the domain name to provide access for a specific domain. After that modified the authentication method following way:
def authenticate_for_staging_server
    authenticate_or_request_with_http_basic do |user_name, password|
      login_by_email(user_name, password) == true
    end
  end

Sunday, December 4, 2011

HTTP basic authentication in rails to protect staging server

Sometimes, you may need to protect your staging server from outside world. It can be done easily by using http basic authentication in rails3.

I did following things to use HTTP basic authentication to protect my staging server:

YML file with username and password pair:
devuser: devpass
testuser: testuserpass

Loaded YML data from application initializer:
HTTP_AUTH_USERS = YAML.load_file("#{Rails.root.to_s}/config/staging_server_users.yml")

Callback and authentication in the application controller:
before_filter :authenticate_for_staging_server, :if => lambda { Rails.env.development? }

private
def authenticate_for_staging_server
  authenticate_or_request_with_http_basic do |user_name, password|
    password == HTTP_AUTH_USERS[user_name]
  end
end

Hope it will help a lot who wants to protect their staging server.