Skip to content

Using license(s) dynamically based on user settings

farukh-dm edited this page Dec 25, 2012 · 7 revisions

This page demonstrate how to choose between licenses based on user setting(s).

So the use case is something like, we have different licenses containing predefined permissions. User can have only one license at once. User should be given access to whatever permissions that license has.

Here's what we would be doing:

  1. Adding a new column(say 'license') to users table.
  2. Creating predefined licenses.
  3. Creating a permit class that determines which license to use based on user setting(s).
  4. Using helpers to test.

So, lets buckle up :) I've tried to make it as simpler as possible. The description might be long, but just give it a try.

1. Adding a new column(say 'license') to users table:

rails g migration add_license_column_to_users license:string

rake db:migrate

**I hope you would have some way to put some value into license column.(Scaffolding or whatsoever). Just populate something like BASIC or GOLD or PLATINUM .

2. Creating predefined licenses(use Generators):

rails g cantango:license basic

rails g cantango:license editor

rails g cantango:license manager

The above commands would generate following 3 files:

  1. app/permits/licenses/basic_license.rb
  2. app/permits/licenses/editor_license.rb
  3. app/permits/licenses/manager_license.rb

Lets put our permissions into these files.

Update app/permits/licenses/basic_license.rb

def permit_rules

can :read, [Question, Board]

end

Update app/permits/licenses/editor_license.rb

def permit_rules

can :edit, [Question, Board]

can :reply, Conversation

end

Update app/permits/licenses/manager_license.rb

def permit_rules

can :create, [Question, Board]

can :delete, [Question, Board]

end

3. Creating a permit class that determines which license to use based on user setting(s):

rails g cantango:user_permit User

The above commands would generate following file:

  1. app/permits/user_license.rb

Update app/permits/user_license.rb as:

Get rules based on user's license

def permit_rules

  Rails.logger.debug("in UserPermit :: permit_rules :: we get access to user object as user, thus use it :: #{user.license}")

  case user.license

    when 'GOLD'

      licenses_to_use = :basic, :editor

    when 'PLATINUM'

      licenses_to_use = :basic, :editor, :manager

    else

      licenses_to_use = :basic

  end

  licenses licenses_to_use

end

If you look above, we've got access to helper method "user" which returns current user object. So based on current user's license, required license and permission specified would be used.

4. Using helpers to test:

So, we just have to do sth like if user_can?(:create, Board ) in our views.

Hope this helps.