Accessing Logged In Users with SaltedHashLoginGenerator

Posted by James Wilford Thu, 23 Feb 2006 23:43:00 GMT

So, I'm using SaltedHashLoginGenerator in my project. All the buzz seems to be around acts_as_authenticated at the moment, but I wasn't too impressed. It seems to lack basic functionality such as 'forgot password'. So I stuck with SaltedHashLoginGenerator, figuring if it ain't broke, don't fix it. However, I have added a few neat tricks to make it easier to use, which are described here.

Are we logged in?

So the most basic thing you'll want to do is alter the behaviour of your controller actions and your views based on whether a user is logged in or not. You might also want to use some of the user's information, for example to display their name.

By default, support for this kind of thing is rather weak. In the "user_system" module (/lib/user_system.rb), there is a "user?" method which returns true or false. You can use this in your controllers to see if a user is logged in. For example:

if user?
  launch_rocket
else
  redirect_to :controller =>  user, :action => login
end

However, if you want to actually use the user's details, or refer to the user in a view, the docs just say you should use @session['user']. Which frankly brings back nasty flashbacks of PHP for me.

Methods to my madness

So the first thing I did was to define a "logged_in_user" method in application.rb:

def logged_in_user
  @session['user'] if user?
end

This can be used in the controller like this:

@user = logged_in_user

Nice Views

All very well, but what about views? Surely we need to define the same kind of things as helpers for the views, a clear violation of the DRY principle.

Not surprisingly, the rails developers have thought of this. And they have very helpfully allowed the use of controller methods and attributes as helpers by means of the methods "helper_method" and its alias, "helper_attr". This allows me to define my application controller something like this:


require 'localization'
require 'user_system'

# The filters added to this controller will be run for all controllers in the application.
# Likewise will all the methods added be available for all controllers.
class ApplicationController < ActionController::Base
  include Localization
  include UserSystem

  helper :user
  model  :user

  helper_method :user?
  helper_attr :logged_in_user
  def logged_in_user
    @session['user'] if user?
  end

end

The 'logged_in_user' method must be here, not in the user_system module, or you'll get a NameError. I'm not sure why this is, so please leave a comment if you know.

Trackbacks

Use the following link to trackback from your own site:
http://blog.wilf.me.uk/trackbacks?article_id=saltedhashlogingenerator-handy-tips&day=23&month=02&year=2006

Comments

Leave a comment

Comments