A simple users system 1/2

written by damien on November 25th, 2007 @ 06:09 PM

At Dexem we are currently working on a new application in which we have to take into account several different users with different permissions. For example we have an admin, several resellers and several customers.

To put that in place, we are gonna use:

The default behavior of Acl System is to look for a roles relation in the User model. In the other applications we have at Dexem, a user may have several roles and each role defines access to specific objects of the application.

But for this application, the permission system should be much simpler. That’s why I decided a user should only have one role which will subsequently define a set of permissions. So instead of having a User model plus a Role model and having links between them, I simplified the system to implement inheritance of the User class for each type of user.

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table "users", :force => true do |t|
      # acts_as_authenticated attributes
      t.column :login,                     :string
      t.column :email,                     :string
      t.column :crypted_password,          :string, :limit => 40
      t.column :salt,                      :string, :limit => 40
      t.column :created_at,                :datetime
      t.column :updated_at,                :datetime
      t.column :remember_token,            :string
      t.column :remember_token_expires_at, :datetime

      # common attributes
      t.column :first_name, :string
      t.column :last_name, :string
      t.column :type, :string
      
      # reseller attributes
      t.column :reseller_account_id, :integer

      # customer attributes
      t.column :customer_account_id, :integer
    end
  end

  def self.down
    drop_table "users"
  end
end

In the User class defined by Acts as authenticated we add a role method:

def role
  self.class.to_s.underscore
end

and in Acl System we modify the role checking method:

module Caboose
  class RoleHandler < AccessHandler
    def check(key, context)
      context[:user].role == key.downcase
    end
  end
end

The users classes:

class Admin < User
end
class Reseller < User
  belongs_to :reseller_account
end
class Customer < User
  belongs_to :customer_account
end
With that code you have everything you need to make use of a basic users system. In the next part , I will explain and show how easy it is to integrate it with the use of Active Scaffold. Obviously, any comments on the design and ways to improve it are welcome :)

Comments are closed

Options:

Size

Colors