Automatic login into Rails app

I use to my current project ActAsAuthenticated plugin. But I don’t want force everybody to create account. If someone does, it is good but I don’t expect everybody to rush and create Yet Another Web App Account (TM).

But application logic requires sometimes to use account data. So force everybody to logon or create checks if user is logged or not. Forcing to logon means forcing to create account, which violates my principles. Simpler would be just to force automatic logon to some anonymous account. So here is recipe for that:

Make an anonymous account – migration is the right solution (however I did it not right, so I give no recipe how to make it portable way). Then change method login_required in lib/authenticated_system.rb to following:

def login_required
username, passwd = get_auth_data
self.current_user ||= User.authenticate(username, passwd) || :false if username && passwd
self.current_user = User.authenticate("anonymous", "PASSWORD") if not self.current_user
logged_in? && authorized? ? true : access_denied
end

Change PASSWORD to password used to create this account. Now, when You enable before_filter :login_required in Your controllers, user will be automatically logged as anonymous use, when application have no other credentials from user. In case You don’t have anonymous account in users DB (well, when You don’t use migration to create this account, and move code to other system You should not expect anonymous account to exists, right?)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.