Compare commits
38 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b9cdce09a | ||
|
|
a13f78d6f9 | ||
|
|
41f67ad6d0 | ||
|
|
7d3b4cdbc2 | ||
|
|
f99d506050 | ||
|
|
ef22de689b | ||
|
|
67416532f4 | ||
|
|
f919ac53bb | ||
|
|
021f33c9a0 | ||
|
|
e9f01300b6 | ||
|
|
f7480d1f5a | ||
|
|
ffa677b2b0 | ||
|
|
a75aee751b | ||
|
|
51fa61bbae | ||
|
|
cd217eb9cf | ||
|
|
94e031bf96 | ||
|
|
63634b4f5d | ||
|
|
a5f98824a0 | ||
|
|
43947c893d | ||
|
|
e32c5d0dfb | ||
|
|
da5a5c031f | ||
|
|
e92a7d8bf4 | ||
|
|
c40490d672 | ||
|
|
d4405e6070 | ||
|
|
e60365505c | ||
|
|
5bd1a85410 | ||
|
|
0ae41f57b8 | ||
|
|
b145a98488 | ||
|
|
b9227eb971 | ||
|
|
072cb0f2de | ||
|
|
52649a8da1 | ||
|
|
15a01a579c | ||
|
|
766fe86a9f | ||
|
|
4322da9d0a | ||
|
|
0f49b5478f | ||
|
|
df276536ab | ||
|
|
1edf583110 | ||
|
|
9d58226563 |
@@ -1,3 +1,54 @@
|
|||||||
*0.1.0* (Nov 16th, 2009)
|
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
|
||||||
|
|
||||||
|
* Allowing :nested option to accept an array for deep nesting
|
||||||
|
|
||||||
|
* Adding :nested option to load resource method - see issue #10
|
||||||
|
|
||||||
|
* Pass :only and :except options to before filters for load/authorize resource methods.
|
||||||
|
|
||||||
|
* Adding :collection and :new options to load_resource method so we can specify behavior of additional actions if needed.
|
||||||
|
|
||||||
|
* BACKWARDS INCOMPATIBLE: turning load and authorize resource methods into class methods which set up the before filter so they can accept additional arguments.
|
||||||
|
|
||||||
|
|
||||||
|
0.2.1 (Nov 26, 2009)
|
||||||
|
|
||||||
|
* many internal refactorings - see issues #11 and #12
|
||||||
|
|
||||||
|
* adding "cannot" method to define which abilities cannot be done - see issue #7
|
||||||
|
|
||||||
|
* support custom objects (usually symbols) in can definition - see issue #8
|
||||||
|
|
||||||
|
|
||||||
|
0.2.0 (Nov 17, 2009)
|
||||||
|
|
||||||
|
* fix behavior of load_and_authorize_resource for namespaced controllers - see issue #3
|
||||||
|
|
||||||
|
* support arrays being passed to "can" to specify multiple actions or classes - see issue #2
|
||||||
|
|
||||||
|
* adding "cannot?" method to ability, controller, and view which is inverse of "can?" - see issue #1
|
||||||
|
|
||||||
|
* BACKWARDS INCOMPATIBLE: use Ability#initialize instead of 'prepare' to set up abilities - see issue #4
|
||||||
|
|
||||||
|
|
||||||
|
0.1.0 (Nov 16, 2009)
|
||||||
|
|
||||||
* initial release
|
* initial release
|
||||||
|
|||||||
142
README.rdoc
142
README.rdoc
@@ -1,33 +1,34 @@
|
|||||||
= CanCan
|
= CanCan
|
||||||
|
|
||||||
This is a simple authorization solution for Rails which is completely decoupled from how you set up the user's roles. All permissions are stored in a single location for convenience.
|
RDocs[http://rdoc.info/projects/ryanb/cancan] | Wiki[http://wiki.github.com/ryanb/cancan] | Screencast[http://railscasts.com/episodes/192-authorization-with-cancan] | Metrics[http://getcaliper.com/caliper/project?repo=git%3A%2F%2Fgithub.com%2Fryanb%2Fcancan.git] | Tests[http://runcoderun.com/ryanb/cancan]
|
||||||
|
|
||||||
This assumes you already have an authentication solution (such as Authlogic) which proves a current_user model.
|
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.
|
||||||
|
|
||||||
|
This assumes you already have authentication (such as Authlogic[http://github.com/binarylogic/authlogic]) which provides a current_user model.
|
||||||
|
|
||||||
== Installation
|
== Installation
|
||||||
|
|
||||||
You can set it up as a gem in your environment.rb file.
|
You can set it up as a gem in your environment.rb file.
|
||||||
|
|
||||||
config.gem "cancan", :source => "http://gemcutter.org"
|
config.gem "cancan"
|
||||||
|
|
||||||
And then install the gem.
|
And then install the gem.
|
||||||
|
|
||||||
gem install cancan
|
sudo rake gems:install
|
||||||
|
|
||||||
Alternatively you can install it as a Rails plugin.
|
Alternatively you can install it as a Rails plugin.
|
||||||
|
|
||||||
script/plugin install git://github.com/ryanb/cancan.git
|
script/plugin install git://github.com/ryanb/cancan.git
|
||||||
|
|
||||||
|
|
||||||
== Setup
|
== Getting Started
|
||||||
|
|
||||||
First define a class called Ability, place it in "models/ability.rb".
|
First, define a class called Ability in "models/ability.rb".
|
||||||
|
|
||||||
class Ability
|
class Ability
|
||||||
include CanCan::Ability
|
include CanCan::Ability
|
||||||
|
|
||||||
def prepare(user)
|
def initialize(user)
|
||||||
if user.admin?
|
if user.admin?
|
||||||
can :manage, :all
|
can :manage, :all
|
||||||
else
|
else
|
||||||
@@ -36,40 +37,36 @@ First define a class called Ability, place it in "models/ability.rb".
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
This class is where all permissions will go. See the "Defining Abilities" section below for more information.
|
This is where all permissions will go. See the "Defining Abilities" section below for more information.
|
||||||
|
|
||||||
In the view layer you can access the current permissions at any point using the "can?" method. See "Checking Abilities" section below.
|
You can access the current permissions at any point using the "can?" and "cannot?" methods in the view.
|
||||||
|
|
||||||
<% if can? :update, @article %>
|
<% if can? :update, @article %>
|
||||||
<%= link_to "Edit", edit_article_path(@article) %>
|
<%= link_to "Edit", edit_article_path(@article) %>
|
||||||
<% end %>
|
<% end %>
|
||||||
|
|
||||||
You can also use this method in the controller layer along with the "unauthorized!" method to restrict access.
|
You can also use these methods in a controller along with the "unauthorized!" method to restrict access.
|
||||||
|
|
||||||
def show
|
def show
|
||||||
@article = Article.find(params[:id])
|
@article = Article.find(params[:id])
|
||||||
unauthorized! unless can? :read, @article
|
unauthorized! if cannot? :read, @article
|
||||||
end
|
end
|
||||||
|
|
||||||
Setting this for every action can be tedious, therefore a before filter is also provided for automatically applying this setting to a RESTful style resource controller.
|
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.
|
||||||
|
|
||||||
class ArticlesController < ApplicationController
|
class ArticlesController < ApplicationController
|
||||||
before_filter :load_and_authorize_resource
|
load_and_authorize_resource
|
||||||
|
|
||||||
def show
|
def show
|
||||||
# @article is already loaded
|
# @article is already loaded
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
If the user authorization fails, a CanCan::AccessDenied exception will be raised. You can catch this and modify its behavior.
|
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
|
class ApplicationController < ActionController::Base
|
||||||
rescue_from CanCan::AccessDenied, :with => :access_denied
|
rescue_from CanCan::AccessDenied do |exception|
|
||||||
|
flash[:error] = exception.message
|
||||||
protected
|
|
||||||
|
|
||||||
def access_denied
|
|
||||||
flash[:error] = "Sorry, you are not allowed to access that page."
|
|
||||||
redirect_to root_url
|
redirect_to root_url
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -77,7 +74,7 @@ If the user authorization fails, a CanCan::AccessDenied exception will be raised
|
|||||||
|
|
||||||
== Defining Abilities
|
== Defining Abilities
|
||||||
|
|
||||||
As shown above, the Ability#prepare method is where all user permissions are defined. The user model is passed into this 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 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.
|
||||||
|
|
||||||
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 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.
|
||||||
|
|
||||||
@@ -89,7 +86,7 @@ You can pass an array for either of these parameters to match any one.
|
|||||||
|
|
||||||
In this case the user has the ability to update or destroy both articles and comments.
|
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. For example:
|
You can pass a block to provide logic based on the article's attributes.
|
||||||
|
|
||||||
can :update, Article do |article|
|
can :update, Article do |article|
|
||||||
article && article.user == user
|
article && article.user == user
|
||||||
@@ -110,17 +107,11 @@ You can also pass :manage as the action which will match any action. In this cas
|
|||||||
can :manage, Comment do |action, comment|
|
can :manage, Comment do |action, comment|
|
||||||
action != :destroy
|
action != :destroy
|
||||||
end
|
end
|
||||||
|
|
||||||
|
Finally, the "cannot" method works similar to "can" but defines which abilities cannot be done.
|
||||||
|
|
||||||
Finally, you can use the "alias_action" method to alias one or more actions into one.
|
can :read, :all
|
||||||
|
cannot :read, Product
|
||||||
alias_action :update, :destroy, :to => :modify
|
|
||||||
can :modify, Comment
|
|
||||||
|
|
||||||
The following aliases are added by default for conveniently mapping common controller actions.
|
|
||||||
|
|
||||||
alias_action :index, :show, :to => :read
|
|
||||||
alias_action :new, :to => :create
|
|
||||||
alias_action :edit, :to => :update
|
|
||||||
|
|
||||||
|
|
||||||
== Checking Abilities
|
== Checking Abilities
|
||||||
@@ -129,65 +120,84 @@ Use the "can?" method in the controller or view to check the user's permission f
|
|||||||
|
|
||||||
can? :destroy, @project
|
can? :destroy, @project
|
||||||
|
|
||||||
You can also pass the class instead of an instance (if you don't have one handy). For example:
|
You can also pass the class instead of an instance (if you don't have one handy).
|
||||||
|
|
||||||
<% if can? :create, Project %>
|
<% if can? :create, Project %>
|
||||||
<%= link_to "New Project", new_project_path %>
|
<%= link_to "New Project", new_project_path %>
|
||||||
<% end %>
|
<% end %>
|
||||||
|
|
||||||
|
The "cannot?" method is for convenience and performs the opposite check of "can?"
|
||||||
|
|
||||||
== Custom Actions
|
cannot? :destroy, @project
|
||||||
|
|
||||||
There is no limit to what actions you can use to determine abilities. For example, if only pro users are allowed to upload a picture for their product, you might add restrictions like this.
|
|
||||||
|
|
||||||
# ability.rb
|
== Aliasing Actions
|
||||||
can :upload_picture, Project if user.pro?
|
|
||||||
|
|
||||||
# projects/_form.html.erb
|
You can use the "alias_action" method to alias one or more actions into one.
|
||||||
<%= f.file_field :picture if can? :upload_picture, @project %>
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
alias_action :index, :show, :to => :read
|
||||||
|
alias_action :new, :to => :create
|
||||||
|
alias_action :edit, :to => :update
|
||||||
|
|
||||||
|
|
||||||
|
== Authorizing Controller Actions
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
# projects_controller.rb
|
private
|
||||||
def update
|
|
||||||
unauthorized! if params[:project][:upload_picture] && !can?(:upload_picture, @project)
|
def find_book_by_permalink
|
||||||
# ...
|
@book = Book.find_by_permalink!(params[:id)
|
||||||
|
end
|
||||||
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.
|
||||||
|
|
||||||
== Customizing Assumptions
|
|
||||||
|
== Assumptions & Configuring
|
||||||
|
|
||||||
CanCan makes two assumptions about your application.
|
CanCan makes two assumptions about your application.
|
||||||
|
|
||||||
* The permissions are defined in Ability#prepare.
|
* You have an Ability class which defines the permissions.
|
||||||
* The user is fetched with current_user method in the controller.
|
* You have a current_user method in the controller which returns the current user model.
|
||||||
|
|
||||||
You can override these by defining the "current_ability" method in your ApplicationController.
|
You can override these by overriding the "current_ability" method in your ApplicationController.
|
||||||
|
|
||||||
def current_ability
|
def current_ability
|
||||||
ability = UserAbility.new # instead of Ability
|
UserAbility.new(current_account) # instead of Ability.new(current_user)
|
||||||
ability.prepare(current_account) # instead of current_user
|
|
||||||
ability # be sure to return the ability
|
|
||||||
end
|
end
|
||||||
|
|
||||||
That's it!
|
That's it!
|
||||||
|
|
||||||
|
|
||||||
== Permissions in Database
|
== Testing Abilities
|
||||||
|
|
||||||
Perhaps a non-coder needs the ability to modify the user abilities, or you want to change them without having to re-deploy the application. In that case it may be best to store the permission logic in a separate model, let's call it Permission. It is easy to use the database records when defining 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.
|
||||||
|
|
||||||
For example, let's assume that each user has_many :permissions, and each permission has "action", "object_type" and "object_id" columns. The last of which is optional.
|
def test "user can only destroy projects which he owns"
|
||||||
|
user = User.new
|
||||||
class Ability
|
ability = Ability.new(user)
|
||||||
include CanCan::Ability
|
assert ability.can?(:destroy, Project.new(:user => user))
|
||||||
|
assert ability.cannot?(:destroy, Project.new)
|
||||||
def prepare(user)
|
|
||||||
can :manage, :all do |action, object_class, object|
|
|
||||||
user.permissions.find_all_by_action(action).any? do |permission|
|
|
||||||
permission.object_type.constantize == object_class &&
|
|
||||||
(object.nil? || permission.object_id.nil? || permission.object_id == object.id)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
The actual details will depend largely on your application requirements, but hopefully you can see how it's possible to define permissions in the database and use them with 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.
|
||||||
|
|||||||
2
Rakefile
2
Rakefile
@@ -9,3 +9,5 @@ Spec::Rake::SpecTask.new do |t|
|
|||||||
t.spec_files = spec_files
|
t.spec_files = spec_files
|
||||||
t.spec_opts = ["-c"]
|
t.spec_opts = ["-c"]
|
||||||
end
|
end
|
||||||
|
|
||||||
|
task :default => :spec
|
||||||
@@ -4,8 +4,8 @@ Gem::Specification.new do |s|
|
|||||||
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.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.homepage = "http://github.com/ryanb/cancan"
|
||||||
|
|
||||||
s.version = "0.1.0"
|
s.version = "1.0.2"
|
||||||
s.date = "2009-11-16"
|
s.date = "2009-12-30"
|
||||||
|
|
||||||
s.authors = ["Ryan Bates"]
|
s.authors = ["Ryan Bates"]
|
||||||
s.email = "ryan@railscasts.com"
|
s.email = "ryan@railscasts.com"
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
module CanCan
|
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
|
class AccessDenied < StandardError; end
|
||||||
end
|
end
|
||||||
|
|
||||||
require File.dirname(__FILE__) + '/cancan/ability'
|
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 File.dirname(__FILE__) + '/cancan/controller_additions'
|
||||||
|
|||||||
@@ -1,45 +1,177 @@
|
|||||||
module CanCan
|
module CanCan
|
||||||
|
|
||||||
|
# This module is designed to be included into an Ability class. This will
|
||||||
|
# provide the "can" methods for defining and checking abilities.
|
||||||
|
#
|
||||||
|
# class Ability
|
||||||
|
# include CanCan::Ability
|
||||||
|
#
|
||||||
|
# def initialize(user)
|
||||||
|
# if user.admin?
|
||||||
|
# can :manage, :all
|
||||||
|
# else
|
||||||
|
# can :read, :all
|
||||||
|
# end
|
||||||
|
# end
|
||||||
|
# end
|
||||||
|
#
|
||||||
module Ability
|
module Ability
|
||||||
attr_accessor :user
|
attr_accessor :user
|
||||||
|
|
||||||
def can?(original_action, target) # TODO this could use some refactoring
|
# Use to check the user's permission for a given action and object.
|
||||||
(@can_history || []).reverse.each do |can_action, can_target, can_block|
|
#
|
||||||
possible_actions_for(original_action).each do |action|
|
# can? :destroy, @project
|
||||||
if (can_action == :manage || can_action == action) && (can_target == :all || can_target == target || target.kind_of?(can_target))
|
#
|
||||||
if can_block.nil?
|
# You can also pass the class instead of an instance (if you don't have one handy).
|
||||||
return true
|
#
|
||||||
else
|
# can? :create, Project
|
||||||
block_args = []
|
#
|
||||||
block_args << action if can_action == :manage
|
# Not only can you use the can? method in the controller and view (see ControllerAdditions),
|
||||||
block_args << (target.class == Class ? target : target.class) if can_target == :all
|
# but you can also call it directly on an ability instance.
|
||||||
block_args << (target.class == Class ? nil : target)
|
#
|
||||||
return can_block.call(*block_args)
|
# ability.can? :destroy, @project
|
||||||
end
|
#
|
||||||
end
|
# This makes testing a user's abilities very easy.
|
||||||
|
#
|
||||||
|
# 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
|
||||||
|
#
|
||||||
|
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
|
end
|
||||||
end
|
end
|
||||||
false
|
false
|
||||||
end
|
end
|
||||||
|
|
||||||
def possible_actions_for(initial_action)
|
# Convenience method which works the same as "can?" but returns the opposite value.
|
||||||
actions = [initial_action]
|
#
|
||||||
(@aliased_actions || default_alias_actions).each do |target, aliases|
|
# cannot? :destroy, @project
|
||||||
actions += possible_actions_for(target) if aliases.include? initial_action
|
#
|
||||||
end
|
def cannot?(*args)
|
||||||
actions
|
!can?(*args)
|
||||||
end
|
|
||||||
|
|
||||||
def can(action, target, &block)
|
|
||||||
@can_history ||= []
|
|
||||||
@can_history << [action, target, block]
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def alias_action(*args)
|
# Defines which abilities are allowed using two arguments. The first one is the action
|
||||||
@aliased_actions ||= default_alias_actions
|
# you're setting the permission for, the second one is the class of object you're setting it on.
|
||||||
target = args.pop[:to]
|
#
|
||||||
@aliased_actions[target] = args
|
# can :update, Article
|
||||||
|
#
|
||||||
|
# You can pass an array for either of these parameters to match any one.
|
||||||
|
#
|
||||||
|
# can [:update, :destroy], [Article, Comment]
|
||||||
|
#
|
||||||
|
# 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.
|
||||||
|
#
|
||||||
|
# can :update, Article do |article|
|
||||||
|
# article && article.user == user
|
||||||
|
# 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
|
||||||
|
#
|
||||||
|
# You can pass custom objects into this "can" method, this is usually done through a symbol
|
||||||
|
# and is useful if a class isn't available to define permissions on.
|
||||||
|
#
|
||||||
|
# can :read, :stats
|
||||||
|
# can? :read, :stats # => true
|
||||||
|
#
|
||||||
|
def can(action, noun, &block)
|
||||||
|
@can_definitions ||= []
|
||||||
|
@can_definitions << [true, action, noun, block]
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Define an ability which cannot be done. Accepts the same arguments as "can".
|
||||||
|
#
|
||||||
|
# can :read, :all
|
||||||
|
# cannot :read, Comment
|
||||||
|
#
|
||||||
|
# A block can be passed just like "can", however if the logic is complex it is recommended
|
||||||
|
# to use the "can" method.
|
||||||
|
#
|
||||||
|
# cannot :read, Product do |product|
|
||||||
|
# product.invisible?
|
||||||
|
# end
|
||||||
|
#
|
||||||
|
def cannot(action, noun, &block)
|
||||||
|
@can_definitions ||= []
|
||||||
|
@can_definitions << [false, action, noun, block]
|
||||||
|
end
|
||||||
|
|
||||||
|
# Alias one or more actions into another one.
|
||||||
|
#
|
||||||
|
# alias_action :update, :destroy, :to => :modify
|
||||||
|
# can :modify, Comment
|
||||||
|
#
|
||||||
|
# Then :modify permission will apply to both :update and :destroy requests.
|
||||||
|
#
|
||||||
|
# can? :update, Comment # => true
|
||||||
|
# can? :destroy, Comment # => true
|
||||||
|
#
|
||||||
|
# This only works in one direction. Passing the aliased action into the "can?" call
|
||||||
|
# will not work because aliases are meant to generate more generic actions.
|
||||||
|
#
|
||||||
|
# alias_action :update, :destroy, :to => :modify
|
||||||
|
# can :update, Comment
|
||||||
|
# can? :modify, Comment # => false
|
||||||
|
#
|
||||||
|
# Unless that exact alias is used.
|
||||||
|
#
|
||||||
|
# can :modify, Comment
|
||||||
|
# can? :modify, Comment # => true
|
||||||
|
#
|
||||||
|
# The following aliases are added by default for conveniently mapping common controller actions.
|
||||||
|
#
|
||||||
|
# alias_action :index, :show, :to => :read
|
||||||
|
# alias_action :new, :to => :create
|
||||||
|
# alias_action :edit, :to => :update
|
||||||
|
#
|
||||||
|
# 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] ||= []
|
||||||
|
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
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
def default_alias_actions
|
def default_alias_actions
|
||||||
{
|
{
|
||||||
:read => [:index, :show],
|
:read => [:index, :show],
|
||||||
@@ -48,8 +180,34 @@ module CanCan
|
|||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
def prepare(user)
|
def expand_actions(actions)
|
||||||
# to be overriden by included class
|
[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
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,40 +1,180 @@
|
|||||||
module CanCan
|
module CanCan
|
||||||
|
|
||||||
|
# This module is automatically included into all controllers.
|
||||||
|
# It also makes the "can?" and "cannot?" methods available to all views.
|
||||||
module ControllerAdditions
|
module ControllerAdditions
|
||||||
|
module ClassMethods
|
||||||
|
# Sets up a before filter which loads and authorizes the current resource. This performs both
|
||||||
|
# load_resource and authorize_resource and accepts the same arguments. See those methods for details.
|
||||||
|
#
|
||||||
|
# class BooksController < ApplicationController
|
||||||
|
# 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 }
|
||||||
|
end
|
||||||
|
|
||||||
|
# Sets up a before filter which loads the appropriate 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"
|
||||||
|
# action.
|
||||||
|
#
|
||||||
|
# Call this method directly on the controller class.
|
||||||
|
#
|
||||||
|
# class BooksController < ApplicationController
|
||||||
|
# load_resource
|
||||||
|
# end
|
||||||
|
#
|
||||||
|
# A resource is not loaded if the instance variable is already set. This makes it easy to override
|
||||||
|
# the behavior through a before_filter on certain actions.
|
||||||
|
#
|
||||||
|
# class BooksController < ApplicationController
|
||||||
|
# before_filter :find_book_by_permalink, :only => :show
|
||||||
|
# load_resource
|
||||||
|
#
|
||||||
|
# private
|
||||||
|
#
|
||||||
|
# def find_book_by_permalink
|
||||||
|
# @book = Book.find_by_permalink!(params[:id)
|
||||||
|
# end
|
||||||
|
# end
|
||||||
|
#
|
||||||
|
# See load_and_authorize_resource to automatically authorize the resource too.
|
||||||
|
#
|
||||||
|
# Options:
|
||||||
|
# [:+only+]
|
||||||
|
# Only applies before filter to given actions.
|
||||||
|
#
|
||||||
|
# [:+except+]
|
||||||
|
# Does not apply before filter to given actions.
|
||||||
|
#
|
||||||
|
# [:+nested+]
|
||||||
|
# Specify which resource this is nested under.
|
||||||
|
#
|
||||||
|
# load_resource :nested => :author
|
||||||
|
#
|
||||||
|
# Deep nesting can be defined in an array.
|
||||||
|
#
|
||||||
|
# load_resource :nested => [:publisher, :author]
|
||||||
|
#
|
||||||
|
# [:+class+]
|
||||||
|
# The class to use for the model.
|
||||||
|
#
|
||||||
|
# [:+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+.
|
||||||
|
#
|
||||||
|
# load_resource :collection => [:sort, :list]
|
||||||
|
#
|
||||||
|
# [:+new+]
|
||||||
|
# Specify which actions are new resource actions in addition to :+new+ and :+create+.
|
||||||
|
# Pass an action name into here if you would like to build a new resource instead of
|
||||||
|
# fetch one.
|
||||||
|
#
|
||||||
|
# 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 }
|
||||||
|
end
|
||||||
|
|
||||||
|
# Sets up a before filter which authorizes the current 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)
|
||||||
|
#
|
||||||
|
# Call this method directly on the controller class.
|
||||||
|
#
|
||||||
|
# class BooksController < ApplicationController
|
||||||
|
# authorize_resource
|
||||||
|
# end
|
||||||
|
#
|
||||||
|
# See load_and_authorize_resource to automatically load the resource too.
|
||||||
|
#
|
||||||
|
# Options:
|
||||||
|
# [:+only+]
|
||||||
|
# Only applies before filter to given actions.
|
||||||
|
#
|
||||||
|
# [:+except+]
|
||||||
|
# Does not apply before filter to given actions.
|
||||||
|
#
|
||||||
|
# [:+class+]
|
||||||
|
# The class to use for the model.
|
||||||
|
#
|
||||||
|
def authorize_resource(options = {})
|
||||||
|
before_filter(options.slice(:only, :except)) { |c| ResourceAuthorization.new(c, c.params, options.except(:only, :except)).authorize_resource }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
def self.included(base)
|
def self.included(base)
|
||||||
base.helper_method :can?
|
base.extend ClassMethods
|
||||||
|
base.helper_method :can?, :cannot?
|
||||||
end
|
end
|
||||||
|
|
||||||
def unauthorized!
|
# Raises the CanCan::AccessDenied exception. This is often used in a
|
||||||
raise AccessDenied, "You are unable to access this page."
|
# controller action to mark a request as unauthorized.
|
||||||
|
#
|
||||||
|
# def show
|
||||||
|
# @article = Article.find(params[:id])
|
||||||
|
# unauthorized! if cannot? :read, @article
|
||||||
|
# end
|
||||||
|
#
|
||||||
|
# The unauthorized! method accepts an optional argument which sets the
|
||||||
|
# message of the exception.
|
||||||
|
#
|
||||||
|
# You can rescue from the exception in the controller to define the behavior.
|
||||||
|
#
|
||||||
|
# class ApplicationController < ActionController::Base
|
||||||
|
# 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!(message = "You are not authorized to access this page.")
|
||||||
|
raise AccessDenied, message
|
||||||
end
|
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 current_ability
|
||||||
|
# UserAbility.new(current_account) # instead of Ability.new(current_user)
|
||||||
|
# end
|
||||||
|
#
|
||||||
def current_ability
|
def current_ability
|
||||||
ability = ::Ability.new
|
::Ability.new(current_user)
|
||||||
ability.prepare(current_user)
|
|
||||||
ability
|
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Use 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 %>
|
||||||
|
#
|
||||||
|
# This simply calls "can?" on the current_ability. See Ability#can?.
|
||||||
def can?(*args)
|
def can?(*args)
|
||||||
(@current_ability ||= current_ability).can?(*args)
|
(@current_ability ||= current_ability).can?(*args)
|
||||||
end
|
end
|
||||||
|
|
||||||
def load_resource # TODO this could use some refactoring
|
# Convenience method which works the same as "can?" but returns the opposite value.
|
||||||
unless params[:action] == "index"
|
#
|
||||||
if params[:id]
|
# cannot? :destroy, @project
|
||||||
instance_variable_set("@#{params[:controller].singularize}", params[:controller].singularize.camelcase.constantize.find(params[:id]))
|
#
|
||||||
else
|
def cannot?(*args)
|
||||||
instance_variable_set("@#{params[:controller].singularize}", params[:controller].singularize.camelcase.constantize.new(params[params[:controller].singularize.to_sym]))
|
(@current_ability ||= current_ability).cannot?(*args)
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def authorize_resource # TODO this could use some refactoring
|
|
||||||
unauthorized! unless can?(params[:action].to_sym, instance_variable_get("@#{params[:controller].singularize}") || params[:controller].singularize.camelcase.constantize)
|
|
||||||
end
|
|
||||||
|
|
||||||
def load_and_authorize_resource
|
|
||||||
load_resource
|
|
||||||
authorize_resource
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -43,4 +183,4 @@ if defined? ActionController
|
|||||||
ActionController::Base.class_eval do
|
ActionController::Base.class_eval do
|
||||||
include CanCan::ControllerAdditions
|
include CanCan::ControllerAdditions
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
40
lib/cancan/controller_resource.rb
Normal file
40
lib/cancan/controller_resource.rb
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
module CanCan
|
||||||
|
class ControllerResource # :nodoc:
|
||||||
|
def initialize(controller, name, parent = nil, options = {})
|
||||||
|
@controller = controller
|
||||||
|
@name = name
|
||||||
|
@parent = parent
|
||||||
|
@options = options
|
||||||
|
end
|
||||||
|
|
||||||
|
def model_class
|
||||||
|
@options[: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)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def model_instance
|
||||||
|
@controller.instance_variable_get("@#{@name}")
|
||||||
|
end
|
||||||
|
|
||||||
|
def model_instance=(instance)
|
||||||
|
@controller.instance_variable_set("@#{@name}", instance)
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def base
|
||||||
|
@parent ? @parent.model_instance.send(@name.to_s.pluralize) : model_class
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
62
lib/cancan/resource_authorization.rb
Normal file
62
lib/cancan/resource_authorization.rb
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
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, @options)
|
||||||
|
end
|
||||||
|
|
||||||
|
def parent_resource
|
||||||
|
parent = nil
|
||||||
|
[@options[:nested]].flatten.compact.each do |name|
|
||||||
|
id = @params["#{name}_id".to_sym]
|
||||||
|
if id
|
||||||
|
parent = ControllerResource.new(@controller, name, parent)
|
||||||
|
parent.find(id)
|
||||||
|
else
|
||||||
|
parent = nil
|
||||||
|
end
|
||||||
|
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
|
||||||
@@ -2,9 +2,8 @@ require File.dirname(__FILE__) + '/../spec_helper'
|
|||||||
|
|
||||||
describe CanCan::Ability do
|
describe CanCan::Ability do
|
||||||
before(:each) do
|
before(:each) do
|
||||||
@ability_class = Class.new
|
@ability = Object.new
|
||||||
@ability_class.send(:include, CanCan::Ability)
|
@ability.extend(CanCan::Ability)
|
||||||
@ability = @ability_class.new
|
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should be able to :read anything" do
|
it "should be able to :read anything" do
|
||||||
@@ -50,9 +49,7 @@ describe CanCan::Ability do
|
|||||||
|
|
||||||
it "should alias update or destroy actions to modify action" do
|
it "should alias update or destroy actions to modify action" do
|
||||||
@ability.alias_action :update, :destroy, :to => :modify
|
@ability.alias_action :update, :destroy, :to => :modify
|
||||||
@ability.can :modify, :all do |object_class, object|
|
@ability.can(:modify, :all) { :modify_called }
|
||||||
:modify_called
|
|
||||||
end
|
|
||||||
@ability.can?(:update, 123).should == :modify_called
|
@ability.can?(:update, 123).should == :modify_called
|
||||||
@ability.can?(:destroy, 123).should == :modify_called
|
@ability.can?(:destroy, 123).should == :modify_called
|
||||||
end
|
end
|
||||||
@@ -78,7 +75,61 @@ describe CanCan::Ability do
|
|||||||
@ability.can?(:edit, 123).should == :update_called
|
@ability.can?(:edit, 123).should == :update_called
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should respond to prepare" do
|
it "should not respond to prepare (now using initialize)" do
|
||||||
@ability.should respond_to(:prepare)
|
@ability.should_not respond_to(:prepare)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should offer cannot? method which is simply invert of can?" do
|
||||||
|
@ability.cannot?(:tie, String).should be_true
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should be able to specify multiple actions and match any" do
|
||||||
|
@ability.can [:read, :update], :all
|
||||||
|
@ability.can?(:read, 123).should be_true
|
||||||
|
@ability.can?(:update, 123).should be_true
|
||||||
|
@ability.can?(:count, 123).should be_false
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should be able to specify multiple classes and match any" do
|
||||||
|
@ability.can :update, [String, Array]
|
||||||
|
@ability.can?(:update, "foo").should be_true
|
||||||
|
@ability.can?(:update, []).should be_true
|
||||||
|
@ability.can?(:update, 123).should be_false
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should support custom objects in the can definition" do
|
||||||
|
@ability.can :read, :stats
|
||||||
|
@ability.can?(:read, :stats).should be_true
|
||||||
|
@ability.can?(:update, :stats).should be_false
|
||||||
|
@ability.can?(:read, :nonstats).should be_false
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should support 'cannot' method to define what user cannot do" do
|
||||||
|
@ability.can :read, :all
|
||||||
|
@ability.cannot :read, Integer
|
||||||
|
@ability.can?(:read, "foo").should be_true
|
||||||
|
@ability.can?(:read, 123).should be_false
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should support block on 'cannot' method" do
|
||||||
|
@ability.can :read, :all
|
||||||
|
@ability.cannot :read, Integer do |int|
|
||||||
|
int > 5
|
||||||
|
end
|
||||||
|
@ability.can?(:read, "foo").should be_true
|
||||||
|
@ability.can?(:read, 3).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
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,21 +1,24 @@
|
|||||||
require File.dirname(__FILE__) + '/../spec_helper'
|
require File.dirname(__FILE__) + '/../spec_helper'
|
||||||
|
|
||||||
class Ability
|
|
||||||
include CanCan::Ability
|
|
||||||
end
|
|
||||||
|
|
||||||
describe CanCan::ControllerAdditions do
|
describe CanCan::ControllerAdditions do
|
||||||
before(:each) do
|
before(:each) do
|
||||||
@controller_class = Class.new
|
@controller_class = Class.new
|
||||||
@controller = @controller_class.new
|
@controller = @controller_class.new
|
||||||
mock(@controller_class).helper_method(:can?)
|
stub(@controller).params { {} }
|
||||||
|
mock(@controller_class).helper_method(:can?, :cannot?)
|
||||||
@controller_class.send(:include, CanCan::ControllerAdditions)
|
@controller_class.send(:include, CanCan::ControllerAdditions)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should read from the cache with request uri as key and render that text" do
|
it "should raise access denied with default message when calling unauthorized!" do
|
||||||
lambda {
|
lambda {
|
||||||
@controller.unauthorized!
|
@controller.unauthorized!
|
||||||
}.should raise_error(CanCan::AccessDenied)
|
}.should raise_error(CanCan::AccessDenied, "You are not authorized to access this page.")
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should raise access denied with custom message when calling unauthorized!" do
|
||||||
|
lambda {
|
||||||
|
@controller.unauthorized! "Access denied!"
|
||||||
|
}.should raise_error(CanCan::AccessDenied, "Access denied!")
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should have a current_ability method which generates an ability for the current user" do
|
it "should have a current_ability method which generates an ability for the current user" do
|
||||||
@@ -23,59 +26,28 @@ describe CanCan::ControllerAdditions do
|
|||||||
@controller.current_ability.should be_kind_of(Ability)
|
@controller.current_ability.should be_kind_of(Ability)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should provide a can? method which goes through the current ability" do
|
it "should provide a can? and cannot? methods which go through the current ability" do
|
||||||
stub(@controller).current_user { :current_user }
|
stub(@controller).current_user { :current_user }
|
||||||
@controller.current_ability.should be_kind_of(Ability)
|
@controller.current_ability.should be_kind_of(Ability)
|
||||||
@controller.can?(:foo, :bar).should be_false
|
@controller.can?(:foo, :bar).should be_false
|
||||||
|
@controller.cannot?(:foo, :bar).should be_true
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should load the resource if params[:id] is specified" do
|
it "load_and_authorize_resource should setup a before filter which passes call to ResourceAuthorization" do
|
||||||
stub(@controller).params { {:controller => "abilities", :action => "show", :id => 123} }
|
stub(CanCan::ResourceAuthorization).new(@controller, @controller.params, :foo => :bar).mock!.load_and_authorize_resource
|
||||||
stub(Ability).find(123) { :some_resource }
|
mock(@controller_class).before_filter({}) { |options, block| block.call(@controller) }
|
||||||
@controller.load_resource
|
@controller_class.load_and_authorize_resource :foo => :bar
|
||||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should build a new resource with hash if params[:id] is not specified" do
|
it "authorize_resource should setup a before filter which passes call to ResourceAuthorization" do
|
||||||
stub(@controller).params { {:controller => "abilities", :action => "create", :ability => {:foo => "bar"}} }
|
stub(CanCan::ResourceAuthorization).new(@controller, @controller.params, :foo => :bar).mock!.authorize_resource
|
||||||
stub(Ability).new(:foo => "bar") { :some_resource }
|
mock(@controller_class).before_filter(:except => :show) { |options, block| block.call(@controller) }
|
||||||
@controller.load_resource
|
@controller_class.authorize_resource :foo => :bar, :except => :show
|
||||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should build a new resource even if attribute hash isn't specified" do
|
it "load_resource should setup a before filter which passes call to ResourceAuthorization" do
|
||||||
stub(@controller).params { {:controller => "abilities", :action => "new"} }
|
stub(CanCan::ResourceAuthorization).new(@controller, @controller.params, :foo => :bar).mock!.load_resource
|
||||||
stub(Ability).new(nil) { :some_resource }
|
mock(@controller_class).before_filter(:only => [:show, :index]) { |options, block| block.call(@controller) }
|
||||||
@controller.load_resource
|
@controller_class.load_resource :foo => :bar, :only => [:show, :index]
|
||||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should not build a resource when on index action" do
|
|
||||||
stub(@controller).params { {:controller => "abilities", :action => "index"} }
|
|
||||||
@controller.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).params { {:controller => "abilities", :action => "show"} }
|
|
||||||
stub(@controller).can?(:show, :some_resource) { false }
|
|
||||||
lambda {
|
|
||||||
@controller.authorize_resource
|
|
||||||
}.should raise_error(CanCan::AccessDenied)
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should perform authorization using controller action and non loaded model" do
|
|
||||||
stub(@controller).params { {:controller => "abilities", :action => "show"} }
|
|
||||||
stub(@controller).can?(:show, Ability) { false }
|
|
||||||
lambda {
|
|
||||||
@controller.authorize_resource
|
|
||||||
}.should raise_error(CanCan::AccessDenied)
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should load and authorize resource in one call" do
|
|
||||||
mock(@controller).load_resource
|
|
||||||
stub(@controller).authorize_resource
|
|
||||||
@controller.load_and_authorize_resource
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
49
spec/cancan/controller_resource_spec.rb
Normal file
49
spec/cancan/controller_resource_spec.rb
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
require File.dirname(__FILE__) + '/../spec_helper'
|
||||||
|
|
||||||
|
describe CanCan::ControllerResource do
|
||||||
|
before(:each) do
|
||||||
|
@controller = Object.new
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should determine model class by constantizing give name" do
|
||||||
|
CanCan::ControllerResource.new(@controller, :ability).model_class.should == Ability
|
||||||
|
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
|
||||||
|
@controller.instance_variable_set(:@ability, :some_ability)
|
||||||
|
CanCan::ControllerResource.new(@controller, :ability).find(123)
|
||||||
|
@controller.instance_variable_get(:@ability).should == :some_ability
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should use the model class option if provided" do
|
||||||
|
stub(Person).find(123) { :some_resource }
|
||||||
|
CanCan::ControllerResource.new(@controller, :ability, nil, :class => Person).find(123)
|
||||||
|
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||||
|
end
|
||||||
|
end
|
||||||
115
spec/cancan/resource_authorization_spec.rb
Normal file
115
spec/cancan/resource_authorization_spec.rb
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
it "should not load nested resource and build through this if *_id param isn't specified" do
|
||||||
|
stub(Person).find(456) { :some_person }
|
||||||
|
stub(Ability).new(nil) { :some_ability }
|
||||||
|
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "new", :person_id => 456}, {:nested => [:person, :behavior]})
|
||||||
|
authorization.load_resource
|
||||||
|
@controller.instance_variable_get(:@person).should == :some_person
|
||||||
|
@controller.instance_variable_get(:@ability).should == :some_ability
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should load the model using a custom class" do
|
||||||
|
stub(Person).find(123) { :some_resource }
|
||||||
|
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "show", :id => 123}, {:class => Person})
|
||||||
|
authorization.load_resource
|
||||||
|
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -9,3 +9,14 @@ require File.dirname(__FILE__) + '/../lib/cancan.rb'
|
|||||||
Spec::Runner.configure do |config|
|
Spec::Runner.configure do |config|
|
||||||
config.mock_with :rr
|
config.mock_with :rr
|
||||||
end
|
end
|
||||||
|
|
||||||
|
class Ability
|
||||||
|
include CanCan::Ability
|
||||||
|
|
||||||
|
def initialize(user)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# this class helps out in testing nesting
|
||||||
|
class Person
|
||||||
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user