Checking permissions when no user is signed in

makandra edited this page Sep 13, 2010 · 7 revisions

When a user is not signed in, there is no User instance on which to check permissions. There are solutions you might prefer to checking current_user.nil? over and over again.

Option 1: Check the permissions class directly

Instead of checking permissions on a user, you can ask the Permissions class directly. The following two lines are equivalent:

Permissions.may?(current_user, :update_post, @post)

To make this work, Aegis needs to know how to deal with a blank user. A good strategy is to have Aegis substitute an unsaved User instance with a guest role whenever it encounters a blank user. To do this, configure your Permissions class with the missing_user_means directive:

class Permissions < Aegis::Permissions
  missing_user_means { => 'guest') }

Option 2: Always have current_user

Another option is to re-rig your ApplicationController so that it returns an unsaved guest user when no user is known:

def current_user
  super || => 'guest')

Your implementation will differ depending on which authentication solution (Clearance, Devise, etc.) you’re using. You might need to touch other code that checks current_user.nil?.