h1. Troles Troles aims to be a complete (end-all) roles solution for Ruby and is also targeted to be used with Rails 3. As of early June it is still under development but getting close to first release. The project currently consists of: * Trole - for single role strategies * Troles - for many roles strategies * TroleGroups - for groups of roles The Troles project uses _role caching_ to optimize performance! The roles list cache of a role subject (fx a user) is only updated (retrieved from data store) when the roles of the role subject changes! Note: Troles is a full redesign of _roles generic_ and company, using lessons learned. Troles uses a much cleaner design. It is aimed at being easy to extend and easy to create adapters for etc. h2. Status June 7, 2011 I'm now in the process of implementing TroleGroups! Finally a fully integrated role groups solution for Ruby and Rails ;) Due to the flexible design ot troles and trole, I can reuse the same infrastructure/design/architecture to implement trole_groups! *Yiii...haaa!* "A RoleGroup is simply another role_subject and can thus be configured with a given role strategy!" Simple and Sweet :) h2. The Ruby Class Decorator (RCD) pattern is born!!! I realized a while ago that I had come upon a very cool kind of "class decorator" design pattern that can be generalized to any gem that "decorates" a class (or perhaps multiple classes) with certain behavior. Gems such as _act_as_xxx_ come to mind fx. I will soon try to generalize this pattern into a separate project and then have trole, troles and trole_groups all use this to leverage their functionality. Also, I will make use of an idea that I just had while taking a cold shower (try it sometime if you have a mind block!). The idea is to have an internal default API, and an exposed API that by default is a reflection of the internal API. However the user is free to block parts of the API from being loaded or define his own external API that utilizes the inner API. Since this is a general purpose decorator pattern, there should also be a kind of Index where you can see which decorators have been applied to an object and what API each such decorator exposes! Cool stuff!!!! Some example usage:
return if !User.has_decorator?(:troles_group) # do some trole group stuff!!! # later ... # list all decorators currently applied to the User class puts User.decorators # print the methods of the public Write API for the :troles_group decorator :) puts User.decorator(:troles_group).public_api(:write).methods.sort # print the methods of the internal Write API for the :troles_group decorator :) puts User.decorator(:troles_group).internal_api(:write).methods.sortI will use the new Decorator API very soon... sth like this:
User.decorator(:trole_groups).configure(:strategy) :ref_one do |strategy| strategy.orm = :mongoid strategy.auto_load = true end.configure!Awesome! h3. Yard documentation I'm using "Yard":http://rubydoc.info/docs/yard/file/docs/GettingStarted.md for documentation.
$ yard server From browser, go to: http://0.0.0.0:8808/ # then you can enjoy! the nice documentation :)There is now support for Caching and invalidation of the _role_list_ when the roles change. The specs now validate that caching works as it should. Please help out to finalize this project! :) h2. Bug hunting by running specs Run specs for at most one strategy at the time for now... @$ rspec spec/troles/strategies/bit_many_spec.rb@ Please see the document _spec/Guide to running specs.textile_ where I advise on how best to do "bug hunting" to help get this project off the ground! h2. Role strategies The following lists the role strategies to be supported * Single - one role from a set of valid roles * Many - many roles from a set of valid roles h3. Single role strategies Schemas: * Boolean field on the User class (admin role) * String field on the User class * One reference to a Role * Embeds one Role (document store only) Field stored in the data store: @trole@ The field is named _trole_, in order not to conflict with the method _#role_ used in the _Role DSL_. h3. Multiple roles strategies Schemas * Integer (bitmap) field on the User class * String of comma delimited roles on User class * References to multiple Roles * Embeds multiple Roles Field stored in the datastore: @troles@ The field is named troles, in order not to conflict with the method _#roles_ used in the _Role DSL_. These strategies can be grouped and named as follows: Single role: * bit_one * string_one * ref_one * embed_one (document store) Multiple roles * bit_many * string_many * ref_many * embed_many (document store) These strategies can be implemented for any data store using any schema format. h3. Using roles strategies with Users and User accounts Roles are assigned to role subject classes such as _User_ or _UserAccount_ (YES, Devise can have multiple user accounts!). The class that has a role strategy assigned is referred to as the _role subject class_. Different role subject classes can have different role strategies! When using Devise this could translate fx into a UserAccount with a "many roles" strategy and an AdminAccount with a "single role" strategy (or vice versa). Example:
require 'troles' require 'troles/macros' class UserAccount troles_strategy(:string_many).configure! end class AdminAccount troles_strategy(:bit_one, :static => true).configure! endThe special troles macros must be enabled my requiring the _trole/macros_ file. h3. Macro options The @:static => true@ options is used to indicate, that the role can not be changed after being initially set. But we are getting ahead of ourselves... (more on this later). Troles can easily be extended to support other macro options if needed. h2. Roles API The Roles API can be divided into: * Core * Event/Cache * Read * Write * Store * Validation * Operations object There is an equivalen Trole API for single role strategies. h3. Event/Cache API The User class should have an event trigger after *save* to react when the roles have changed. If the roles were changed, an even should be sent to an _Event Manager_ to handle this. The event manager can have subscribers to events. Also any write event to the datastore should be predicated on _#static_roles?_ not being true for the user (thus ensuring guest roles are never updated). Save triggers call to Event#update_roles
User after_save: update_roles # event handler
module Troles::Api::Event def update_roles def publish_change eventh3. Roles Read API This API operates directly on a user, fx _user#has_role?_
user.has_role? :admin user.is_role? :editor user.has_any_roles? :editor, :adminh3. Roles Write API This API operates directly on a user, fx _user#has_role?_
user.add_role :admin user.remove_role :editorh3. Roles Operations object The Roles Operations object is available on user#roles
user.roles + :admin user.roles - :editor user.roles << [:editor, :admin] user.roles.clear!h3. Creating a custom Data Store Adapter (DSA) An adapter almost always requires a custom Config class implementation. Look at the _troles/common/config.rb_ to see what functionality is available that you can use. Note that :single role strategies always have the namespace 'Trole' whereas for :many it is 'Troles'. This convention is used throughout troles and breaking this convention will thus break the troles functionality. A custom Config class for _:single_ role strategies using _Mongoid_ could look sth. like this:
module Trole::Mongoid class Config < Troles::Common::Config def initialize subject_class, options = {} super end def configure_relation case strategy when :ref_one has_one_for subject_class, object_model belongs_to_for object_model, subject_class when :embed_one embeds_one_for subject_class, object_model end end def configure_field type = case strategy when :bit_one Boolean when :string_one String end subject_class.send(:field, role_field, type) if type endAs you can see, you have several nice convenience methods available to help set up these somewhat complex model relationships! See the _schema_helpers.rb_ file for more details! Example: Config class for :many roles strategies with _Mongoid_
module Troles::Mongoid class Config < Troles::Common::Config def initialize subject_class, options = {} super end def configure_relation case strategy ... end end def configure_field type = case strategy when :bit_many Integer when :string_many String end subject_class.send(:field, role_field, type: => type) if type endh3. Creating a custom Strategy Storage Adapter (SSA) Often you need to define Storage class implementations for some of the strategies, especially those that reference or embed other models. You must implement the following methods: - #display_roles (returns symbol list of roles) - #clear! (clear the roles in the datastore) - #set_roles (set the roles in the datastore) - #set_role (as #set_roles) Note: #set_role is only required for :single role strategies. In this case #set_roles is not required, as the superclass implementation simply calls #set_role with the first role. Example custom SSA (encrypted role string):
module Trole::Storage module EncryptedStringOne < BaseOne def initialize role_subject super end def display_roles decrypted_value.split(',') end # saves the role of the role subject in the data store # @param [Symbol] the role name def set_role role set_encrypted_ds_field role.to_s end # sets the role to its default state def clear! set_encrypted_ds_field "" end protected def decrypted_value ds_field_value.decrypt! end def set_encrypted_value value set_ds_field value.encrypt! end end endh3. Custom Storage for an ORM (or data store) In some cases it is useful to rewrite part of the base Storage functionality. One such method is #find_roles.
module Troles::Storage class BaseMany < Troles::Common::Storage def find_roles *roles role_model.where(:name => roles.flatten).all end ... endActive Record and Mongoid both implement the above API, so no need to customize this method in the Storage adapter. For most other ORMs/data stores you will likely have to write your own logic to achieve this.
module Troles::MongoidStorage class RefMany < Troles::Storage::BaseMany def find_roles *roles # my own custom datastore logic!!! end ...h3. Custom data marshaller You can also use a custom "Marshaller":http://en.wikipedia.org/wiki/Marshalling_%28computer_science%29 to store the roles in a non-standard format. This is used for the _BitMany_ strategy, which has a special _Marshaller::BitMask_ class which handles conversion between a list of symbols to an _Integer_ bitmap representing it (relative to a valid roles list!). You can create your own _Marshaller_, fx to encrypt the roles info or whatever you like!
module Troles::Marshaller class Encryption < Generic def initialize role_subject super end # convert marshalled value into roles symbols list def read ... end # convert roles symbols list into value to be marshalled def write *roles ... end end endh3. Using a custom Marshaller in a Storage implementation The following example is taken from the BitOne Storage implementation that is part of troles:
require 'troles/common/marshaller' module Trole::Storage class BitOne < BaseOne # display the role as a list of one symbol # see Troles::Marshaller::Bitmask # @return [ArrayNote that the same _BitMask_ marshaller is also reused in the _BitMany_ storage! The _#bitmask_ method returns an instance of the _Bitmask_ marshaller, instantiated with the _role_subject_ (the instance that has the #role_list method, typically the user or user account). To use the _Encryption_ marshaller in an Encryption storage we could create a _#marshaller_ method:] roles list def display_roles raise "BitOne requires exactly two valid roles, was: #{valid_roles}" if !(valid_roles.size == 2) [bitmask.read].flatten end # saves the role for the role subject in the data store # @param [Symbol] role name def set_role role num = bitmask.write role set_ds_field(num == 1 ? false : true) # boolean field in Data store end # Clears the role state of the role subject def clear! set_ds_field false end protected def bitmask @bitmask ||= Troles::Common::Marshaller::Bitmask.new role_subject end ...
def marshaller @marshaller ||= Troles::Marshaller::Encryption.new role_subject endThen use @marshaller.write(*roles)@ in the _set_xxxx_ methods and @marshaller.read@ in _#display_roles_ method of the storage, as needed. h3. Custom troles strategy To add a new strategy, you can optionally create a special Strategy module that acts as the module included by the troles macro. Using standard naming convention it will be found and used by the _troles_strategy_ macro method :) If you don't create a specialized Strategy module, troles will just use the _BaseOne_ or _BaseMany_ depending on the singularity (one or many) of the strategy. Using naming conventions, the strategy will always try to use a matching storage class (substitute Strategy for Storage). If you don't define a custom Strategy module or Storage class, troles will just use a generic implementation. Try to keep it simple and start by defining only a Config class and then see if you need to implement a custom Storage class. You rarely need to implement a custom Strategy module or custom API implementations. Here is an example of a custom Strategy implementation for _EncryptedStringMany_ that simply wraps the _BaseMany_ strategy implementation. This example demonstrates how you can easily override functionality with custom implementations by including modules "on top".
module Troles::Strategy module EncryptedStringMany # What to add to the role subject class when this role strategy is included # @param [Class] the role subject class to def self.included(base) base.send :include, BaseMany base.send :include, InstanceMethods base.extend ClassMethods end module ClassMethods # .. my custom class methods end module InstanceMethods # .. my custom instance methods end end endh3. Creating a Base strategy for an Adapter In some cases you need a custom Base strategy that contains common functionality shared among strategies with the same singularity (one or many). Example: _BaseMany_, used as the base for all Many roles strategies
module Troles::Mongoid module Strategy module BaseMany # @param [Class] the role subject class for which to include the Role strategy (fx User Account) # def self.included(base) base.send :include, Troles::Strategy::BaseMany # base.send :include, InstanceMethods # base.extend ClassMethods end end end endTo use your adapter, simply pass an extra option to the _troles_strategy_ macro:
User.troles_strategy(:bit_one, :orm => :mongoid).configure!This even allows you to use different ORM role strategies/storages for different user accounts simultaneously!!! Using the :auto_load option will 'auto load' (i.e require) the orm adapter from the built-in catalog of adapters that come with troles. You can include a specific custom (or 3rd party) adapter manually. In the future it will be possible to configure troles with adapters and specify how/where to load them from as part of this configuration!
User.troles_strategy(:bit_one, :orm => :mongoid, :auto_load => true).configure!You can also specify some of the options relevant to model configuration on the call to #configure if you like ;)
User.troles_strategy(:bit_one, :orm => :active_record, :auto_load => true).configure! :role_model => 'Troll'The _troles_strategy_ macro will yield the Config object if you pass it a block. This allows you to configure your stategy with troles inside the block and then call _configure!_ on end of the block. Using all this in combination, you could configure it all doing sth. like this:
require 'my/own/active_record/adapter' User.troles_strategy :bit_one, :orm => :active_record do |c| c.auto_load = false c.valid_roles = [:troll_commander, :troll_warrior] c.auto_config[:relations] = false # to take over control of setting up model relationships end.configure! :role_model => 'Troll', :role_join_model => 'UserTroll'Enjoy :) h2. Global configuration The following is a list of the global Troles common configuration options: * default_orm * auto_load (true|false) * log_on (true|false) * auto_config[:models] (true|false) * auto_config[:fields] (true|false) * auto_config[:relations] (true|false) Examples: @Troles::Common::Config.default_orm = :mongoid@ Troles uses this as the ORM setting in case you don't specify the orm when you configure a troles strategy. @Troles::Common::Config.auto_load = true@ Ensures the adapter is autoloaded from the troles internal _/adapter_ folder. Leave this to false (defalt) if you have rolled your own or use a 3rd party adapter. @Troles::Common::Config.log_on = true@ Turns on some logging to make it easier to debug what goes on behind the curtain (note: to be improved...). @Troles::Common::Config.auto_config[:models] = false@ Disables troles auto configuration of models, allowing you full control. @Troles::Common::Config.auto_config[:relations] = false@ Disables troles auto configuration of model relationships (has_many, belongs_to and such), allowing you full control. @Troles::Common::Config.auto_config[:fields] = false@ Disables troles auto configuration of model fields (for data stores such as Data Mapper, Mongoid etc that have the concept of data fields), allowing you full control. Note: For all the global on/off options you can opt to use same option on an individual strategy basis as part of an individual strategy configuration. In the strategy Config class they can be used like this @if auto_config?(:fields)@ h2. Other notes on Application-User control _troles_ will be part of a larger project under development that will go under the name "dancing tango with trolls". This will be a rework of _cream_ and _cancan-permits_ that will target use in apllications with multiple user accounts and multiple sub applications. In this new system, _dancing_ will be the replacement of _cream_ and _tango_ the replacement of _cancan-permits_. I hope to give a talk on RubyConf 2011 about this system. h3. Guest users From the Devise wiki: https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user "In some applications, it's useful to have a guest User object to pass around even before the (human) user has registered or logged in. Normally, you want this guest user to persist as long as the browser session persists. Our approach is to create a guest user object in the database and store its id in session[:guest_user_id]. When (and if) the user registers or logs in, we delete the guest user and clear the session variable. A helper function, current_or_guest_user, returns guest_user if the user is not logged in and current_user if the user is logged in."
module ApplicationHelper ... # if user is logged in, return current_user, else return guest_user def current_or_guest_user if current_user if session[:guest_user_id] logging_in guest_user.destroy session[:guest_user_id] = nil end current_user else guest_user end end # find guest_user object associated with the current session, # creating one as needed def guest_user guest_user_id = session[:guest_user_id] ||= User.create(:name => "guest").id User.find(guest_user_id) end # called (once) when the user logs in, insert any code your application needs # to hand off from guest_user to current_user. def logging_in end ... endIn the new system, I propose the following:
# this will make the current user the guest user account for the given scope! def sign_in_guest scope, options = {} warden.set_user(guest_user.account, options.merge!(:scope => scope)) end # sign_in :user, @user # sign_in(scope, resource) # sign_in @user # sign_in(resource) # sign_in @user, :event => :authentication # sign_in(resource, options) # sign_in @user, :bypass => true # sign_in(resource, options) # def sign_in(resource_or_scope, *args) ... post_sign_in resource, scope end def post_sign_in resource, scope user = warden.user(scope) return if !user user.transfer_guest(guest_user) if guest_user? && user.respond_to?(:transfer) session[:guest_user] = nil end def guest_user? !session[:guest_user].nil? end def guest_user session[:guest_user] ||= GuestUser.new end
class GuestUserAccount troles_strategy(:static_one, :role => :guest) do |c| # c.valid_roles = [:guest] not needed! end.configure! attr_accessor :guest def user guest end def initialize roles.set_default! end endHere the special _:static_many_ strategy is used, which means that whatever the _role_list_ is first set to can never change for that user.
module BaseAccount # transfer guest settings to logged_in user/account def transfer_guest(guest_user) end end class UserAccount include Mongoid::Document troles_strategy(:bit_many, :orm => :mongoid) do |c| c.valid_roles = [:user, :admin, :guest] end.configure! end class BloggerAccount include Mongoid::Document troles_strategy(:string_many, :orm => :mongoid) do |c| c.valid_roles = [:blogger, :editor, :admin] end.configure! endAnd here the User setup:
module BaseUser end class User include Mongoid::Document include BaseUser has_one :user_account has_one :admin_account has_one :blogger_account ... end
class GuestUser include BaseUser def account @guest_user_account ||= GuestUserAccount.new end endThe Guest class should be set up to only have relationship to those special guest user accounts. The Guest class should implement the same API as User but can stub or hardcode much functionality in order to act as a guest and not a "real" user. The guest user should (usually) not have any user info persisted, so it makes sense to use a generic account that is in-memory. h2. License This project rocks and uses MIT-LICENSE.