95 Commits
1.0.0 ... 1.3.4

Author SHA1 Message Date
Ryan Bates
04b523eea4 releasing version 1.3.4 2010-08-31 15:46:26 -07:00
Ryan Bates
5a353c1cba don't stop at cannot definition when checking class - closes #131 2010-08-30 15:20:06 -07:00
Ryan Bates
4fe44af45d be more clear about blocks not working with accessible_by - closes #130 2010-08-30 13:40:31 -07:00
Ryan Bates
a10a38c82f releasing version 1.3.3 2010-08-20 16:27:25 -07:00
Ryan Bates
caed4fcee5 use RSpec namespace for matcher - closes #119 2010-08-18 16:22:43 -07:00
Ryan Bates
e893e12260 fixing broken spec and minor improvements to tableized_conditions method 2010-08-18 16:04:08 -07:00
McClain Looney
3d7742ea43 fix for bug 123 2010-08-17 09:33:11 -05:00
Ryan Bates
a566ea0f4f releasing version 1.3.2 which fixes slice error when passing custom resource name 2010-08-07 08:38:35 -07:00
Ryan Bates
333ddf1970 properly pass along resource name without slice error - closes #112 2010-08-07 08:33:31 -07:00
Ryan Bates
cd74267364 releasing version 1.3.1 with sanitize_sql fix 2010-08-06 23:28:51 -07:00
Ryan Bates
f8631dcc93 fixing error on protected sanitize_sql - closes #111 2010-08-06 23:24:04 -07:00
Ryan Bates
7a17586eb3 releasing version 1.3.0 2010-08-06 16:00:52 -07:00
Ryan Bates
13427e18d5 updating readme 2010-08-06 15:54:25 -07:00
Ryan Bates
1dccc0252a removing :resource option from rdocs since it's not longer used 2010-08-06 15:05:24 -07:00
Ryan Bates
75ce2bdefa allow :parent => false option to work in load/authorize resource 2010-08-06 14:26:57 -07:00
Ryan Bates
c9e0f4e3ef renaming :singular resource option to :singleton 2010-08-06 13:06:18 -07:00
Ryan Bates
7d9e710f05 updating changelog 2010-08-06 11:42:30 -07:00
Ryan Bates
236cece3b3 adding :find_by option to load_resource - closes #19 2010-08-06 11:18:54 -07:00
Ryan Bates
84f4c904b7 adding :singular option to support has_one associations in load/authorize resource - closes #93 2010-08-06 11:03:10 -07:00
Ryan Bates
6998e8bdd1 support multiple resources in :through option of load_resource, this makes polymorphic associations possible - closes #73 2010-08-06 10:35:42 -07:00
Ryan Bates
961b8c2477 consider ancestors when matching classes in Ability#can, this way it works with STI - closes #55 2010-08-06 10:06:37 -07:00
Ryan Bates
a157b65fbf adding :instance_name option to load/authorize_resource - closes #44 2010-08-06 09:35:07 -07:00
Ryan Bates
47f0aa597e change how params are passed to ControllerResource and use HashWithIndifferentAccess in tests 2010-08-06 09:24:01 -07:00
Ryan Bates
67b069579e don't pass nil to 'new' call when no params are specified - closes #63 2010-08-05 16:52:37 -07:00
Ryan Bates
156839b73e only use the :read action when authorizing parent resources 2010-08-05 16:24:08 -07:00
Ryan Bates
25a1c553bf adding :through option to replace :nesting option and moving ResourceAuthorization class code into ControllerResource 2010-08-05 16:12:30 -07:00
Ryan Bates
8dee01195d improving inline documentation for Query 2010-07-21 12:16:08 -07:00
Ryan Bates
5eae169d7b mentioning CanCan contributors in README 2010-07-21 12:06:28 -07:00
Ryan Bates
66ff1f2ea3 removing metrics link in readme, farewell Caliper :( 2010-07-21 12:02:27 -07:00
Ryan Bates
18dcf2a121 mention Rails 3 installation in README - closes #56 2010-07-21 11:59:24 -07:00
Ryan Bates
9b26f4d767 fixing specs for older versions of ruby and rspec 2010-07-21 11:56:19 -07:00
Ryan Bates
25637bb33a removing extra white space at end of lines 2010-07-21 11:45:26 -07:00
Ryan Bates
c5737f6d28 adding thanks to changelog 2010-07-20 17:11:05 -07:00
Ryan Bates
1659f21bb3 updating changelong with support for multiple can calls in accessible_by - closes #71 2010-07-20 17:09:46 -07:00
Ryan Bates
ba8cb3cf6d refactoring query.joins 2010-07-20 17:05:17 -07:00
Ryan Bates
e098ddaacd refactoring query.conditions 2010-07-20 16:00:22 -07:00
Ryan Bates
964a4765b1 removing need to pass tableize option around for query conditions 2010-07-20 13:43:43 -07:00
Ryan Bates
a42e067f3b extracting out Query class for generating sql conditions and association joins 2010-07-20 13:20:01 -07:00
Ryan Bates
60848143b7 refactoring can definition matching behavior 2010-07-20 11:04:03 -07:00
Ryan Bates
5d8f04363d merging with master and resolving a couple conflicts 2010-07-19 16:36:01 -07:00
Ryan Bates
cad425989e supporting deeply nested aliases - closes #98 2010-07-19 16:03:09 -07:00
Ryan Bates
1b4377cbf3 releasing version 1.2.0 2010-07-19 09:21:14 -07:00
Yura Sokolov
75eb1917f9 add test for single cannot definition 2010-05-25 14:28:29 +04:00
Yura Sokolov
5fd793090a fix logic error for single cannot condition - it should return no records 2010-05-25 14:09:01 +04:00
Yura Sokolov
ac19422a90 add tests for merging conditions and joins 2010-05-25 14:02:26 +04:00
Yura Sokolov
9c0346b90b can accept array for sql sanitizing in conditions 2010-05-25 14:01:53 +04:00
Yura Sokolov
b473d8827f CanDefinition#only_block? 2010-05-25 12:23:39 +04:00
Yura Sokolov
bcab8d6369 fix error with single cannot condition 2010-05-25 12:14:01 +04:00
Yura Sokolov
dbc1538054 small refactoring: CanDefinition #definitive? #conditions_empty? 2010-05-24 18:15:20 +04:00
Yura Sokolov
46f03013f3 Merge remote branch 'upstream/master'
Conflicts:
	lib/cancan/ability.rb
	lib/cancan/active_record_additions.rb
	lib/cancan/can_definition.rb
	spec/cancan/ability_spec.rb
2010-05-24 15:17:10 +04:00
Ryan Bates
1ade44221a load parent resources for collection actions such 'index' 2010-05-21 15:22:21 -07:00
Ryan Bates
2a3dd85a18 adding :name option to load_and_authorize_resource if it does not match controller - closes #65 2010-05-21 14:20:45 -07:00
Ryan Bates
dfd84a10ed improving inline documentation 2010-05-21 13:41:24 -07:00
John Allison
7543eedd6a fixing issue when using accessible_by with nil can conditions - closes #66 2010-05-20 17:06:10 -07:00
Logan Raarup
605063b974 Make sure conditions on associations are pluralized 2010-05-21 07:31:29 +08:00
Sokolov Yura
7d7d249182 passing throw matching rules with not matching conditions
Main goal is to allow:

cannot :manage, :all
can :read, :all
can :manage, User, :id=>user.id
can :manage, User, :manager_id=>user.id

Signed-off-by: Sokolov Yura <funny.falcon@gmail.com>
2010-05-16 22:13:02 +04:00
Ryan Bates
06296b0a40 support has_many association or arrays in can conditions hash 2010-04-22 17:39:22 -07:00
Ryan Bates
e20081454f adding joins clause to accessible_by when conditions are across associations 2010-04-20 17:02:28 -07:00
Ryan Bates
4da31c0709 can has cheezburger? (thanks Seivan) 2010-04-20 14:24:26 -07:00
Ryan Bates
5aa6252df6 removing unused methods and a bit more refactoring 2010-04-18 00:44:42 -07:00
Ryan Bates
bbbc8a68e0 refactoring much of Ability class into separate CanDefinition class 2010-04-18 00:11:15 -07:00
Ryan Bates
232ecd5b4b releasing 1.1.1 which fixes behavior in Rails 3 by properly initializing ResourceAuthorization 2010-04-17 14:01:20 -07:00
Ryan Bates
e1652ea424 adding admin namespace wiki page link to readme 2010-04-17 13:27:01 -07:00
Ryan Bates
b9995c6147 minor changes to readme 2010-04-17 12:37:32 -07:00
Ryan Bates
ff8c11cfc5 releasing version 1.1, see wiki and changelog for details 2010-04-17 12:06:06 -07:00
Ryan Bates
f1ba76b61b supporting arrays, ranges, and nested hashes in ability conditions 2010-04-17 11:54:27 -07:00
Ryan Bates
283f58ee16 improving readme with links to wiki 2010-04-17 11:45:41 -07:00
Ryan Bates
f46696348e allow access to classes when using hash conditions since you'll generally want to narrow it down with a database query 2010-04-16 15:56:07 -07:00
Ryan Bates
8903feee70 removing unauthorized! in favor of authorize! and including more information in AccessDenied exception - closes #40 2010-04-16 14:54:18 -07:00
Ryan Bates
ecf2818a9e removing apparently unnecessary user attr_accessor in Ability 2010-04-16 08:57:10 -07:00
Ryan Bates
d9f3c8b0ae renaming noun to subject internally 2010-04-16 08:55:36 -07:00
Ryan Bates
240c281061 renaming ActiveRecordAdditions#can method to accessible_by since it flows better and makes more sense 2010-04-15 23:54:45 -07:00
Ryan Bates
ef5900c5b1 adding caching to current_ability class method, if you're overriding this be sure to add caching there too 2010-04-15 23:28:04 -07:00
Ryan Bates
37f482e8d5 default ActiveRecordAdditions#can method action to :read and use 'scoped' if 'where' is not available 2010-04-15 23:18:49 -07:00
Ryan Bates
3c68a911d0 adding can method to Active Record for fetching records matching a specific ability, still needs documentation 2010-04-15 17:04:36 -07:00
Ryan Bates
baeef0b9dd adding conditions behavior to Ability#can and fetch with Ability#conditions - closes #53 2010-04-15 16:50:47 -07:00
Ryan Bates
23a5888fe0 renaming :class option to :resource for load_and_authorize_resource which now supports a symbol for non models - closes #45 2010-04-15 14:14:22 -07:00
Ryan Bates
f2a1695636 properly handle Admin::AbilitiesController in params[:controller] - closes #46 2010-04-15 13:10:12 -07:00
Ryan Bates
6e1e96c85a allow additional arguments for be_able_to matcher, this requires Ruby 1.8.7 or higher to use matcher 2010-04-15 12:04:43 -07:00
David Chelimsky
cf49c5b9de add be_able_to matcher 2010-04-16 02:46:03 +08:00
David Chelimsky
35c4864de4 simplify paths 2010-04-16 02:46:02 +08:00
Ryan Bates
510cf509ee adding documentation for passing additional arguments to can? 2010-04-15 11:28:58 -07:00
Ryan Bates
69f7a65914 support additional arguments to can? which get passed to the block - closes #48 2010-04-15 11:21:44 -07:00
Ryan Bates
f027b2ebb3 use Dir globbing more efficiently in gemspec 2010-04-05 08:22:02 -07:00
Ryan Bates
5d4138f0b2 cleaning up gemspec 2010-04-02 15:25:38 -07:00
Ryan Bates
3b9cdce09a releasing v1.0.2 2009-12-30 21:33:31 -08:00
Ryan Bates
a13f78d6f9 listing additional resources at top of readme page (including metrics and tests) 2009-12-30 20:29:19 -08:00
Ryan Bates
41f67ad6d0 making spec the default rake task so it works at runcoderun.com 2009-12-30 20:22:26 -08:00
Ryan Bates
7d3b4cdbc2 Adding clear_aliased_actions to Ability which removes previously defined actions including defaults 2009-12-30 18:01:40 -08:00
Ryan Bates
f99d506050 Append aliased actions (don't overwrite them) - closes #20 2009-12-30 17:49:49 -08:00
Ryan Bates
ef22de689b adding custom message argument to unauthorized! method - closes #18 2009-12-15 10:53:05 -08:00
Ryan Bates
67416532f4 adding Railscasts episode to documentation 2009-12-14 09:42:51 -08:00
Ryan Bates
f919ac53bb releasing gem v1.0.1 2009-12-14 08:37:30 -08:00
Ryan Bates
021f33c9a0 Adding :class option to load_resource so one can customize which class to use for the model - closes #17 2009-12-14 08:31:49 -08:00
Ryan Bates
e9f01300b6 Don't fetch parent of nested resource if *_id parameter is missing so it works with shallow nested routes - closes #14 2009-12-14 08:18:08 -08:00
26 changed files with 1693 additions and 629 deletions

View File

@@ -1,3 +1,111 @@
1.3.4 (August 31, 2010)
* Don't stop at +cannot+ with hash conditions when checking class (thanks tamoya) - see issue #131
1.3.3 (August 20, 2010)
* Switching to Rspec namespace to remove deprecation warning in Rspec 2 - see issue #119
* Pluralize nested associations for conditions in accessible_by (thanks mlooney) - see issue #123
1.3.2 (August 7, 2010)
* Fixing slice error when passing in custom resource name - see issue #112
1.3.1 (August 6, 2010)
* Fixing protected sanitize_sql error - see issue #111
1.3.0 (August 6, 2010)
* Adding :find_by option to load_resource - see issue #19
* Adding :singleton option to load_resource - see issue #93
* Supporting multiple resources in :through option for polymorphic associations - see issue #73
* Supporting Single Table Inheritance for "can" comparisons - see issue #55
* Adding :instance_name option to load/authorize_resource - see issue #44
* Don't pass nil to "new" to keep MongoMapper happy - see issue #63
* Parent resources are now authorized with :read action.
* Changing :resource option in load/authorize_resource back to :class with ability to pass false
* Removing :nested option in favor of :through option with separate load/authorize call
* Moving internal logic from ResourceAuthorization to ControllerResource class
* Supporting multiple "can" and "cannot" calls with accessible_by (thanks funny-falcon) - see issue #71
* Supporting deeply nested aliases - see issue #98
1.2.0 (July 16, 2010)
* Load nested parent resources on collection actions such as "index" (thanks dohzya)
* Adding :name option to load_and_authorize_resource if it does not match controller - see issue #65
* Fixing issue when using accessible_by with nil can conditions (thanks jrallison) - see issue #66
* Pluralize table name for belongs_to associations in can conditions hash (thanks logandk) - see issue #62
* Support has_many association or arrays in can conditions hash
* Adding joins clause to accessible_by when conditions are across associations
1.1.1 (April 17, 2010)
* Fixing behavior in Rails 3 by properly initializing ResourceAuthorization
1.1.0 (April 17, 2010)
* Supporting arrays, ranges, and nested hashes in ability conditions
* Removing "unauthorized!" method in favor of "authorize!" in controllers
* Adding action, subject and default_message abilities to AccessDenied exception - see issue #40
* Adding caching to current_ability controller method, if you're overriding this be sure to add caching too.
* Adding "accessible_by" method to Active Record for fetching records matching a specific ability
* Adding conditions behavior to Ability#can and fetch with Ability#conditions - see issue #53
* Renaming :class option to :resource for load_and_authorize_resource which now supports a symbol for non models - see issue #45
* Properly handle Admin::AbilitiesController in params[:controller] - see issue #46
* Adding be_able_to RSpec matcher (thanks dchelimsky), requires Ruby 1.8.7 or higher - see issue #54
* Support additional arguments to can? which get passed to the block - see issue #48
1.0.2 (Dec 30, 2009)
* Adding clear_aliased_actions to Ability which removes previously defined actions including defaults - see issue #20
* Append aliased actions (don't overwrite them) - see issue #20
* Adding custom message argument to unauthorized! method (thanks tjwallace) - see issue #18
1.0.1 (Dec 14, 2009)
* Adding :class option to load_resource so one can customize which class to use for the model - see issue #17
* Don't fetch parent of nested resource if *_id parameter is missing so it works with shallow nested routes - see issue #14
1.0.0 (Dec 13, 2009)
* Don't set resource instance variable if it has been set already - see issue #13

View File

@@ -1,29 +1,30 @@
= CanCan
This is a simple authorization solution for Ruby on Rails to restrict what a given user is allowed to access in the application. This is completely decoupled from any role based implementation allowing you to define user roles the way you want. All permissions are stored in a single location for convenience.
Wiki[http://wiki.github.com/ryanb/cancan] | RDocs[http://rdoc.info/projects/ryanb/cancan] | Screencast[http://railscasts.com/episodes/192-authorization-with-cancan]
This assumes you already have authentication (such as Authlogic[http://github.com/binarylogic/authlogic]) which provides a current_user model.
CanCan is an authorization solution for Ruby on Rails for restricting what a given user is allowed to access throughout the application. It does not care how your user roles are defined, it simply focusses on keeping permission logic in a single location (the +Ability+ class) so it is not duplicated across controllers, views, and database queries.
By default, the +current_user+ method is required, so if you have not already, set up some authentication (such as Authlogic[http://github.com/binarylogic/authlogic] or Devise[http://github.com/plataformatec/devise]). See {Changing Defaults}[http://wiki.github.com/ryanb/cancan/changing-defaults] if you need different behavior.
See the RDocs[http://rdoc.info/projects/ryanb/cancan] and Wiki[http://wiki.github.com/ryanb/cancan] for additional documentation.
== Installation
You can set it up as a gem in your environment.rb file.
To install CanCan, include the gem in the environment.rb in Rails 2.3.
config.gem "cancan"
And then install the gem.
Or the Gemfile in Rails 3.
sudo rake gems:install
gem "cancan"
Alternatively you can install it as a Rails plugin.
Alternatively it can be installed as a plugin.
script/plugin install git://github.com/ryanb/cancan.git
== Getting Started
First, define a class called Ability in "models/ability.rb".
First, define a class called +Ability+ in "models/ability.rb" or anywhere else in the load path. It should look something like this.
class Ability
include CanCan::Ability
@@ -39,169 +40,113 @@ First, define a class called Ability in "models/ability.rb".
This is where all permissions will go. See the "Defining Abilities" section below for more information.
You can access the current permissions at any point using the "can?" and "cannot?" methods in the view.
The current user's permissions can be accessed using the "can?" and "cannot?" methods in the view and controller.
<% if can? :update, @article %>
<%= link_to "Edit", edit_article_path(@article) %>
<% end %>
You can also use these methods in a controller along with the "unauthorized!" method to restrict access.
See {Checking Abilities}[http://wiki.github.com/ryanb/cancan/checking-abilities] for more information
The "authorize!" method in the controller will raise an exception if the user is not able to perform the given action.
def show
@article = Article.find(params[:id])
unauthorized! if cannot? :read, @article
authorize! :read, @article
end
Setting this for every action can be tedious, therefore the load_and_authorize_resource method is also provided to automatically authorize all actions in a RESTful style resource controller. It will set up a before filter which loads the resource into the instance variable and authorizes it.
Setting this for every action can be tedious, therefore the +load_and_authorize_resource+ method is provided to automatically authorize all actions in a RESTful style resource controller. It will use a before filter to load the resource into an instance variable and authorize it for each action.
class ArticlesController < ApplicationController
load_and_authorize_resource
def show
# @article is already loaded
# @article is already loaded and authorized
end
end
If the user authorization fails, a CanCan::AccessDenied exception will be raised. You can catch this and modify its behavior in the ApplicationController.
See {Authorizing Controller Actions}[http://wiki.github.com/ryanb/cancan/authorizing-controller-actions] for more information
If the user authorization fails, a CanCan::AccessDenied exception will be raised. You can catch this and modify its behavior in the +ApplicationController+.
class ApplicationController < ActionController::Base
rescue_from CanCan::AccessDenied, :with => :access_denied
protected
def access_denied
flash[:error] = "Sorry, you are not allowed to access that page."
rescue_from CanCan::AccessDenied do |exception|
flash[:error] = exception.message
redirect_to root_url
end
end
See {Exception Handling}[http://wiki.github.com/ryanb/cancan/exception-handling] for more information.
== Defining Abilities
As shown above, the Ability class is where all user permissions are defined. The user model is passed into the initialize method so you are free to modify the permissions based on the user's attributes. This way CanCan is completely decoupled with how you choose to handle roles.
As shown above, the +Ability+ class is where all user permissions are defined. The user model is passed into the initialize method so the permissions can be modified based on any user attributes. CanCan makes no assumptions about how roles are handled in your application. See {Role Based Authorization}[http://wiki.github.com/ryanb/cancan/role-based-authorization] for an example.
The "can" method accepts two arguments, the first one is the action you're setting the permission for, the second one is the class of object you're setting it on.
The +can+ method is used to define permissions and requires two arguments. The first one is the action you're setting the permission for, the second one is the class of object you're setting it on.
can :update, Article
You can pass an array for either of these parameters to match any one.
You can pass an array for either of these parameters to match any one. In this case the user will have the ability to update or destroy both articles and comments.
can [:update, :destroy], [Article, Comment]
In this case the user has the ability to update or destroy both articles and comments.
Use :+manage+ to represent any action and :+all+ to represent any class. Here are some examples.
You can pass a block to provide logic based on the article's attributes.
can :manage, Article # has permissions to do anything to articles
can :read, :all # has permission to read any model
can :manage, :all # has permission to do anything to any model
can :update, Article do |article|
article && article.user == user
You can pass a hash of conditions as the third argument to further restrict what the user is able to access. Here the user will only have permission to read active projects which he owns.
can :read, Project, :active => true, :user_id => user.id
See {Defining Abilities with Hashes}[http://wiki.github.com/ryanb/cancan/defining-abilities-with-hashes] for more information.
Blocks can also be used if you need more control.
can :update, Project do |project|
project && project.groups.include?(user.group)
end
If the block returns true then the user has that :update ability for that article, otherwise he will be denied access. It's possible for the passed in model to be nil if one isn't specified, so be sure to take that into consideration.
You can pass :all to reference every type of object. In this case the object type will be passed into the block as well (just in case object is nil).
can :read, :all do |object_class, object|
object_class != Order
end
Here the user has permission to read all objects except orders.
You can also pass :manage as the action which will match any action. In this case the action is passed to the block.
can :manage, Comment do |action, comment|
action != :destroy
end
Finally, the "cannot" method works similar to "can" but defines which abilities cannot be done.
can :read, :all
cannot :read, Product
== Checking Abilities
Use the "can?" method in the controller or view to check the user's permission for a given action and object.
can? :destroy, @project
You can also pass the class instead of an instance (if you don't have one handy).
<% if can? :create, Project %>
<%= link_to "New Project", new_project_path %>
<% end %>
The "cannot?" method is for convenience and performs the opposite check of "can?"
cannot? :destroy, @project
If the block returns true then the user has that :+update+ ability for that project, otherwise he will be denied access. See {Defining Abilities with Blocks}[http://wiki.github.com/ryanb/cancan/defining-abilities-with-blocks] for more information.
== Aliasing Actions
You can use the "alias_action" method to alias one or more actions into one.
alias_action :update, :destroy, :to => :modify
can :modify, Comment
can? :update, Comment # => true
The following aliases are added by default for conveniently mapping common controller actions.
You will usually be working with four actions when defining and checking permissions: :+read+, :+create+, :+update+, :+destroy+. These aren't the same as the 7 RESTful actions in Rails. CanCan automatically adds some default aliases for mapping those actions.
alias_action :index, :show, :to => :read
alias_action :new, :to => :create
alias_action :edit, :to => :update
Notice the +edit+ action is aliased to +update+. If the user is able to update a record he also has permission to edit it. You can define your own aliases in the +Ability+ class
== Authorizing Controller Actions
alias_action :update, :destroy, :to => :modify
can :modify, Comment
can? :update, Comment # => true
As mentioned in the Getting Started section, you can use the +load_and_authorize_resource+ method in your controller to load the resource into an instance variable and authorize it. If you have a nested resource you can specify that as well.
load_and_authorize_resource :nested => :author
You can also pass an array to the :+nested+ attribute for deep nesting.
If you want to customize the loading behavior on certain actions, you can do so in a before filter.
class BooksController < ApplicationController
before_filter :find_book_by_permalink, :only => :show
load_and_authorize_resource
private
def find_book_by_permalink
@book = Book.find_by_permalink!(params[:id)
end
end
Here the @book instance variable is already set so it will not be loaded again for that action. This works for nested resources as well.
See {Custom Actions}[http://wiki.github.com/ryanb/cancan/custom-actions] for information on adding other actions.
== Assumptions & Configuring
== Fetching Records
CanCan makes two assumptions about your application.
In the controller +index+ action you may want to fetch only the records which the user has permission to read. You can do this with the +accessible_by+ scope.
* You have an Ability class which defines the permissions.
* You have a current_user method in the controller which returns the current user model.
@articles = Article.accessible_by(current_ability)
You can override these by overriding the "current_ability" method in your ApplicationController.
def current_ability
UserAbility.new(current_account) # instead of Ability.new(current_user)
end
That's it!
This will only work when abilities are defined using hash conditions, not blocks. See {Fetching Records}[http://wiki.github.com/ryanb/cancan/fetching-records] for more information.
== Testing Abilities
It is very easy to test the Ability model since you can call "can?" directly on it as you would in the view or controller.
def test "user can only destroy projects which he owns"
user = User.new
ability = Ability.new(user)
assert ability.can?(:destroy, Project.new(:user => user))
assert ability.cannot?(:destroy, Project.new)
end
== Additional Docs
* {Upgrading to 1.3}[http://wiki.github.com/ryanb/cancan/upgrading-to-13]
* {Nested Resources}[http://wiki.github.com/ryanb/cancan/nested-resources]
* {Testing Abilities}[http://wiki.github.com/ryanb/cancan/testing-abilities]
* {Accessing Request Data}[http://wiki.github.com/ryanb/cancan/accessing-request-data]
* {Admin Namespace}[http://wiki.github.com/ryanb/cancan/admin-namespace]
* {See more}[http://wiki.github.com/ryanb/cancan/]
== Special Thanks
CanCan was inspired by declarative_authorization[http://github.com/stffn/declarative_authorization/] and aegis[http://github.com/makandra/aegis]. Many thanks to the authors and contributors.
CanCan was inspired by declarative_authorization[http://github.com/stffn/declarative_authorization/] and aegis[http://github.com/makandra/aegis]. Also many thanks to the CanCan contributors[http://github.com/ryanb/cancan/contributors]. See the CHANGELOG[http://github.com/ryanb/cancan/blob/master/CHANGELOG.rdoc] for the full list.

View File

@@ -9,3 +9,5 @@ Spec::Rake::SpecTask.new do |t|
t.spec_files = spec_files
t.spec_opts = ["-c"]
end
task :default => :spec

View File

@@ -1,22 +1,15 @@
Gem::Specification.new do |s|
s.name = "cancan"
s.summary = "Simple authorization solution for Rails."
s.description = "Simple authorization solution for Rails which is completely decoupled from the user's roles. All permissions are stored in a single location for convenience."
s.homepage = "http://github.com/ryanb/cancan"
s.name = "cancan"
s.version = "1.3.4"
s.author = "Ryan Bates"
s.email = "ryan@railscasts.com"
s.homepage = "http://github.com/ryanb/cancan"
s.summary = "Simple authorization solution for Rails."
s.description = "Simple authorization solution for Rails which is decoupled from user roles. All permissions are stored in a single location."
s.version = "1.0.0"
s.date = "2009-12-13"
s.files = Dir["{lib,spec}/**/*", "[A-Z]*", "init.rb"]
s.require_path = "lib"
s.authors = ["Ryan Bates"]
s.email = "ryan@railscasts.com"
s.require_paths = ["lib"]
s.files = Dir["lib/**/*"] + Dir["spec/**/*"] + ["LICENSE", "README.rdoc", "Rakefile", "CHANGELOG.rdoc", "init.rb"]
s.extra_rdoc_files = ["README.rdoc", "CHANGELOG.rdoc", "LICENSE"]
s.has_rdoc = true
s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "CanCan", "--main", "README.rdoc"]
s.rubygems_version = "1.3.4"
s.required_rubygems_version = Gem::Requirement.new(">= 1.2")
s.rubyforge_project = s.name
s.required_rubygems_version = ">= 1.3.4"
end

View File

@@ -1,10 +1,7 @@
module CanCan
# This error is raised when a user isn't allowed to access a given
# controller action. See ControllerAdditions#unauthorized! for details.
class AccessDenied < StandardError; end
end
require File.dirname(__FILE__) + '/cancan/ability'
require File.dirname(__FILE__) + '/cancan/controller_resource'
require File.dirname(__FILE__) + '/cancan/resource_authorization'
require File.dirname(__FILE__) + '/cancan/controller_additions'
require 'cancan/ability'
require 'cancan/can_definition'
require 'cancan/controller_resource'
require 'cancan/controller_additions'
require 'cancan/active_record_additions'
require 'cancan/exceptions'
require 'cancan/query'

View File

@@ -16,9 +16,7 @@ module CanCan
# end
#
module Ability
attr_accessor :user
# Use to check the user's permission for a given action and object.
# Use to check if the user has permission to perform a given action on an object.
#
# can? :destroy, @project
#
@@ -26,6 +24,15 @@ module CanCan
#
# can? :create, Project
#
# Any additional arguments will be passed into the "can" block definition. This
# can be used to pass more information about the user's request for example.
#
# can? :create, Project, request.remote_ip
#
# can :create Project do |project, remote_ip|
# # ...
# end
#
# Not only can you use the can? method in the controller and view (see ControllerAdditions),
# but you can also call it directly on an ability instance.
#
@@ -40,16 +47,13 @@ module CanCan
# assert ability.cannot?(:destroy, Project.new)
# end
#
def can?(action, noun)
(@can_definitions || []).reverse.each do |base_behavior, defined_action, defined_noun, defined_block|
defined_actions = expand_actions(defined_action)
defined_nouns = [defined_noun].flatten
if includes_action?(defined_actions, action) && includes_noun?(defined_nouns, noun)
result = can_perform_action?(action, noun, defined_actions, defined_nouns, defined_block)
return base_behavior ? result : !result
end
# Also see the RSpec Matchers to aid in testing.
def can?(action, subject, *extra_args)
raise Error, "Nom nom nom. I eated it." if action == :has && subject == :cheezburger
match = relevant_can_definitions(action, subject).detect do |can_definition|
can_definition.matches_conditions?(action, subject, extra_args)
end
false
match ? match.base_behavior : false
end
# Convenience method which works the same as "can?" but returns the opposite value.
@@ -71,16 +75,26 @@ module CanCan
#
# In this case the user has the ability to update or destroy both articles and comments.
#
# You can pass a block to provide logic based on the article's attributes.
# You can pass a hash of conditions as the third argument.
#
# can :update, Article do |article|
# article && article.user == user
# can :read, Project, :active => true, :user_id => user.id
#
# Here the user can only see active projects which he owns. See ActiveRecordAdditions#accessible_by
# for how to use this in database queries.
#
# If the conditions hash does not give you enough control over defining abilities, you can use a block to
# write any Ruby code you want.
#
# can :update, Project do |project|
# project && project.groups.include?(user.group)
# end
#
# If the block returns true then the user has that :update ability for that article, otherwise he
# If the block returns true then the user has that :update ability for that project, otherwise he
# will be denied access. It's possible for the passed in model to be nil if one isn't specified,
# so be sure to take that into consideration.
#
# The downside to using a block is that it cannot be used to generate conditions for database queries.
#
# You can pass :all to reference every type of object. In this case the object type will be passed
# into the block as well (just in case object is nil).
#
@@ -103,12 +117,11 @@ module CanCan
# can :read, :stats
# can? :read, :stats # => true
#
def can(action, noun, &block)
@can_definitions ||= []
@can_definitions << [true, action, noun, block]
def can(action, subject, conditions = nil, &block)
can_definitions << CanDefinition.new(true, action, subject, conditions, block)
end
# Define an ability which cannot be done. Accepts the same arguments as "can".
# Defines an ability which cannot be done. Accepts the same arguments as "can".
#
# can :read, :all
# cannot :read, Comment
@@ -120,9 +133,8 @@ module CanCan
# product.invisible?
# end
#
def cannot(action, noun, &block)
@can_definitions ||= []
@can_definitions << [false, action, noun, block]
def cannot(action, subject, conditions = nil, &block)
can_definitions << CanDefinition.new(false, action, subject, conditions, block)
end
# Alias one or more actions into another one.
@@ -156,13 +168,57 @@ module CanCan
# This way one can use params[:action] in the controller to determine the permission.
def alias_action(*args)
target = args.pop[:to]
aliased_actions[target] = args
aliased_actions[target] ||= []
aliased_actions[target] += args
end
# Returns a hash of aliased actions. The key is the target and the value is an array of actions aliasing the key.
def aliased_actions
@aliased_actions ||= default_alias_actions
end
# Removes previously aliased actions including the defaults.
def clear_aliased_actions
@aliased_actions = {}
end
# Returns a CanCan::Query instance to help generate database queries based on the ability.
# If any relevant can definitions use a block then an exception will be raised because an
# SQL query cannot be generated from blocks of code.
def query(action, subject)
Query.new(subject, relevant_can_definitions_for_query(action, subject))
end
private
def aliased_actions
@aliased_actions ||= default_alias_actions
# Accepts a hash of aliased actions and returns an array of actions which match.
# This should be called before "matches?" and other checking methods since they
# rely on the actions to be expanded.
def expand_actions(actions)
actions.map do |action|
aliased_actions[action] ? [action, *expand_actions(aliased_actions[action])] : action
end.flatten
end
def can_definitions
@can_definitions ||= []
end
# Returns an array of CanDefinition instances which match the action and subject
# This does not take into consideration any hash conditions or block statements
def relevant_can_definitions(action, subject)
can_definitions.reverse.select do |can_definition|
can_definition.expanded_actions = expand_actions(can_definition.actions)
can_definition.relevant? action, subject
end
end
def relevant_can_definitions_for_query(action, subject)
relevant_can_definitions(action, subject).each do |can_definition|
if can_definition.only_block?
raise Error, "The accessible_by call cannot be used with a block 'can' definition. The SQL cannot be determined for #{action.inspect} #{subject.inspect}"
end
end
end
def default_alias_actions
@@ -172,35 +228,5 @@ module CanCan
:update => [:edit],
}
end
def expand_actions(actions)
[actions].flatten.map do |action|
if aliased_actions[action]
[action, *aliased_actions[action]]
else
action
end
end.flatten
end
def can_perform_action?(action, noun, defined_actions, defined_nouns, defined_block)
if defined_block.nil?
true
else
block_args = []
block_args << action if defined_actions.include?(:manage)
block_args << (noun.class == Class ? noun : noun.class) if defined_nouns.include?(:all)
block_args << (noun.class == Class ? nil : noun)
return defined_block.call(*block_args)
end
end
def includes_action?(actions, action)
actions.include?(:manage) || actions.include?(action)
end
def includes_noun?(nouns, noun)
nouns.include?(:all) || nouns.include?(noun) || nouns.any? { |c| c.kind_of?(Class) && noun.kind_of?(c) }
end
end
end

View File

@@ -0,0 +1,42 @@
module CanCan
# This module is automatically included into all Active Record models.
module ActiveRecordAdditions
module ClassMethods
# Returns a scope which fetches only the records that the passed ability
# can perform a given action on. The action defaults to :read. This
# is usually called from a controller and passed the +current_ability+.
#
# @articles = Article.accessible_by(current_ability)
#
# Here only the articles which the user is able to read will be returned.
# If the user does not have permission to read any articles then an empty
# result is returned. Since this is a scope it can be combined with any
# other scopes or pagination.
#
# An alternative action can optionally be passed as a second argument.
#
# @articles = Article.accessible_by(current_ability, :update)
#
# Here only the articles which the user can update are returned. This
# internally uses Ability#conditions method, see that for more information.
def accessible_by(ability, action = :read)
query = ability.query(action, self)
if respond_to? :where
where(query.conditions).joins(query.joins)
else
scoped(:conditions => query.conditions, :joins => query.joins)
end
end
end
def self.included(base)
base.extend ClassMethods
end
end
end
if defined? ActiveRecord
ActiveRecord::Base.class_eval do
include CanCan::ActiveRecordAdditions
end
end

View File

@@ -0,0 +1,104 @@
module CanCan
# This class is used internally and should only be called through Ability.
# it holds the information about a "can" call made on Ability and provides
# helpful methods to determine permission checking and conditions hash generation.
class CanDefinition # :nodoc:
attr_reader :base_behavior, :actions
attr_writer :expanded_actions
# The first argument when initializing is the base_behavior which is a true/false
# value. True for "can" and false for "cannot". The next two arguments are the action
# and subject respectively (such as :read, @project). The third argument is a hash
# of conditions and the last one is the block passed to the "can" call.
def initialize(base_behavior, action, subject, conditions, block)
@base_behavior = base_behavior
@actions = [action].flatten
@subjects = [subject].flatten
@conditions = conditions || {}
@block = block
end
# Matches both the subject and action, not necessarily the conditions
def relevant?(action, subject)
matches_action?(action) && matches_subject?(subject)
end
# Matches the block or conditions hash
def matches_conditions?(action, subject, extra_args)
if @block
call_block(action, subject, extra_args)
elsif @conditions.kind_of?(Hash) && subject.class != Class
matches_conditions_hash?(subject)
else
@base_behavior
end
end
def tableized_conditions(conditions = @conditions)
conditions.inject({}) do |result_hash, (name, value)|
if value.kind_of? Hash
name = name.to_s.tableize.to_sym
value = tableized_conditions(value)
end
result_hash[name] = value
result_hash
end
end
def only_block?
conditions_empty? && !@block.nil?
end
def conditions_empty?
@conditions == {} || @conditions.nil?
end
def associations_hash(conditions = @conditions)
hash = {}
conditions.map do |name, value|
hash[name] = associations_hash(value) if value.kind_of? Hash
end
hash
end
private
def matches_action?(action)
@expanded_actions.include?(:manage) || @expanded_actions.include?(action)
end
def matches_subject?(subject)
@subjects.include?(:all) || @subjects.include?(subject) || matches_subject_class?(subject)
end
def matches_subject_class?(subject)
@subjects.any? { |sub| sub.kind_of?(Class) && (subject.kind_of?(sub) || subject.kind_of?(Class) && subject.ancestors.include?(sub)) }
end
def matches_conditions_hash?(subject, conditions = @conditions)
conditions.all? do |name, value|
attribute = subject.send(name)
if value.kind_of?(Hash)
if attribute.kind_of? Array
attribute.any? { |element| matches_conditions_hash? element, value }
else
matches_conditions_hash? attribute, value
end
elsif value.kind_of?(Array) || value.kind_of?(Range)
value.include? attribute
else
attribute == value
end
end
end
def call_block(action, subject, extra_args)
block_args = []
block_args << action if @expanded_actions.include?(:manage)
block_args << (subject.class == Class ? subject : subject.class) if @subjects.include?(:all)
block_args << (subject.class == Class ? nil : subject)
block_args += extra_args
@block.call(*block_args)
end
end
end

View File

@@ -11,11 +11,11 @@ module CanCan
# load_and_authorize_resource
# end
#
def load_and_authorize_resource(options = {})
before_filter(options.slice(:only, :except)) { |c| ResourceAuthorization.new(c, c.params, options.except(:only, :except)).load_and_authorize_resource }
def load_and_authorize_resource(*args)
ControllerResource.add_before_filter(self, :load_and_authorize_resource, *args)
end
# Sets up a before filter which loads the appropriate model resource into an instance variable.
# Sets up a before filter which loads the model resource into an instance variable.
# For example, given an ArticlesController it will load the current article into the @article
# instance variable. It does this by either calling Article.find(params[:id]) or
# Article.new(params[:article]) depending upon the action. It does nothing for the "index"
@@ -41,6 +41,20 @@ module CanCan
# end
# end
#
# If a name is provided which does not match the controller it assumes it is a parent resource. Child
# resources can then be loaded through it.
#
# class BooksController < ApplicationController
# load_resource :author
# load_resource :book, :through => :author
# end
#
# Here the author resource will be loaded before each action using params[:author_id]. The book resource
# will then be loaded through the @author instance variable.
#
# That first argument is optional and will default to the singular name of the controller.
# A hash of options (see below) can also be passed to this method to further customize it.
#
# See load_and_authorize_resource to automatically authorize the resource too.
#
# Options:
@@ -50,19 +64,30 @@ module CanCan
# [:+except+]
# Does not apply before filter to given actions.
#
# [:+nested+]
# Specify which resource this is nested under.
# [:+through+]
# Load this resource through another one. This should match the name of the parent instance variable.
#
# load_resource :nested => :author
# [:+singleton+]
# Pass +true+ if this is a singleton resource through a +has_one+ association.
#
# Deep nesting can be defined in an array.
# [:+parent+]
# True or false depending on if the resource is considered a parent resource. This defaults to +true+ if a resource
# name is given which does not match the controller.
#
# load_resource :nested => [:publisher, :author]
# [:+class+]
# The class to use for the model (string or constant).
#
# [:+instance_name+]
# The name of the instance variable to load the resource into.
#
# [:+find_by+]
# Find using a different attribute other than id. For example.
#
# load_resource :find_by => :permalink # will use find_by_permlink!(params[:id])
#
# [:+collection+]
# Specify which actions are resource collection actions in addition to :+index+. This
# is usually not necessary because it will try to guess depending on if an :+id+
# is present in +params+.
# is usually not necessary because it will try to guess depending on if the id param is present.
#
# load_resource :collection => [:sort, :list]
#
@@ -73,16 +98,16 @@ module CanCan
#
# load_resource :new => :build
#
def load_resource(options = {})
before_filter(options.slice(:only, :except)) { |c| ResourceAuthorization.new(c, c.params, options.except(:only, :except)).load_resource }
def load_resource(*args)
ControllerResource.add_before_filter(self, :load_resource, *args)
end
# Sets up a before filter which authorizes the current resource using the instance variable.
# Sets up a before filter which authorizes the resource using the instance variable.
# For example, if you have an ArticlesController it will check the @article instance variable
# and ensure the user can perform the current action on it. Under the hood it is doing
# something like the following.
#
# unauthorized! if cannot?(params[:action].to_sym, @article || Article)
# authorize!(params[:action].to_sym, @article || Article)
#
# Call this method directly on the controller class.
#
@@ -90,6 +115,19 @@ module CanCan
# authorize_resource
# end
#
# If you pass in the name of a resource which does not match the controller it will assume
# it is a parent resource.
#
# class BooksController < ApplicationController
# authorize_resource :author
# authorize_resource :book
# end
#
# Here it will authorize :+show+, @+author+ on every action before authorizing the book.
#
# That first argument is optional and will default to the singular name of the controller.
# A hash of options (see below) can also be passed to this method to further customize it.
#
# See load_and_authorize_resource to automatically load the resource too.
#
# Options:
@@ -99,8 +137,19 @@ module CanCan
# [:+except+]
# Does not apply before filter to given actions.
#
def authorize_resource(options = {})
before_filter(options.slice(:only, :except)) { |c| ResourceAuthorization.new(c, c.params, options.except(:only, :except)).authorize_resource }
# [:+parent+]
# True or false depending on if the resource is considered a parent resource. This defaults to +true+ if a resource
# name is given which does not match the controller.
#
# [:+class+]
# The class to use for the model (string or constant). This passed in when the instance variable is not set.
# Pass +false+ if there is no associated class for this resource and it will use a symbol of the resource name.
#
# [:+instance_name+]
# The name of the instance variable for this resource.
#
def authorize_resource(*args)
ControllerResource.add_before_filter(self, :authorize_resource, *args)
end
end
@@ -109,44 +158,58 @@ module CanCan
base.helper_method :can?, :cannot?
end
# Raises the CanCan::AccessDenied exception. This is often used in a
# controller action to mark a request as unauthorized.
# Raises a CanCan::AccessDenied exception if the current_ability cannot
# perform the given action. This is usually called in a controller action or
# before filter to perform the authorization.
#
# def show
# @article = Article.find(params[:id])
# unauthorized! if cannot? :read, @article
# authorize! :read, @article
# end
#
# You can rescue from the exception in the controller to specify
# the user experience.
# A :message option can be passed to specify a different message.
#
# authorize! :read, @article, :message => "Not authorized to read #{@article.name}"
#
# You can rescue from the exception in the controller to customize how unauthorized
# access is displayed to the user.
#
# class ApplicationController < ActionController::Base
# rescue_from CanCan::AccessDenied, :with => :access_denied
#
# protected
#
# def access_denied
# flash[:error] = "Sorry, you are not allowed to access that page."
# rescue_from CanCan::AccessDenied do |exception|
# flash[:error] = exception.message
# redirect_to root_url
# end
# end
#
# See the load_and_authorize_resource method to automatically add
# the "unauthorized!" behavior to a RESTful controller's actions.
def unauthorized!
raise AccessDenied, "You are unable to access this page."
# See the CanCan::AccessDenied exception for more details on working with the exception.
#
# See the load_and_authorize_resource method to automatically add the authorize! behavior
# to the default RESTful actions.
def authorize!(action, subject, *args)
message = nil
if args.last.kind_of?(Hash) && args.last.has_key?(:message)
message = args.pop[:message]
end
raise AccessDenied.new(message, action, subject) if cannot?(action, subject, *args)
end
# Creates and returns the current user's ability. You generally do not invoke
# this method directly, instead you can override this method to change its
# behavior if the Ability class or current_user method are different.
def unauthorized!(message = nil)
raise ImplementationRemoved, "The unauthorized! method has been removed from CanCan, use authorize! instead."
end
# Creates and returns the current user's ability and caches it. If you
# want to override how the Ability is defined then this is the place.
# Just define the method in the controller to change behavior.
#
# def current_ability
# UserAbility.new(current_account) # instead of Ability.new(current_user)
# # instead of Ability.new(current_user)
# @current_ability ||= UserAbility.new(current_account)
# end
#
# Notice it is important to cache the ability object so it is not
# recreated every time.
def current_ability
::Ability.new(current_user)
@current_ability ||= ::Ability.new(current_user)
end
# Use in the controller or view to check the user's permission for a given action
@@ -162,7 +225,7 @@ module CanCan
#
# This simply calls "can?" on the current_ability. See Ability#can?.
def can?(*args)
(@current_ability ||= current_ability).can?(*args)
current_ability.can?(*args)
end
# Convenience method which works the same as "can?" but returns the opposite value.
@@ -170,7 +233,7 @@ module CanCan
# cannot? :destroy, @project
#
def cannot?(*args)
(@current_ability ||= current_ability).cannot?(*args)
current_ability.cannot?(*args)
end
end
end

View File

@@ -1,39 +1,129 @@
module CanCan
# Handle the load and authorization controller logic so we don't clutter up all controllers with non-interface methods.
# This class is used internally, so you do not need to call methods directly on it.
class ControllerResource # :nodoc:
def initialize(controller, name, parent = nil)
@controller = controller
@name = name
@parent = parent
end
def model_class
@name.to_s.camelize.constantize
end
def find(id)
self.model_instance ||= base.find(id)
end
def build(attributes)
if base.kind_of? Class
self.model_instance ||= base.new(attributes)
else
self.model_instance ||= base.build(attributes)
def self.add_before_filter(controller_class, method, *args)
options = args.extract_options!
resource_name = args.first
controller_class.before_filter(options.slice(:only, :except)) do |controller|
ControllerResource.new(controller, resource_name, options.except(:only, :except)).send(method)
end
end
def model_instance
@controller.instance_variable_get("@#{@name}")
def initialize(controller, *args)
@controller = controller
@params = controller.params
@options = args.extract_options!
@name = args.first
raise CanCan::ImplementationRemoved, "The :nested option is no longer supported, instead use :through with separate load/authorize call." if @options[:nested]
raise CanCan::ImplementationRemoved, "The :name option is no longer supported, instead pass the name as the first argument." if @options[:name]
raise CanCan::ImplementationRemoved, "The :resource option has been renamed back to :class, use false if no class." if @options[:resource]
end
def model_instance=(instance)
@controller.instance_variable_set("@#{@name}", instance)
def load_and_authorize_resource
load_resource
authorize_resource
end
def load_resource
if !resource_instance && (parent? || member_action?)
@controller.instance_variable_set("@#{instance_name}", load_resource_instance)
end
end
def authorize_resource
@controller.authorize!(authorization_action, resource_instance || resource_class)
end
def parent?
@options.has_key?(:parent) ? @options[:parent] : @name && @name != name_from_controller.to_sym
end
private
def base
@parent ? @parent.model_instance.send(@name.to_s.pluralize) : model_class
def load_resource_instance
if !parent? && new_actions.include?(@params[:action].to_sym)
build_resource
elsif id_param || @options[:singleton]
find_resource
end
end
def build_resource
method_name = @options[:singleton] ? "build_#{name}" : "new"
resource_base.send(*[method_name, @params[name]].compact)
end
def find_resource
if @options[:singleton]
resource_base.send(name)
else
@options[:find_by] ? resource_base.send("find_by_#{@options[:find_by]}!", id_param) : resource_base.find(id_param)
end
end
def authorization_action
parent? ? :read : @params[:action].to_sym
end
def id_param
@params[parent? ? :"#{name}_id" : :id]
end
def member_action?
!collection_actions.include? @params[:action].to_sym
end
# Returns the class used for this resource. This can be overriden by the :class option.
# If +false+ is passed in it will use the resource name as a symbol in which case it should
# only be used for authorization, not loading since there's no class to load through.
def resource_class
case @options[:class]
when false then name.to_sym
when nil then name.to_s.camelize.constantize
when String then @options[:class].constantize
else @options[:class]
end
end
def resource_instance
@controller.instance_variable_get("@#{instance_name}")
end
# The object that methods (such as "find", "new" or "build") are called on.
# If the :through option is passed it will go through an association on that instance.
# If the :singleton option is passed it won't use the association because it needs to be handled later.
def resource_base
if through_resource
@options[:singleton] ? through_resource : through_resource.send(name.to_s.pluralize)
else
resource_class
end
end
# The object to load this resource through.
def through_resource
@options[:through] && [@options[:through]].flatten.map { |i| @controller.instance_variable_get("@#{i}") }.compact.first
end
def name
@name || name_from_controller
end
def name_from_controller
@params[:controller].sub("Controller", "").underscore.split('/').last.singularize
end
def instance_name
@options[:instance_name] || name
end
def collection_actions
[:index] + [@options[:collection]].flatten
end
def new_actions
[:new, :create] + [@options[:new]].flatten
end
end
end

43
lib/cancan/exceptions.rb Normal file
View File

@@ -0,0 +1,43 @@
module CanCan
# A general CanCan exception
class Error < StandardError; end
# Raised when removed code is called, an alternative solution is provided in message.
class ImplementationRemoved < Error; end
# This error is raised when a user isn't allowed to access a given controller action.
# This usually happens within a call to ControllerAdditions#authorize! but can be
# raised manually.
#
# raise CanCan::AccessDenied.new("Not authorized!", :read, Article)
#
# The passed message, action, and subject are optional and can later be retrieved when
# rescuing from the exception.
#
# exception.message # => "Not authorized!"
# exception.action # => :read
# exception.subject # => Article
#
# If the message is not specified (or is nil) it will default to "You are not authorized
# to access this page." This default can be overridden by setting default_message.
#
# exception.default_message = "Default error message"
# exception.message # => "Default error message"
#
# See ControllerAdditions#authorized! for more information on rescuing from this exception.
class AccessDenied < Error
attr_reader :action, :subject
attr_writer :default_message
def initialize(message = nil, action = nil, subject = nil)
@message = message
@action = action
@subject = subject
@default_message = "You are not authorized to access this page."
end
def to_s
@message || @default_message
end
end
end

14
lib/cancan/matchers.rb Normal file
View File

@@ -0,0 +1,14 @@
RSpec = Spec unless defined? RSpec # for RSpec 1 compatability
RSpec::Matchers.define :be_able_to do |*args|
match do |ability|
ability.can?(*args)
end
failure_message_for_should do |ability|
"expected to be able to #{args.map(&:inspect).join(" ")}"
end
failure_message_for_should_not do |ability|
"expected not to be able to #{args.map(&:inspect).join(" ")}"
end
end

97
lib/cancan/query.rb Normal file
View File

@@ -0,0 +1,97 @@
module CanCan
# Generates the sql conditions and association joins for use in ActiveRecord queries.
# Normally you will not use this class directly, but instead through ActiveRecordAdditions#accessible_by.
class Query
def initialize(sanitizer, can_definitions)
@sanitizer = sanitizer
@can_definitions = can_definitions
end
# Returns conditions intended to be used inside a database query. Normally you will not call this
# method directly, but instead go through ActiveRecordAdditions#accessible_by.
#
# If there is only one "can" definition, a hash of conditions will be returned matching the one defined.
#
# can :manage, User, :id => 1
# query(:manage, User).conditions # => { :id => 1 }
#
# If there are multiple "can" definitions, a SQL string will be returned to handle complex cases.
#
# can :manage, User, :id => 1
# can :manage, User, :manager_id => 1
# cannot :manage, User, :self_managed => true
# query(:manage, User).conditions # => "not (self_managed = 't') AND ((manager_id = 1) OR (id = 1))"
#
def conditions
if @can_definitions.size == 1 && @can_definitions.first.base_behavior
# Return the conditions directly if there's just one definition
@can_definitions.first.tableized_conditions
else
@can_definitions.reverse.inject(false_sql) do |sql, can_definition|
merge_conditions(sql, can_definition.tableized_conditions, can_definition.base_behavior)
end
end
end
# Returns the associations used in conditions for the :joins option of a search.
# See ActiveRecordAdditions#accessible_by for use in Active Record.
def joins
joins_hash = {}
@can_definitions.each do |can_definition|
merge_joins(joins_hash, can_definition.associations_hash)
end
clean_joins(joins_hash) unless joins_hash.empty?
end
private
def merge_conditions(sql, conditions_hash, behavior)
if conditions_hash.blank?
behavior ? true_sql : false_sql
else
conditions = sanitize_sql(conditions_hash)
case sql
when true_sql
behavior ? true_sql : "not (#{conditions})"
when false_sql
behavior ? conditions : false_sql
else
behavior ? "(#{conditions}) OR (#{sql})" : "not (#{conditions}) AND (#{sql})"
end
end
end
def false_sql
sanitize_sql(['?=?', true, false])
end
def true_sql
sanitize_sql(['?=?', true, true])
end
def sanitize_sql(conditions)
@sanitizer.send(:sanitize_sql, conditions)
end
# Takes two hashes and does a deep merge.
def merge_joins(base, add)
add.each do |name, nested|
if base[name].is_a?(Hash) && !nested.empty?
merge_joins(base[name], nested)
else
base[name] = nested
end
end
end
# Removes empty hashes and moves everything into arrays.
def clean_joins(joins_hash)
joins = []
joins_hash.each do |name, nested|
joins << (nested.empty? ? name : {name => clean_joins(nested)})
end
joins
end
end
end

View File

@@ -1,57 +0,0 @@
module CanCan
class ResourceAuthorization # :nodoc:
attr_reader :params
def initialize(controller, params, options = {})
@controller = controller
@params = params
@options = options
end
def load_and_authorize_resource
load_resource
authorize_resource
end
def load_resource
unless collection_actions.include? params[:action].to_sym
if new_actions.include? params[:action].to_sym
resource.build(params[model_name.to_sym])
elsif params[:id]
resource.find(params[:id])
end
end
end
def authorize_resource
@controller.unauthorized! if @controller.cannot?(params[:action].to_sym, resource.model_instance || resource.model_class)
end
private
def resource
@resource ||= ControllerResource.new(@controller, model_name, parent_resource)
end
def parent_resource
parent = nil
[@options[:nested]].flatten.compact.each do |name|
parent = ControllerResource.new(@controller, name, parent)
parent.find(@params["#{name}_id".to_sym])
end
parent
end
def model_name
params[:controller].split('/').last.singularize
end
def collection_actions
[:index] + [@options[:collection]].flatten
end
def new_actions
[:new, :create] + [@options[:new]].flatten
end
end
end

View File

@@ -1,10 +1,9 @@
require File.dirname(__FILE__) + '/../spec_helper'
require "spec_helper"
describe CanCan::Ability do
before(:each) do
@ability_class = Class.new
@ability_class.send(:include, CanCan::Ability)
@ability = @ability_class.new
@ability = Object.new
@ability.extend(CanCan::Ability)
end
it "should be able to :read anything" do
@@ -17,52 +16,81 @@ describe CanCan::Ability do
@ability.can?(:foodfight, String).should be_false
end
it "should return what block returns on a can call" do
it "should pass true to `can?` when non false/nil is returned in block" do
@ability.can :read, :all
@ability.can :read, Symbol do |sym|
sym
"foo" # TODO test that sym is nil when no instance is passed
end
@ability.can?(:read, Symbol).should be_nil
@ability.can?(:read, :some_symbol).should == :some_symbol
@ability.can?(:read, :some_symbol).should == true
end
it "should pass to previous can definition, if block returns false or nil" do
@ability.can :read, Symbol
@ability.can :read, Integer do |i|
i < 5
end
@ability.can :read, Integer do |i|
i > 10
end
@ability.can?(:read, Symbol).should be_true
@ability.can?(:read, 11).should be_true
@ability.can?(:read, 1).should be_true
@ability.can?(:read, 6).should be_false
end
it "should pass class with object if :all objects are accepted" do
@ability.can :preview, :all do |object_class, object|
[object_class, object]
object_class.should == Fixnum
object.should == 123
@block_called = true
end
@ability.can?(:preview, 123).should == [Fixnum, 123]
@ability.can?(:preview, 123)
@block_called.should be_true
end
it "should pass class with no object if :all objects are accepted and class is passed directly" do
@ability.can :preview, :all do |object_class, object|
[object_class, object]
object_class.should == Hash
object.should be_nil
@block_called = true
end
@ability.can?(:preview, Hash).should == [Hash, nil]
@ability.can?(:preview, Hash)
@block_called.should be_true
end
it "should pass action and object for global manage actions" do
@ability.can :manage, Array do |action, object|
[action, object]
action.should == :stuff
object.should == [1, 2]
@block_called = true
end
@ability.can?(:stuff, [1, 2]).should == [:stuff, [1, 2]]
@ability.can?(:stuff, Array).should == [:stuff, nil]
@ability.can?(:stuff, [1, 2]).should
@block_called.should be_true
end
it "should alias update or destroy actions to modify action" do
@ability.alias_action :update, :destroy, :to => :modify
@ability.can :modify, :all do |object_class, object|
:modify_called
end
@ability.can?(:update, 123).should == :modify_called
@ability.can?(:destroy, 123).should == :modify_called
@ability.can :modify, :all
@ability.can?(:update, 123).should be_true
@ability.can?(:destroy, 123).should be_true
end
it "should allow deeply nested aliased actions" do
@ability.alias_action :increment, :to => :sort
@ability.alias_action :sort, :to => :modify
@ability.can :modify, :all
@ability.can?(:increment, 123).should be_true
end
it "should return block result for action, object_class, and object for any action" do
@ability.can :manage, :all do |action, object_class, object|
[action, object_class, object]
action.should == :foo
object_class.should == Fixnum
object.should == 123
@block_called = true
end
@ability.can?(:foo, 123).should == [:foo, Fixnum, 123]
@ability.can?(:bar, Fixnum).should == [:bar, Fixnum, nil]
@ability.can?(:foo, 123)
@block_called.should be_true
end
it "should automatically alias index and show into read calls" do
@@ -72,10 +100,10 @@ describe CanCan::Ability do
end
it "should automatically alias new and edit into create and update respectively" do
@ability.can(:create, :all) { :create_called }
@ability.can(:update, :all) { :update_called }
@ability.can?(:new, 123).should == :create_called
@ability.can?(:edit, 123).should == :update_called
@ability.can :create, :all
@ability.can :update, :all
@ability.can?(:new, 123).should be_true
@ability.can?(:edit, 123).should be_true
end
it "should not respond to prepare (now using initialize)" do
@@ -107,6 +135,13 @@ describe CanCan::Ability do
@ability.can?(:read, :nonstats).should be_false
end
it "should check ancestors of class" do
@ability.can :read, Numeric
@ability.can?(:read, Integer).should be_true
@ability.can?(:read, 1.23).should be_true
@ability.can?(:read, "foo").should be_false
end
it "should support 'cannot' method to define what user cannot do" do
@ability.can :read, :all
@ability.cannot :read, Integer
@@ -123,4 +158,105 @@ describe CanCan::Ability do
@ability.can?(:read, 3).should be_true
@ability.can?(:read, 123).should be_false
end
it "should pass to previous can definition, if block returns false or nil" do
#same as previous
@ability.can :read, :all
@ability.cannot :read, Integer do |int|
int > 10 ? nil : ( int > 5 )
end
@ability.can?(:read, "foo").should be_true
@ability.can?(:read, 3).should be_true
@ability.can?(:read, 8).should be_false
@ability.can?(:read, 123).should be_true
end
it "should always return `false` for single cannot definition" do
@ability.cannot :read, Integer do |int|
int > 10 ? nil : ( int > 5 )
end
@ability.can?(:read, "foo").should be_false
@ability.can?(:read, 3).should be_false
@ability.can?(:read, 8).should be_false
@ability.can?(:read, 123).should be_false
end
it "should pass to previous cannot definition, if block returns false or nil" do
@ability.cannot :read, :all
@ability.can :read, Integer do |int|
int > 10 ? nil : ( int > 5 )
end
@ability.can?(:read, "foo").should be_false
@ability.can?(:read, 3).should be_false
@ability.can?(:read, 10).should be_true
@ability.can?(:read, 123).should be_false
end
it "should append aliased actions" do
@ability.alias_action :update, :to => :modify
@ability.alias_action :destroy, :to => :modify
@ability.aliased_actions[:modify].should == [:update, :destroy]
end
it "should clear aliased actions" do
@ability.alias_action :update, :to => :modify
@ability.clear_aliased_actions
@ability.aliased_actions[:modify].should be_nil
end
it "should pass additional arguments to block from can?" do
@ability.can :read, Integer do |int, x|
int > x
end
@ability.can?(:read, 2, 1).should be_true
@ability.can?(:read, 2, 3).should be_false
end
it "should use conditions as third parameter and determine abilities from it" do
@ability.can :read, Array, :first => 1, :last => 3
@ability.can?(:read, [1, 2, 3]).should be_true
@ability.can?(:read, [1, 2, 3, 4]).should be_false
@ability.can?(:read, Array).should be_true
end
it "should allow an array of options in conditions hash" do
@ability.can :read, Array, :first => [1, 3, 5]
@ability.can?(:read, [1, 2, 3]).should be_true
@ability.can?(:read, [2, 3]).should be_false
@ability.can?(:read, [3, 4]).should be_true
end
it "should allow a range of options in conditions hash" do
@ability.can :read, Array, :first => 1..3
@ability.can?(:read, [1, 2, 3]).should be_true
@ability.can?(:read, [3, 4]).should be_true
@ability.can?(:read, [4, 5]).should be_false
end
it "should allow nested hashes in conditions hash" do
@ability.can :read, Array, :first => { :length => 5 }
@ability.can?(:read, ["foo", "bar"]).should be_false
@ability.can?(:read, ["test1", "foo"]).should be_true
end
it "should allow nested hash of arrays and match any element" do
@ability.can :read, Array, :first => { :to_i => 3 }
@ability.can?(:read, [[1, 2, 3]]).should be_true
@ability.can?(:read, [[4, 5, 6]]).should be_false
end
it "should not stop at cannot definition when comparing class" do
@ability.can :read, Array
@ability.cannot :read, Array, :first => 1
@ability.can?(:read, [2, 3, 5]).should be_true
@ability.can?(:read, [1, 3, 5]).should be_false
@ability.can?(:read, Array).should be_true
end
it "should has eated cheezburger" do
lambda {
@ability.can? :has, :cheezburger
}.should raise_error(CanCan::Error, "Nom nom nom. I eated it.")
end
end

View File

@@ -0,0 +1,51 @@
require "spec_helper"
describe CanCan::ActiveRecordAdditions do
before(:each) do
@model_class = Class.new(Person)
stub(@model_class).scoped { :scoped_stub }
@model_class.send(:include, CanCan::ActiveRecordAdditions)
@ability = Object.new
@ability.extend(CanCan::Ability)
end
it "should call where('true=false') when no ability is defined so no records are found" do
stub(@model_class).where('true=false').stub!.joins(nil) { :no_match }
@model_class.accessible_by(@ability, :read).should == :no_match
end
it "should call where with matching ability conditions" do
@ability.can :read, @model_class, :foo => {:bar => 1}
stub(@model_class).where(:foos => { :bar => 1 }).stub!.joins([:foo]) { :found_records }
@model_class.accessible_by(@ability, :read).should == :found_records
end
it "should default to :read ability and use scoped when where isn't available" do
@ability.can :read, @model_class, :foo => {:bar => 1}
stub(@model_class).scoped(:conditions => {:foos => {:bar => 1}}, :joins => [:foo]) { :found_records }
@model_class.accessible_by(@ability).should == :found_records
end
it "should merge association joins and sanitize conditions" do
@ability.can :read, @model_class, :foo => {:bar => 1}
@ability.can :read, @model_class, :too => {:car => 1, :far => {:bar => 1}}
condition_variants = [
'(toos.fars.bar=1 AND toos.car=1) OR (foos.bar=1)', # faked sql sanitizer is stupid ;-)
'(toos.car=1 AND toos.fars.bar=1) OR (foos.bar=1)'
]
joins_variants = [
[:foo, {:too => [:far]}],
[{:too => [:far]}, :foo]
]
condition_variants.each do |condition|
joins_variants.each do |joins|
stub(@model_class).scoped( :conditions => condition, :joins => joins ) { :found_records }
end
end
# @ability.conditions(:read, @model_class).should == '(too.car=1 AND too.far.bar=1) OR (foo.bar=1)'
# @ability.associations_hash(:read, @model_class).should == [{:too => [:far]}, :foo]
@model_class.accessible_by(@ability).should == :found_records
end
end

View File

@@ -0,0 +1,56 @@
require "spec_helper"
describe CanCan::CanDefinition do
before(:each) do
@conditions = {}
@can = CanCan::CanDefinition.new(true, :read, Integer, @conditions, nil)
end
it "should return no association joins if none exist" do
@can.associations_hash.should == {}
end
it "should return no association for joins if just attributes" do
@conditions[:foo] = :bar
@can.associations_hash.should == {}
end
it "should return single association for joins" do
@conditions[:foo] = {:bar => 1}
@can.associations_hash.should == {:foo => {}}
end
it "should return multiple associations for joins" do
@conditions[:foo] = {:bar => 1}
@conditions[:test] = {1 => 2}
@can.associations_hash.should == {:foo => {}, :test => {}}
end
it "should return nested associations for joins" do
@conditions[:foo] = {:bar => {1 => 2}}
@can.associations_hash.should == {:foo => {:bar => {}}}
end
it "should tableize correctly for absurdly complex permissions" do
@conditions[:unit] = {:property=>{:landlord=>{:weasle_id=>560}}}
@conditions[:test] = 1
@can.tableized_conditions.should == {:units => {:properties => {:landlords=>{:weasle_id=>560}}}, :test => 1}
end
it "should tableize correctly for complex permissions" do
@conditions[:unit] = {:property=>{:landlord_id=>560}}
@conditions[:test] = 1
@can.tableized_conditions.should == {:units => {:properties => {:landlord_id=>560}}, :test => 1}
end
it "should return table names in conditions for association joins" do
@conditions[:foo] = {:bar => 1}
@conditions[:test] = 1
@can.tableized_conditions.should == {:foos => {:bar => 1}, :test => 1}
end
it "should return no association joins if conditions is nil" do
can = CanCan::CanDefinition.new(true, :read, Integer, nil, nil)
can.associations_hash.should == {}
end
end

View File

@@ -1,46 +1,77 @@
require File.dirname(__FILE__) + '/../spec_helper'
require "spec_helper"
describe CanCan::ControllerAdditions do
before(:each) do
@controller_class = Class.new
@controller = @controller_class.new
stub(@controller).params { {} }
stub(@controller).current_user { :current_user }
mock(@controller_class).helper_method(:can?, :cannot?)
@controller_class.send(:include, CanCan::ControllerAdditions)
end
it "should read from the cache with request uri as key and render that text" do
lambda {
@controller.unauthorized!
}.should raise_error(CanCan::AccessDenied)
it "should raise ImplementationRemoved when attempting to call 'unauthorized!' on a controller" do
lambda { @controller.unauthorized! }.should raise_error(CanCan::ImplementationRemoved)
end
it "should raise access denied exception if ability us unauthorized to perform a certain action" do
begin
@controller.authorize! :read, :foo, 1, 2, 3, :message => "Access denied!"
rescue CanCan::AccessDenied => e
e.message.should == "Access denied!"
e.action.should == :read
e.subject.should == :foo
else
fail "Expected CanCan::AccessDenied exception to be raised"
end
end
it "should not raise access denied exception if ability is authorized to perform an action" do
@controller.current_ability.can :read, :foo
lambda { @controller.authorize!(:read, :foo) }.should_not raise_error
end
it "should raise access denied exception with default message if not specified" do
begin
@controller.authorize! :read, :foo
rescue CanCan::AccessDenied => e
e.default_message = "Access denied!"
e.message.should == "Access denied!"
else
fail "Expected CanCan::AccessDenied exception to be raised"
end
end
it "should have a current_ability method which generates an ability for the current user" do
stub(@controller).current_user { :current_user }
@controller.current_ability.should be_kind_of(Ability)
end
it "should provide a can? and cannot? methods which go through the current ability" do
stub(@controller).current_user { :current_user }
@controller.current_ability.should be_kind_of(Ability)
@controller.can?(:foo, :bar).should be_false
@controller.cannot?(:foo, :bar).should be_true
end
it "load_and_authorize_resource should setup a before filter which passes call to ResourceAuthorization" do
stub(CanCan::ResourceAuthorization).new(@controller, @controller.params, :foo => :bar).mock!.load_and_authorize_resource
it "load_and_authorize_resource should setup a before filter which passes call to ControllerResource" do
stub(CanCan::ControllerResource).new(@controller, nil, :foo => :bar).mock!.load_and_authorize_resource
mock(@controller_class).before_filter({}) { |options, block| block.call(@controller) }
@controller_class.load_and_authorize_resource :foo => :bar
end
it "authorize_resource should setup a before filter which passes call to ResourceAuthorization" do
stub(CanCan::ResourceAuthorization).new(@controller, @controller.params, :foo => :bar).mock!.authorize_resource
it "load_and_authorize_resource should properly pass first argument as the resource name" do
stub(CanCan::ControllerResource).new(@controller, :project, :foo => :bar).mock!.load_and_authorize_resource
mock(@controller_class).before_filter({}) { |options, block| block.call(@controller) }
@controller_class.load_and_authorize_resource :project, :foo => :bar
end
it "authorize_resource should setup a before filter which passes call to ControllerResource" do
stub(CanCan::ControllerResource).new(@controller, nil, :foo => :bar).mock!.authorize_resource
mock(@controller_class).before_filter(:except => :show) { |options, block| block.call(@controller) }
@controller_class.authorize_resource :foo => :bar, :except => :show
end
it "load_resource should setup a before filter which passes call to ResourceAuthorization" do
stub(CanCan::ResourceAuthorization).new(@controller, @controller.params, :foo => :bar).mock!.load_resource
it "load_resource should setup a before filter which passes call to ControllerResource" do
stub(CanCan::ControllerResource).new(@controller, nil, :foo => :bar).mock!.load_resource
mock(@controller_class).before_filter(:only => [:show, :index]) { |options, block| block.call(@controller) }
@controller_class.load_resource :foo => :bar, :only => [:show, :index]
end

View File

@@ -1,43 +1,251 @@
require File.dirname(__FILE__) + '/../spec_helper'
require "spec_helper"
describe CanCan::ControllerResource do
before(:each) do
@controller = Object.new
@params = HashWithIndifferentAccess.new(:controller => "abilities")
@controller = Object.new # simple stub for now
stub(@controller).params { @params }
end
it "should determine model class by constantizing give name" do
CanCan::ControllerResource.new(@controller, :ability).model_class.should == Ability
it "should load the resource into an instance variable if params[:id] is specified" do
@params.merge!(:action => "show", :id => 123)
stub(Ability).find(123) { :some_resource }
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should fetch model through model class and assign it to the instance" do
stub(Ability).find(123) { :some_ability }
CanCan::ControllerResource.new(@controller, :ability).find(123)
@controller.instance_variable_get(:@ability).should == :some_ability
end
it "should fetch model through parent and assign it to the instance" do
parent = Object.new
stub(parent).model_instance.stub!.abilities.stub!.find(123) { :some_ability }
CanCan::ControllerResource.new(@controller, :ability, parent).find(123)
@controller.instance_variable_get(:@ability).should == :some_ability
end
it "should build model through model class and assign it to the instance" do
stub(Ability).new(123) { :some_ability }
CanCan::ControllerResource.new(@controller, :ability).build(123)
@controller.instance_variable_get(:@ability).should == :some_ability
end
it "should build model through parent and assign it to the instance" do
parent = Object.new
stub(parent).model_instance.stub!.abilities.stub!.build(123) { :some_ability }
CanCan::ControllerResource.new(@controller, :ability, parent).build(123)
@controller.instance_variable_get(:@ability).should == :some_ability
end
it "should not load resource if instance variable is already provided" do
it "should not load resource into an instance variable if already set" do
@params.merge!(:action => "show", :id => 123)
@controller.instance_variable_set(:@ability, :some_ability)
CanCan::ControllerResource.new(@controller, :ability).find(123)
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_ability
end
it "should properly load resource for namespaced controller" do
@params.merge!(:controller => "admin/abilities", :action => "show", :id => 123)
stub(Ability).find(123) { :some_resource }
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should properly load resource for namespaced controller when using '::' for namespace" do
@params.merge!(:controller => "Admin::AbilitiesController", :action => "show", :id => 123)
stub(Ability).find(123) { :some_resource }
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should build a new resource with hash if params[:id] is not specified" do
@params.merge!(:action => "create", :ability => {:foo => "bar"})
stub(Ability).new("foo" => "bar") { :some_resource }
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should build a new resource with no arguments if attribute hash isn't specified" do
@params[:action] = "new"
mock(Ability).new { :some_resource }
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should not build a resource when on index action" do
@params[:action] = "index"
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@ability).should be_nil
end
it "should perform authorization using controller action and loaded model" do
@params[:action] = "show"
@controller.instance_variable_set(:@ability, :some_resource)
stub(@controller).authorize!(:show, :some_resource) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller)
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
end
it "should perform authorization using controller action and non loaded model" do
@params[:action] = "show"
stub(@controller).authorize!(:show, Ability) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller)
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
end
it "should call load_resource and authorize_resource for load_and_authorize_resource" do
@params[:action] = "show"
resource = CanCan::ControllerResource.new(@controller)
mock(resource).load_resource
mock(resource).authorize_resource
resource.load_and_authorize_resource
end
it "should not build a resource when on custom collection action" do
@params[:action] = "sort"
resource = CanCan::ControllerResource.new(@controller, :collection => [:sort, :list])
resource.load_resource
@controller.instance_variable_get(:@ability).should be_nil
end
it "should build a resource when on custom new action even when params[:id] exists" do
@params.merge!(:action => "build", :id => 123)
stub(Ability).new { :some_resource }
resource = CanCan::ControllerResource.new(@controller, :new => :build)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should not try to load resource for other action if params[:id] is undefined" do
@params[:action] = "list"
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@ability).should be_nil
end
it "should be a parent resource when name is provided which doesn't match controller" do
resource = CanCan::ControllerResource.new(@controller, :person)
resource.should be_parent
end
it "should not be a parent resource when name is provided which matches controller" do
resource = CanCan::ControllerResource.new(@controller, :ability)
resource.should_not be_parent
end
it "should be parent if specified in options" do
resource = CanCan::ControllerResource.new(@controller, :ability, {:parent => true})
resource.should be_parent
end
it "should not be parent if specified in options" do
resource = CanCan::ControllerResource.new(@controller, :person, {:parent => false})
resource.should_not be_parent
end
it "should load parent resource through proper id parameter when supplying a resource with a different name" do
@params.merge!(:action => "index", :person_id => 123)
stub(Person).find(123) { :some_person }
resource = CanCan::ControllerResource.new(@controller, :person)
resource.load_resource
@controller.instance_variable_get(:@person).should == :some_person
end
it "should load parent resource for collection action" do
@params.merge!(:action => "index", :person_id => 456)
stub(Person).find(456) { :some_person }
resource = CanCan::ControllerResource.new(@controller, :person)
resource.load_resource
@controller.instance_variable_get(:@person).should == :some_person
end
it "should load resource through the association of another parent resource" do
@params.merge!(:action => "show", :id => 123)
person = Object.new
@controller.instance_variable_set(:@person, person)
stub(person).abilities.stub!.find(123) { :some_ability }
resource = CanCan::ControllerResource.new(@controller, :through => :person)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_ability
end
it "should not load through parent resource if instance isn't loaded" do
@params.merge!(:action => "show", :id => 123)
stub(Ability).find(123) { :some_ability }
resource = CanCan::ControllerResource.new(@controller, :through => :person)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_ability
end
it "should load through first matching if multiple are given" do
@params.merge!(:action => "show", :id => 123)
person = Object.new
@controller.instance_variable_set(:@person, person)
stub(person).abilities.stub!.find(123) { :some_ability }
resource = CanCan::ControllerResource.new(@controller, :through => [:thing, :person])
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_ability
end
it "should find record through has_one association with :singleton option" do
@params.merge!(:action => "show")
person = Object.new
@controller.instance_variable_set(:@person, person)
stub(person).ability { :some_ability }
resource = CanCan::ControllerResource.new(@controller, :through => :person, :singleton => true)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_ability
end
it "should build record through has_one association with :singleton option" do
@params.merge!(:action => "create", :ability => :ability_attributes)
person = Object.new
@controller.instance_variable_set(:@person, person)
stub(person).build_ability(:ability_attributes) { :new_ability }
resource = CanCan::ControllerResource.new(@controller, :through => :person, :singleton => true)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :new_ability
end
it "should only authorize :read action on parent resource" do
@params.merge!(:action => "new", :person_id => 123)
stub(Person).find(123) { :some_person }
stub(@controller).authorize!(:read, :some_person) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller, :person)
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
end
it "should load the model using a custom class" do
@params.merge!(:action => "show", :id => 123)
stub(Person).find(123) { :some_resource }
resource = CanCan::ControllerResource.new(@controller, :class => Person)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should authorize based on resource name if class is false" do
@params.merge!(:action => "show", :id => 123)
stub(@controller).authorize!(:show, :ability) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller, :class => false)
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
end
it "should load and authorize using custom instance name" do
@params.merge!(:action => "show", :id => 123)
stub(Ability).find(123) { :some_ability }
stub(@controller).authorize!(:show, :some_ability) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller, :instance_name => :custom_ability)
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
@controller.instance_variable_get(:@custom_ability).should == :some_ability
end
it "should load resource using custom find_by attribute" do
@params.merge!(:action => "show", :id => 123)
stub(Ability).find_by_name!(123) { :some_resource }
resource = CanCan::ControllerResource.new(@controller, :find_by => :name)
resource.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should raise ImplementationRemoved when adding :name option" do
lambda {
CanCan::ControllerResource.new(@controller, :name => :foo)
}.should raise_error(CanCan::ImplementationRemoved)
end
it "should raise ImplementationRemoved exception when specifying :resource option since it is no longer used" do
lambda {
CanCan::ControllerResource.new(@controller, :resource => Person)
}.should raise_error(CanCan::ImplementationRemoved)
end
it "should raise ImplementationRemoved exception when passing :nested option" do
lambda {
CanCan::ControllerResource.new(@controller, :nested => :person)
}.should raise_error(CanCan::ImplementationRemoved)
end
end

View File

@@ -0,0 +1,35 @@
require "spec_helper"
describe CanCan::AccessDenied do
describe "with action and subject" do
before(:each) do
@exception = CanCan::AccessDenied.new(nil, :some_action, :some_subject)
end
it "should have action and subject accessors" do
@exception.action.should == :some_action
@exception.subject.should == :some_subject
end
it "should have a changable default message" do
@exception.message.should == "You are not authorized to access this page."
@exception.default_message = "Unauthorized!"
@exception.message.should == "Unauthorized!"
end
end
describe "with only a message" do
before(:each) do
@exception = CanCan::AccessDenied.new("Access denied!")
end
it "should have nil action and subject" do
@exception.action.should be_nil
@exception.subject.should be_nil
end
it "should have passed message" do
@exception.message.should == "Access denied!"
end
end
end

View File

@@ -0,0 +1,33 @@
require "spec_helper"
describe "be_able_to" do
it "delegates to can?" do
object = Object.new
mock(object).can?(:read, 123) { true }
object.should be_able_to(:read, 123)
end
it "reports a nice failure message for should" do
object = Object.new
mock(object).can?(:read, 123) { false }
expect do
object.should be_able_to(:read, 123)
end.should raise_error('expected to be able to :read 123')
end
it "reports a nice failure message for should not" do
object = Object.new
mock(object).can?(:read, 123) { true }
expect do
object.should_not be_able_to(:read, 123)
end.should raise_error('expected not to be able to :read 123')
end
it "delegates additional arguments to can? and reports in failure message" do
object = Object.new
mock(object).can?(:read, 123, 456) { false }
expect do
object.should be_able_to(:read, 123, 456)
end.should raise_error('expected to be able to :read 123 456')
end
end

107
spec/cancan/query_spec.rb Normal file
View File

@@ -0,0 +1,107 @@
require "spec_helper"
describe CanCan::Query do
before(:each) do
@ability = Object.new
@ability.extend(CanCan::Ability)
end
it "should have false conditions if no abilities match" do
@ability.query(:destroy, Person).conditions.should == "true=false"
end
it "should return hash for single `can` definition" do
@ability.can :read, Person, :blocked => false, :user_id => 1
@ability.query(:read, Person).conditions.should == { :blocked => false, :user_id => 1 }
end
it "should merge multiple can definitions into single SQL string joining with OR" do
@ability.can :read, Person, :blocked => false
@ability.can :read, Person, :admin => true
@ability.query(:read, Person).conditions.should == "(admin=true) OR (blocked=false)"
end
it "should merge multiple can definitions into single SQL string joining with OR and AND" do
@ability.can :read, Person, :blocked => false, :active => true
@ability.can :read, Person, :admin => true
@ability.query(:read, Person).conditions.should orderlessly_match("(blocked=false AND active=true) OR (admin=true)")
end
it "should merge multiple can definitions into single SQL string joining with OR and AND" do
@ability.can :read, Person, :blocked => false, :active => true
@ability.can :read, Person, :admin => true
@ability.query(:read, Person).conditions.should orderlessly_match("(blocked=false AND active=true) OR (admin=true)")
end
it "should return false conditions for cannot clause" do
@ability.cannot :read, Person
@ability.query(:read, Person).conditions.should == "true=false"
end
it "should return SQL for single `can` definition in front of default `cannot` condition" do
@ability.cannot :read, Person
@ability.can :read, Person, :blocked => false, :user_id => 1
@ability.query(:read, Person).conditions.should orderlessly_match("blocked=false AND user_id=1")
end
it "should return true condition for single `can` definition in front of default `can` condition" do
@ability.can :read, Person
@ability.can :read, Person, :blocked => false, :user_id => 1
@ability.query(:read, Person).conditions.should == 'true=true'
end
it "should return false condition for single `cannot` definition" do
@ability.cannot :read, Person, :blocked => true, :user_id => 1
@ability.query(:read, Person).conditions.should == 'true=false'
end
it "should return `false condition` for single `cannot` definition in front of default `cannot` condition" do
@ability.cannot :read, Person
@ability.cannot :read, Person, :blocked => true, :user_id => 1
@ability.query(:read, Person).conditions.should == 'true=false'
end
it "should return `not (sql)` for single `cannot` definition in front of default `can` condition" do
@ability.can :read, Person
@ability.cannot :read, Person, :blocked => true, :user_id => 1
@ability.query(:read, Person).conditions.should orderlessly_match("not (blocked=true AND user_id=1)")
end
it "should return appropriate sql conditions in complex case" do
@ability.can :read, Person
@ability.can :manage, Person, :id => 1
@ability.can :update, Person, :manager_id => 1
@ability.cannot :update, Person, :self_managed => true
@ability.query(:update, Person).conditions.should == 'not (self_managed=true) AND ((manager_id=1) OR (id=1))'
@ability.query(:manage, Person).conditions.should == {:id=>1}
@ability.query(:read, Person).conditions.should == 'true=true'
end
it "should have nil joins if no can definitions" do
@ability.query(:read, Person).joins.should be_nil
end
it "should have nil joins if no nested hashes specified in conditions" do
@ability.can :read, Person, :blocked => false
@ability.can :read, Person, :admin => true
@ability.query(:read, Person).joins.should be_nil
end
it "should merge separate joins into a single array" do
@ability.can :read, Person, :project => { :blocked => false }
@ability.can :read, Person, :company => { :admin => true }
@ability.query(:read, Person).joins.inspect.should orderlessly_match([:company, :project].inspect)
end
it "should merge same joins into a single array" do
@ability.can :read, Person, :project => { :blocked => false }
@ability.can :read, Person, :project => { :admin => true }
@ability.query(:read, Person).joins.should == [:project]
end
it "should merge complex, nested joins" do
@ability.can :read, Person, :project => { :bar => {:test => true} }, :company => { :bar => {:test => true} }
@ability.can :read, Person, :project => { :foo => {:bar => true}, :bar => {:zip => :zap} }
@ability.query(:read, Person).joins.inspect.should orderlessly_match([{:project => [:bar, :foo]}, {:company => [:bar]}].inspect)
end
end

View File

@@ -1,99 +0,0 @@
require File.dirname(__FILE__) + '/../spec_helper'
describe CanCan::ResourceAuthorization do
before(:each) do
@controller = Object.new # simple stub for now
stub(@controller).unauthorized! { raise CanCan::AccessDenied }
end
it "should load the resource into an instance variable if params[:id] is specified" do
stub(Ability).find(123) { :some_resource }
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "show", :id => 123)
authorization.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should properly load resource for namespaced controller" do
stub(Ability).find(123) { :some_resource }
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "admin/abilities", :action => "show", :id => 123)
authorization.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should build a new resource with hash if params[:id] is not specified" do
stub(Ability).new(:foo => "bar") { :some_resource }
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "create", :ability => {:foo => "bar"})
authorization.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should build a new resource even if attribute hash isn't specified" do
stub(Ability).new(nil) { :some_resource }
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "new")
authorization.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should not build a resource when on index action" do
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "index")
authorization.load_resource
@controller.instance_variable_get(:@ability).should be_nil
end
it "should perform authorization using controller action and loaded model" do
@controller.instance_variable_set(:@ability, :some_resource)
stub(@controller).cannot?(:show, :some_resource) { true }
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "show")
lambda {
authorization.authorize_resource
}.should raise_error(CanCan::AccessDenied)
end
it "should perform authorization using controller action and non loaded model" do
stub(@controller).cannot?(:show, Ability) { true }
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "show")
lambda {
authorization.authorize_resource
}.should raise_error(CanCan::AccessDenied)
end
it "should call load_resource and authorize_resource for load_and_authorize_resource" do
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "show")
mock(authorization).load_resource
mock(authorization).authorize_resource
authorization.load_and_authorize_resource
end
it "should not build a resource when on custom collection action" do
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "sort"}, {:collection => [:sort, :list]})
authorization.load_resource
@controller.instance_variable_get(:@ability).should be_nil
end
it "should build a resource when on custom new action even when params[:id] exists" do
stub(Ability).new(nil) { :some_resource }
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "build", :id => 123}, {:new => :build})
authorization.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should not try to load resource for other action if params[:id] is undefined" do
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "list")
authorization.load_resource
@controller.instance_variable_get(:@ability).should be_nil
end
it "should load nested resource and fetch other resource through the association" do
stub(Person).find(456).stub!.abilities.stub!.find(123) { :some_ability }
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "show", :id => 123, :person_id => 456}, {:nested => :person})
authorization.load_resource
@controller.instance_variable_get(:@ability).should == :some_ability
end
it "should load nested resource and build resource through a deep association" do
stub(Person).find(456).stub!.behaviors.stub!.find(789).stub!.abilities.stub!.build(nil) { :some_ability }
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "new", :person_id => 456, :behavior_id => 789}, {:nested => [:person, :behavior]})
authorization.load_resource
@controller.instance_variable_get(:@ability).should == :some_ability
end
end

13
spec/matchers.rb Normal file
View File

@@ -0,0 +1,13 @@
Spec::Matchers.define :orderlessly_match do |original_string|
match do |given_string|
original_string.split('').sort == given_string.split('').sort
end
failure_message_for_should do |given_string|
"expected \"#{given_string}\" to have the same characters as \"#{original_string}\""
end
failure_message_for_should_not do |given_string|
"expected \"#{given_string}\" not to have the same characters as \"#{original_string}\""
end
end

1
spec/spec.opts Normal file
View File

@@ -0,0 +1 @@
--color

View File

@@ -4,7 +4,9 @@ require 'active_support'
require 'active_record'
require 'action_controller'
require 'action_view'
require File.dirname(__FILE__) + '/../lib/cancan.rb'
require 'matchers'
require 'cancan'
require 'cancan/matchers'
Spec::Runner.configure do |config|
config.mock_with :rr
@@ -17,6 +19,29 @@ class Ability
end
end
# this class helps out in testing nesting
# this class helps out in testing SQL conditions
class Person
class << self
protected
def sanitize_sql(hash_cond)
case hash_cond
when Hash
sanitize_hash(hash_cond).join(' AND ')
when Array
hash_cond.shift.gsub('?'){"#{hash_cond.shift.inspect}"}
when String then hash_cond
end
end
def sanitize_hash(hash)
hash.map do |name, value|
if Hash === value
sanitize_hash(value).map{|cond| "#{name}.#{cond}"}
else
"#{name}=#{value}"
end
end.flatten
end
end
end