-
Notifications
You must be signed in to change notification settings - Fork 45
Using license(s) dynamically based on user settings
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:
- Adding a new column(say 'license') to users table.
- Creating predefined licenses.
- Creating a permit class that determines which license to use based on user setting(s).
- 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.
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:
- app/permits/licenses/basic_license.rb
- app/permits/licenses/editor_license.rb
- app/permits/licenses/manager_license.rb
Lets put our permissions into these files.
def permit_rules
can :read, [Question, Board]
end
def permit_rules
can :edit, [Question, Board]
can :reply, Conversation
end
def permit_rules
can :create, [Question, Board]
can :delete, [Question, Board]
end
rails g cantango:user_permit User
The above commands would generate following file:
- app/permits/user_license.rb
Update app/permits/user_license.rb as:
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.
So, we just have to do sth like if user_can?(:create, Board ) in our views.
Hope this helps.