Use a PHPBB forum to handle user authentication in your rails app

Im currently in the process of rebuilding www.realalehunter.co.uk in rails. Its currently uses PHPBB to handle logging in and authentication so to make the rebuild simpler I thought keep it working in the same way instead of trying to migrate all the users/passwords to a separate system.

So I wrote a rails gem / plugin to make this a bit easier. It currently works on Rails > 2.3.3. I decided that I still wanted to have a users table in my applications database to make relationships easier but I would just store the stuff that’s important to the app itself (not passwords etc). So if you visit the rails site and are logged in to the forum a user will also be created in your rails app database if one does not exist.

So here is how to get started:

# install the gem
gem install mattfawcett-phpbb-auth

Tell rails that you want to use the gem it by adding the following to your environment.rb

config.gem "mattfawcett-phpbb-auth", :lib => "phpbb_auth", :source => "http://gems.github.com"


Add an entries to database.yml for phpbb_database_development, phpbb_database_production and phpbb_database_development.

In your config directory create a file called phpbb_auth_settings.rb, copy whats below into the file and change to match your setup.

PHPBB_AUTH_FORUM_DATABASE_TABLE_PREFIX = 'phpbb_'
PHPBB_AUTH_COOKIE_NAME = 'phpbb3_7uah4'; 
PHPBB_AUTH_LOCAL_USER_MODEL_NAME ='User' #this is the name of the model that you will use to store information about  users in your rails app 
PHPBB_AUTH_REMOTE_REMOTE_IDENTIFIER = 'user_email' #I use email to identify somebody, you may want to use the username  instead 
PHPBB_AUTH_REMOTE_LOCAL_IDENTIFIER = 'email' #this is the name of a field on your local user model that will be used to  lookup the value of remote identifier.
PHPBB_AUTH_COLUMNS_TO_DUPLICATE = {:user_website => :website} #specify any additional fields that you would like copying  to your local user model 

In application_controller.rb, include the module

include PhpbbAuth 

How you handle the rest is up to you but here’s what I did. Create a method called set_current_user.

def set_current_user   
  @current_user = current_user 
end

Add a before filter to the controller to run the method.

before_filter :set_current_user 

You will then have access to the @current_user variable in your controllers and views. This will be either nil if the user is not logged in, or an instance of your local User.

The source is up on Github.

Posted by Matt Mon, 31 Aug 2009 12:12:00 GMT