This plugin provides a flexible way to add authorization to Rails.
The authorization process decides whether a user is allowed access to some feature. It is distinct from the authentication process, which tries to confirm a user is authentic, not an imposter. There are many authentication systems available for Rails, e.g., acts_as_authenticated and LoginEngine. This authorization system will play nicely with them as long as some simple requirements are met:
-
User objects are available that implement a has_role?(role, authorizable_object = nil) method. This requirement can be easily handled by using acts_as_authorized_user in the User-like class.
-
If you want to use “role of model” authorization expressions, like “owner of resource” or “eligible for :award”, then your models with roles must implement an accepts_role?(role, user) method. This requirement can be handled by using acts_as_authorizable in the model class.
The authorization plugin provides the following:
-
A simple way of checking authorization at either the class or instance method level using #permit and #permit?
-
Authorization using roles for the entire application, a model class, or an instance of a model (i.e., a particular object).
-
Some english-like dynamic methods that draw on the defined roles. You will be able to use methods like “user.is_fan_of angelina” or “angelina.has_fans?”, where a ‘fan’ is only defined in the roles table.
-
Pick-and-choose a mixin for your desired level of database complexity. For all the features, you will want to use “object roles table” (see below)
class MeetingController < ApplicationController permit "rubyists and wanna_be_rubyists", :except => :public_page def public_page render :text => "We're all in Chicago" end def secret_info permit "interested in Answers and (matz or dhh)" do render :text => "The Answer = 42" end end def find_apprentice @founder = User.find_by_name('matz') permit "'inner circle' of :founder" do if request.post? apprentice = User.find_by_skillset(params[:uber_hacker]) ruby_community = Group.find_by_name('Ruby') ruby_community.accepts_role 'yarv_builder', apprentice end end end def rails_conf @meeting = Meeting.find_by_name('RailsConf') permit "attendees of :meeting or swedish_mensa_supermodels" do venue = Hotel.find_by_name("Wyndham O'Hare") current_user.is_traveller_to venue if permit? "traveller to :venue and not speaker" Partay.all_night_long @misdeeds = current_user.is_participant_in_what end end end end
Installation of the Authorization plugin is quick and easy.
Open a terminal and change directory to the root of your Ruby on Rails application referred to here as ‘RAILS_ROOT’. You can choose to install the plugin using the standard Ruby on Rails tools (recommended), as a Git sub-module, or by grabbing a tarball.
NOTE : This assumes you are using a current (Rails 2.1.x +) version of Rails which now has built in support for installing a plugin directly from a git repo. This also assumes you have Git installed and working properly. You can always use the manual install shown below if this is not true.
Run the following command in your RAILS_ROOT:
./script/plugin install git://github.com/DocSavage/rails-authorization-plugin.git
This will install the latest version of the plugin from our GitHub master repo into your RAILS_ROOT/vendor/plugins/rails-authorization-plugin directory.
The source code for this plugin is maintained in a Git SCM repository. The Git repository will always have the latest version of the code.
You can install the plugin using Git sub-modules (which are akin to using SVN externals). Installing this way allows you to update the plugin code later if needed (but note that it will not update any generated code created earlier by this plugin such as migrations, which you will need to update manually). Also note that if you are deploying your code using Capistrano this method may cause issues if you are not careful (e.g. the code will be deployed but the sub-modules will not be updated or installed at all).
From your RAILS_ROOT directory run:
git submodule add git://github.com/DocSavage/rails-authorization-plugin.git vendor/plugins/authorization
You should be able to update this plugin in the future with the simple command (again from RAILS_ROOT):
git submodule update
If you like to install the old school manual way, feel free to download a copy of latest master branch plugin code from:
github.com/docsavage/rails-authorization-plugin/tarball/master
Once downloaded, rename the top level dir to ‘rails-authorization-plugin’ and then you can stuff that directory in your RAILS_ROOT/vendor/plugins directory.
These instructions will show you how to do the initial configuration of the plugin.
This is the simplest way to use the plugin and requires no database. Roles are assumed to be coded into the Model classes using the has_role?(role, obj = nil)
method. This method is however more limited in the functionality available to you.
The Object Roles Table mixin provides full support for authorization expressions within a database by add a polymorphic field to the Role table. Because roles have polymorphic associations to an authorizable object, we can assign a user to a role for any model instance. So you could declare user X to be a moderator for workshop Y, or you could make user A be the owner of resource B.
The identity module adds a number of dynamic methods that use defined roles. The user-like model gets methods like ‘user.is_moderator_of group (sets user to “moderator” of group`), user.is_moderator? (returns true/false if user has some role “moderator”), and group.has_moderators (returns an array of users that have role “moderator” for the group). If you prefer not to have these dynamic methods available, you can simply comment out the inclusion of the identity module within object_roles_table.rb.
Choose one of the installation types identified above and make sure your application provides a current_user method or something that returns the current user object (resful_authentication provides this out of the box).
At the top of your RAILS_ROOT/config/environment.rb file add something like the following (customized for your controllers and actions of course):
... # Authorization plugin for role based access control # You can override default authorization system constants here. # Can be 'object roles' or 'hardwired' AUTHORIZATION_MIXIN = "object roles" # NOTE : If you use modular controllers like '/admin/products' be sure # to redirect to something like '/sessions' controller (with a leading slash) # as shown in the example below or you will not get redirected properly # # This can be set to a hash or to an explicit path like '/login' # LOGIN_REQUIRED_REDIRECTION = { :controller => '/sessions', :action => 'new' } PERMISSION_DENIED_REDIRECTION = { :controller => '/home', :action => 'index' } # The method your auth scheme uses to store the location to redirect back to STORE_LOCATION_METHOD = :store_location # standard rails config below here Rails::Initializer.run do |config| ...
-
Set the AUTHORIZATION_MIXIN constant to object roles or hardwired. (See init.rb in this plugin for how the role support is mixed in.)
-
Set the LOGIN_REQUIRED_REDIRECTION to match the path or a hash with the :controller and :action for your applications login page.
-
Set the PERMISSION_DENIED_REDIRECTION to match the path or a hash with the :controller and :action for your applications permission denied page.
-
Set the STORE_LOCATION_METHOD to the method your application uses for storing the current URL that the user should return to after authentication (e.g. store_location).
-
See the PLUGIN_DIRlibauthorization.rb file for the default values of LOGIN_REQUIRED_REDIRECTION, PERMISSION_DENIED_REDIRECTION and STORE_LOCATION_METHOD.
If you plan to use the object roles method you will need to setup a few database tables. We have provided a database migration file (Rails 2.0+ compatible) that will make this process easy for you. If you plan to use the hardwired mixin, no extra database tables are required. and you can skip to the next step.
Run the following command from your RAILS_ROOT (Note : The generator takes a model name as its argument, which at this time must be ‘Role’.):
./script/generate role_model Role
This will create:
Model: RAILS_ROOT/app/models/role.rb Test: RAILS_ROOT/test/unit/role_test.rb Fixtures: RAILS_ROOT/test/fixtures/roles.yml Migration: RAILS_ROOT/db/migrate/###_add_role.rb
And now you will need to run a database migration from your RAILS_ROOT:
rake db:migrate
Now we need to add the methods needed by each of your models that will participate in role based authorization. Typically these models fall into two categories, the User model, and all other models that will have roles available for use.
For a typical installation you would add both mixins to your User model.
class User < ActiveRecord::Base # Authorization plugin acts_as_authorized_user acts_as_authorizable ...
Then in each additional model that you want to be able to restrict based on role you would add just the acts_as_authorizable mixin like this:
class Event < ActiveRecord::Base acts_as_authorizable ...
You are done with the configuration!
permit and permit? take an authorization expression and a hash of options that typically includes any objects that need to be queried:
permit <authorization expression> [, options hash ] permit? <authorization expression> [, options hash ]
The difference between permit and permit? is redirection. permit is a declarative statement and redirects by default. It can also be used as a class or an instance method, gating the access to an entire controller in a before_filter fashion.
permit? is only an instance method, can be used within expressions, does not redirect by default.
The authorization expression is a boolean expression made up of permitted roles, prepositions, and authorizable models. Examples include “admin” (User model assumed), “moderator of :workshop” (looks at options hash and then @workshop), “‘top salesman’ at :company” (multiword roles delimited by single quotes), or “scheduled for Exam” (queries class method of Exam).
Note that we can use several permitted prepositions (‘of’, ‘for’, ‘in’, ‘on’, ‘to’, ‘at’, ‘by’). In the discussion below, we assume you use the “of” preposition. You can modify the permitted prepositions by changing the constant in Authorization::Base::Parser.
-
If a specified role has no “of <model>” designation, we assume it is a user role (i.e., the model is the user-like object).
-
If an “of model” designation is given but no “model” key/value is supplied in the hash, we check if an instance variable @model if it’s available.
-
If the model is capitalized, we assume it’s a class and query
Model#self.accepts_role?
(the class method) for the permission. (Currently only available in ObjectRolesTable mixin.)
For each role, a query is sent to the appropriate model object.
The grammar for the authorization expression is:
<expr> ::= (<expr>) | not <expr> | <term> or <expr> | <term> and <expr> | <term> <term> ::= <role> | <role> <preposition> <model> <preposition> ::= of | for | in | on | to | at | by <model> ::= /:*\w+/ <role> ::= /\w+/ | /'.*'/
Parentheses should be used to clarify permissions. Note that you may prefix the model with an optional “:” – the first versions of Authorization plugin made this mandatory but it’s now optional since the mandatory preposition makes models unambiguous.
:allow_guests => false.
We can allow permission processing without a current user object. The default is false.
:user => YourUserObject.
The name of your user object.
:get_user_method => method_name
The method name provided should return a user object. Default is #current_user, which is the how acts_as_authenticated works.
:only => [ :method1, :method2 ]
Array of methods to apply permit (not valid when used in instance methods)
:except => [ :method1, :method2 ]
Array of methods that won’t have permission checking (not valid when used in instance methods)
:redirect => boolean
Default is true. If false, permit will not redirect to denied page.
:login_required_redirection => path or hash default is "{ :controller => 'session', :action => 'new' }"
Path or Hash where user will be redirected if not logged in ()
:login_required_message => 'my message'
A string to present to your users when login is required. Default is ‘Login is required to access the requested page.’
:permission_denied_redirection => path or hash
Path or Hash where user will be redirected if logged in but not authorized (default is ”)
:permission_denied_message => 'my message'
Message that will be presented to the user when permission is denied. Default is ‘Permission denied. You cannot access the requested page.’
Roles are set by #has_role and #accepts_role methods that are mixed into the User-like object and the authorizable models. User objects can set roles and optionally an object scope for that role:
user.has_role 'site_admin' user.has_role 'moderator', group user.has_no_role 'site_admin' user.has_no_role 'moderator', group user.has_role 'member', Group
Note that the last method sets role “member” on a class “Group”. Roles can be set with three scopes: entire application (no class or object specified), a model class, or an instance of a model (i.e., a model object).
Models set roles for specific users:
a_model.accepts_role 'moderator', user a_model.accepts_no_role 'moderator', user Model.accepts_role 'class moderator', user
The method language has been chosen to aid memory of the argument order. A user has a role “foo”, so the role string immediately follows has_role. Similarly, a model accepts a role “foo”, so the role string immediately follows accepts_role. Then we append the scope.
Sometimes the user-like object might be an authorizable object as well, for example, when you allow ‘friend’ roles for users. In this case, the user-like object can be declared to be acts_as_authorizable
as well as acts_as_authorized_user
.
Role queries follow the same pattern as the setting of roles:
user.has_role? 'moderator' user.has_role? 'moderator', group user.has_role? 'member', Group a_model.accepts_role? 'moderator', user Model.accepts_role? 'moderator', user
When a user is queried without specifying either a model class or object, it returns true if the user has any matching role. For example, user.has_role? 'moderator'
returns true if the user is ‘moderator’ of a class, a model object, or just a generic ‘moderator’. Note that if you say user.has_role 'moderator'
, the user does not become ‘moderator’ for all classes and model objects; the user simply has a generic role ‘moderator’.
The Object Roles Table version includes some dynamic methods that use the roles table. For example, if you have roles like “eligible”, “moderator”, and “owner”, you’ll be able to use the following:
user.is_eligible_for_what --> returns array of authorizable objects for which user has role "eligible" user.is_moderator_of? group --> returns true/false user.is_moderator_of group --> sets user to have role "moderator" for object group. user.is_administrator --> sets user to have role "administrator" not really tied to any object.
Models get has_* methods:
group.has_moderators --> returns array of users with role "moderator" on that group group.has_moderators? --> returns true/false
Allowed prepositions are optional in the above dynamic methods. They are simply syntactic sugar. For example, the following are equivalent:
user.is_member_of group user.is_member_for group user.is_member group
Allowed prepositions are required in the authorization expressions because they are used to distinguish “role” and “role of :model” and “role of Model”.
If you prefer not to pollute your namespace with these dynamic methods, do not include the Identity module in object_roles_table.rb
.
We expect the application to provide the following methods:
Returns some user object, like an instance of my favorite class, UserFromMars
. A user
object, from the Authorization viewpoint, is simply an object that provides a has_role?
method.
Note that duck typing means we don’t care what else the UserFromMars
might be doing. We only care that we can get an id from whatever it is, and we can check if a given role string is associated with it. By using acts_as_authorized_user
, we inject what we need into the user object.
If you use an authorization expression “admin of :foo”, we check permission by asking foo
if it accepts_role?('admin', user)
. So for each model that is used in an expression, we assume that it provides the accepts_role?(role, user)
method.
Note that user
can be nil
if :allow_guests => true
.
This method will be called if authorization fails and the user is about to be redirected to the login action. This allows the application to return to the desired page after login. If the application doesn’t provide this method, the method will not be called.
The name of the method for storing a location can be modified by changing the constant STORE_LOCATION_METHOD in environment.rb. Also, the default login and permission denied pages are defined by the constants LOGIN_REQUIRED_REDIRECTION and PERMISSION_DENIED_REDIRECTION in authorization.rb and can be overriden in your environment.rb.
Roles specified without the “of model” designation:
-
We see if there is a
current_user
method available that will return a user object. This method can be overridden with the:user
hash. -
Once a user object is determined, we pass the role to
user.has_role?
and expect a true return value if the user has the given role.
Roles specified with “of model” designation:
-
We attempt to query an object in the options hash that has a matching key. Example:
permit "knight for justice", :justice => @abstract_idea
-
If there is no object with a matching key, we see if there’s a matching instance variable. Example: @meeting defined before we use
permit "moderator of meeting"
-
Once the model object is determined, we pass the role and user (determined in the manner above) to
model.accepts_role?
When upgrading this plugin, please refer to the following file:
github.com/DocSavage/rails-authorization-plugin/tree/master/UPGRADE.rdoc
Please see the file README_developers.txt for the methods we would like you to use to submit new code features, bugfixes and patches.
This version of rails-authorization-plugin will check if the object has a method named the role-in-question which return a user-like object, then will check if the returned object is the current_user
.
Suppose a user can write many posts. Only the poster and moderator can edit the posts.
class Post < ActiveRecord::Base belongs_to :user acts_as_authorizable ... end class User < ActiveRecord::Base has_many :posts acts_as_authorized_user ... end
We can check post.accepts_role? "user", user
without redefine the role to the user object. This way, we can set the permission :
class PostController < ApplicationController permit "user of :post or moderator", :only => [:edit, :update] ... end
Ofcourse you can use rename the method so it will make more sense
class Post belongs_to :user acts_as_authorizable def poster user end ... end
so:
class PostController < ApplicationController permit "poster of :post or moderator", :only => [:edit, :update] ... end
However, it can be somewhat dangerous. Imagine if you call post.accepts_role? "destroy", user
Just don’t do it ;-). I believe that this addition will not make it into the master project, so I won’t make any pull request.