Compare commits
94 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
872e4cfba8 | ||
|
|
787511a208 | ||
|
|
92995d791e | ||
|
|
ebf77ed647 | ||
|
|
9a7c427373 | ||
|
|
cf263c105d | ||
|
|
79180de372 | ||
|
|
f901c367fc | ||
|
|
67cd83dd96 | ||
|
|
6c3e87eea9 | ||
|
|
fa766e71ed | ||
|
|
b0cec5251c | ||
|
|
18b45d5cfc | ||
|
|
8f49f28713 | ||
|
|
12037d7f43 | ||
|
|
1f81b8dd1e | ||
|
|
3391c5a0d7 | ||
|
|
c11ffb6fd1 | ||
|
|
264e2d2b68 | ||
|
|
ebef3cc745 | ||
|
|
cef55c95e7 | ||
|
|
7e0e72276e | ||
|
|
ff9a91705b | ||
|
|
a0f73fe0f7 | ||
|
|
e2c341b8d3 | ||
|
|
f236b1b5a4 | ||
|
|
0b270f2d0f | ||
|
|
961df90ecd | ||
|
|
4eee637270 | ||
|
|
a5ff826e40 | ||
|
|
9d915457af | ||
|
|
158c908d3b | ||
|
|
bf9b8ad1a6 | ||
|
|
1af6c6f395 | ||
|
|
7c5243321f | ||
|
|
721939babd | ||
|
|
a744377ac9 | ||
|
|
1be5bf7a57 | ||
|
|
c88cb8f459 | ||
|
|
737f8acff5 | ||
|
|
a5f838a964 | ||
|
|
66314a89f8 | ||
|
|
b1fb179aaf | ||
|
|
6105edc6a7 | ||
|
|
04b523eea4 | ||
|
|
5a353c1cba | ||
|
|
4fe44af45d | ||
|
|
a10a38c82f | ||
|
|
caed4fcee5 | ||
|
|
e893e12260 | ||
|
|
3d7742ea43 | ||
|
|
a566ea0f4f | ||
|
|
333ddf1970 | ||
|
|
cd74267364 | ||
|
|
f8631dcc93 | ||
|
|
7a17586eb3 | ||
|
|
13427e18d5 | ||
|
|
1dccc0252a | ||
|
|
75ce2bdefa | ||
|
|
c9e0f4e3ef | ||
|
|
7d9e710f05 | ||
|
|
236cece3b3 | ||
|
|
84f4c904b7 | ||
|
|
6998e8bdd1 | ||
|
|
961b8c2477 | ||
|
|
a157b65fbf | ||
|
|
47f0aa597e | ||
|
|
67b069579e | ||
|
|
156839b73e | ||
|
|
25a1c553bf | ||
|
|
8dee01195d | ||
|
|
5eae169d7b | ||
|
|
66ff1f2ea3 | ||
|
|
18dcf2a121 | ||
|
|
9b26f4d767 | ||
|
|
25637bb33a | ||
|
|
c5737f6d28 | ||
|
|
1659f21bb3 | ||
|
|
ba8cb3cf6d | ||
|
|
e098ddaacd | ||
|
|
964a4765b1 | ||
|
|
a42e067f3b | ||
|
|
60848143b7 | ||
|
|
5d8f04363d | ||
|
|
cad425989e | ||
|
|
75eb1917f9 | ||
|
|
5fd793090a | ||
|
|
ac19422a90 | ||
|
|
9c0346b90b | ||
|
|
b473d8827f | ||
|
|
bcab8d6369 | ||
|
|
dbc1538054 | ||
|
|
46f03013f3 | ||
|
|
7d7d249182 |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1 +1,5 @@
|
||||
*.swp
|
||||
**/*.swp
|
||||
*.gem
|
||||
Gemfile.lock
|
||||
.bundle
|
||||
|
||||
101
CHANGELOG.rdoc
101
CHANGELOG.rdoc
@@ -1,3 +1,104 @@
|
||||
1.4.1 (November 12, 2010)
|
||||
|
||||
* Renaming skip_authorization to skip_authorization_check - see issue #169
|
||||
|
||||
* Adding :through_association option to load_resource (thanks hunterae) - see issue #171
|
||||
|
||||
* The :shallow option now works with the :singleton option (thanks nandalopes) - see issue #187
|
||||
|
||||
* Play nicely with quick_scopes gem (thanks ramontayag) - see issue #183
|
||||
|
||||
* Fix odd behavior when "cache_classes = false" (thanks mphalliday) - see issue #174
|
||||
|
||||
|
||||
1.4.0 (October 5, 2010)
|
||||
|
||||
* Adding Gemfile; to get specs running just +bundle+ and +rake+ - see issue #163
|
||||
|
||||
* Stop at 'cannot' definition when there are no conditions - see issue #161
|
||||
|
||||
* The :through option will now call a method with that name if instance variable doesn't exist - see issue #146
|
||||
|
||||
* Adding :shallow option to load_resource to bring back old behavior of fetching a child without a parent
|
||||
|
||||
* Raise AccessDenied error when loading a child and parent resource isn't found
|
||||
|
||||
* Abilities defined on a module will apply to anything that includes that module - see issue #150 and #152
|
||||
|
||||
* Abilities can be defined with a string of SQL in addition to a block so accessible_by works with a block - see issue #150
|
||||
|
||||
* Adding better support for InheritedResource - see issue #23
|
||||
|
||||
* Loading the collection instance variable (for index action) using accessible_by - see issue #137
|
||||
|
||||
* Adding action and subject variables to I18n unauthorized message - closes #142
|
||||
|
||||
* Adding check_authorization and skip_authorization controller class methods to ensure authorization is performed (thanks justinko) - see issue #135
|
||||
|
||||
* Setting initial attributes based on ability conditions in new/create actions - see issue #114
|
||||
|
||||
* Check parent attributes for nested association in index action - see issue #121
|
||||
|
||||
* Supporting nesting in can? method using hash - see issue #121
|
||||
|
||||
* Adding I18n support for Access Denied messages (thanks EppO) - see issue #103
|
||||
|
||||
* Passing no arguments to +can+ definition will pass action, class, and object to block - see issue #129
|
||||
|
||||
* Don't pass action to block in +can+ definition when using :+manage+ option - see issue #129
|
||||
|
||||
* No longer calling block in +can+ definition when checking on class - see issue #116
|
||||
|
||||
|
||||
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)
|
||||
|
||||
2
LICENSE
2
LICENSE
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2009 Ryan Bates
|
||||
Copyright (c) 2010 Ryan Bates
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
|
||||
57
README.rdoc
57
README.rdoc
@@ -1,26 +1,30 @@
|
||||
= CanCan
|
||||
|
||||
Wiki[http://wiki.github.com/ryanb/cancan] | RDocs[http://rdoc.info/projects/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]
|
||||
Wiki[http://wiki.github.com/ryanb/cancan] | RDocs[http://rdoc.info/projects/ryanb/cancan] | Screencast[http://railscasts.com/episodes/192-authorization-with-cancan]
|
||||
|
||||
CanCan is an authorization solution for Ruby on Rails. This restricts what a given user is allowed to access throughout the application. It is completely decoupled from any role based implementation and focusses on keeping permission logic in a single location (the +Ability+ class) so it is not duplicated across controllers, views, and database queries.
|
||||
|
||||
This assumes you already have authentication (such as Authlogic[http://github.com/binarylogic/authlogic] or Devise[http://github.com/plataformatec/devise]) that provides a +current_user+ method which CanCan relies on. See {Changing Defaults}[http://wiki.github.com/ryanb/cancan/changing-defaults] if you need different behavior.
|
||||
CanCan is an authorization library for Ruby on Rails which restricts what resources a given user is allowed to access. All permissions are defined in a single location (the +Ability+ class) and not duplicated across controllers, views, and database queries.
|
||||
|
||||
|
||||
== Installation
|
||||
|
||||
CanCan is provided as a gem. Simply include it in your environment.rb or Gemfile.
|
||||
In <b>Rails 3</b>, add this to your Gemfile.
|
||||
|
||||
gem "cancan"
|
||||
|
||||
In <b>Rails 2</b>, add this to your environment.rb file.
|
||||
|
||||
config.gem "cancan"
|
||||
|
||||
Alternatively it can be installed as a plugin.
|
||||
Alternatively, you can install it as a plugin.
|
||||
|
||||
script/plugin install git://github.com/ryanb/cancan.git
|
||||
rails plugin install git://github.com/ryanb/cancan.git
|
||||
|
||||
|
||||
== Getting Started
|
||||
|
||||
First, define a class called +Ability+ in "models/ability.rb". It should look something like this.
|
||||
CanCan expects a +current_user+ method to exist. 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.
|
||||
|
||||
Next create a class called +Ability+ in "models/ability.rb" or anywhere else in the load path. It should look similar to this.
|
||||
|
||||
class Ability
|
||||
include CanCan::Ability
|
||||
@@ -34,7 +38,7 @@ First, define a class called +Ability+ in "models/ability.rb". It should look so
|
||||
end
|
||||
end
|
||||
|
||||
This is where all permissions will go. See the "Defining Abilities" section below for more information.
|
||||
The +current_user+ is passed in to this method which is where the abilities are defined. See the "Defining Abilities" section below for more information.
|
||||
|
||||
The current user's permissions can be accessed using the "can?" and "cannot?" methods in the view and controller.
|
||||
|
||||
@@ -63,11 +67,11 @@ Setting this for every action can be tedious, therefore the +load_and_authorize_
|
||||
|
||||
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+.
|
||||
If the user authorization fails, a <tt>CanCan::AccessDenied</tt> exception will be raised. You can catch this and modify its behavior in the +ApplicationController+.
|
||||
|
||||
class ApplicationController < ActionController::Base
|
||||
rescue_from CanCan::AccessDenied do |exception|
|
||||
flash[:error] = exception.message
|
||||
flash[:alert] = exception.message
|
||||
redirect_to root_url
|
||||
end
|
||||
end
|
||||
@@ -77,7 +81,7 @@ See {Exception Handling}[http://wiki.github.com/ryanb/cancan/exception-handling]
|
||||
|
||||
== 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 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.
|
||||
As shown above, the +Ability+ class is where all user permissions are defined. The current user model is passed into the initialize method so the permissions can be modified based on any user attributes. CanCan makes no assumption 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 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.
|
||||
|
||||
@@ -93,7 +97,7 @@ Use :+manage+ to represent any action and :+all+ to represent any class. Here ar
|
||||
can :read, :all # has permission to read any model
|
||||
can :manage, :all # has permission to do anything to any model
|
||||
|
||||
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.
|
||||
You can pass a hash of conditions as the third argument to further define 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
|
||||
|
||||
@@ -102,10 +106,10 @@ See {Defining Abilities with Hashes}[http://wiki.github.com/ryanb/cancan/definin
|
||||
Blocks can also be used if you need more control.
|
||||
|
||||
can :update, Project do |project|
|
||||
project && project.groups.include?(user.group)
|
||||
project.groups.include?(user.group)
|
||||
end
|
||||
|
||||
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.
|
||||
If the block returns true then the user has that 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
|
||||
@@ -116,32 +120,43 @@ You will usually be working with four actions when defining and checking permiss
|
||||
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
|
||||
Notice the +edit+ action is aliased to +update+. This means 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.
|
||||
|
||||
alias_action :update, :destroy, :to => :modify
|
||||
can :modify, Comment
|
||||
can? :update, Comment # => true
|
||||
|
||||
See {Custom Actions}[http://wiki.github.com/ryanb/cancan/custom-actions] for information on adding other actions.
|
||||
The +alias_action+ method is an instance method and usually called in +initialize+. See {Custom Actions}[http://wiki.github.com/ryanb/cancan/custom-actions] for information on adding other actions.
|
||||
|
||||
|
||||
== Fetching Records
|
||||
|
||||
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.
|
||||
It is possible to fetch records which the user has permission to read using the +accessible_by+ scope in Active Record.
|
||||
|
||||
@articles = Article.accessible_by(current_ability)
|
||||
|
||||
See {Fetching Records}[http://wiki.github.com/ryanb/cancan/fetching-records] for more information.
|
||||
Since version 1.4 this is done automatically when loading resources in the index action, so one rarely needs to do it manually.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
== Additional Docs
|
||||
|
||||
* {Upgrading to 1.1}[http://wiki.github.com/ryanb/cancan/upgrading-to-11]
|
||||
* {Upgrading to 1.4}[http://github.com/ryanb/cancan/wiki/Upgrading-to-1.4]
|
||||
* {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/]
|
||||
|
||||
|
||||
== Questions or Problems?
|
||||
|
||||
If you have any issues with CanCan which you cannot find the solution to in the documentation, please add an {issue on GitHub}[http://github.com/ryanb/cancan/issues] or fork the project and send a pull request.
|
||||
|
||||
To get the specs running you should call +bundle+ and then +rake+. Specs currently do not work in Ruby 1.9 due to the RR mocking framework.
|
||||
|
||||
|
||||
== 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.
|
||||
|
||||
11
Rakefile
11
Rakefile
@@ -1,13 +1,10 @@
|
||||
require 'rubygems'
|
||||
require 'rake'
|
||||
require 'spec/rake/spectask'
|
||||
require 'rspec/core/rake_task'
|
||||
|
||||
spec_files = Rake::FileList["spec/**/*_spec.rb"]
|
||||
|
||||
desc "Run specs"
|
||||
Spec::Rake::SpecTask.new do |t|
|
||||
t.spec_files = spec_files
|
||||
t.spec_opts = ["-c"]
|
||||
desc "Run RSpec"
|
||||
RSpec::Core::RakeTask.new do |t|
|
||||
t.verbose = false
|
||||
end
|
||||
|
||||
task :default => :spec
|
||||
@@ -1,15 +1,20 @@
|
||||
Gem::Specification.new do |s|
|
||||
s.name = "cancan"
|
||||
s.version = "1.2.0"
|
||||
s.version = "1.4.1"
|
||||
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 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 decoupled from user roles. All permissions are stored in a single location."
|
||||
|
||||
s.files = Dir["{lib,spec}/**/*", "[A-Z]*", "init.rb"]
|
||||
s.files = Dir["{lib,spec}/**/*", "[A-Z]*", "init.rb"] - ["Gemfile.lock"]
|
||||
s.require_path = "lib"
|
||||
|
||||
s.add_development_dependency 'rspec', '~> 2.0.0.beta.22'
|
||||
s.add_development_dependency 'rails', '~> 3.0.0'
|
||||
s.add_development_dependency 'rr', '~> 0.10.11' # 1.0.0 has respond_to? issues: http://github.com/btakita/rr/issues/issue/43
|
||||
s.add_development_dependency 'supermodel', '~> 0.1.4'
|
||||
|
||||
s.rubyforge_project = s.name
|
||||
s.required_rubygems_version = ">= 1.3.4"
|
||||
end
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
require 'cancan/ability'
|
||||
require 'cancan/can_definition'
|
||||
require 'cancan/controller_resource'
|
||||
require 'cancan/resource_authorization'
|
||||
require 'cancan/controller_additions'
|
||||
require 'cancan/active_record_additions'
|
||||
require 'cancan/exceptions'
|
||||
require 'cancan/query'
|
||||
require 'cancan/inherited_resource'
|
||||
|
||||
@@ -16,7 +16,7 @@ module CanCan
|
||||
# end
|
||||
#
|
||||
module Ability
|
||||
# Use to check if the user has permission to perform a given action on an object.
|
||||
# Check if the user has permission to perform a given action on an object.
|
||||
#
|
||||
# can? :destroy, @project
|
||||
#
|
||||
@@ -24,6 +24,11 @@ module CanCan
|
||||
#
|
||||
# can? :create, Project
|
||||
#
|
||||
# Nested resources can be passed through a hash, this way conditions which are
|
||||
# dependent upon the association will work when using a class.
|
||||
#
|
||||
# can? :create, @category => 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.
|
||||
#
|
||||
@@ -49,9 +54,10 @@ module CanCan
|
||||
#
|
||||
# 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
|
||||
can_definition = matching_can_definition(action, subject)
|
||||
can_definition && can_definition.can?(action, subject, extra_args)
|
||||
match = relevant_can_definitions_for_match(action, subject).detect do |can_definition|
|
||||
can_definition.matches_conditions?(action, subject, extra_args)
|
||||
end
|
||||
match ? match.base_behavior : false
|
||||
end
|
||||
|
||||
# Convenience method which works the same as "can?" but returns the opposite value.
|
||||
@@ -68,54 +74,54 @@ module CanCan
|
||||
# can :update, Article
|
||||
#
|
||||
# You can pass an array for either of these parameters to match any one.
|
||||
# Here the user has 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.
|
||||
# You can pass :all to match any object and :manage to match any action. Here are some examples.
|
||||
#
|
||||
# You can pass a hash of conditions as the third argument.
|
||||
# can :manage, :all
|
||||
# can :update, :all
|
||||
# can :manage, Project
|
||||
#
|
||||
# You can pass a hash of conditions as the third argument. Here the user can only see active projects which he owns.
|
||||
#
|
||||
# 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.
|
||||
# See ActiveRecordAdditions#accessible_by for how to use this in database queries. These conditions
|
||||
# are also used for initial attributes when building a record in ControllerAdditions#load_resource.
|
||||
#
|
||||
# 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.
|
||||
# If the conditions hash does not give you enough control over defining abilities, you can use a block
|
||||
# along with any Ruby code you want.
|
||||
#
|
||||
# can :update, Project do |project|
|
||||
# project && project.groups.include?(user.group)
|
||||
# project.groups.include?(user.group)
|
||||
# end
|
||||
#
|
||||
# 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.
|
||||
# will be denied access. The downside to using a block is that it cannot be used to generate
|
||||
# conditions for database queries.
|
||||
#
|
||||
# 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).
|
||||
#
|
||||
# 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
|
||||
# You can pass custom objects into this "can" method, this is usually done with 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, subject, conditions = nil, &block)
|
||||
# IMPORTANT: Neither a hash of conditions or a block will be used when checking permission on a class.
|
||||
#
|
||||
# can :update, Project, :priority => 3
|
||||
# can? :update, Project # => true
|
||||
#
|
||||
# If you pass no arguments to +can+, the action, class, and object will be passed to the block and the
|
||||
# block will always be executed. This allows you to override the full behavior if the permissions are
|
||||
# defined in an external source such as the database.
|
||||
#
|
||||
# can do |action, object_class, object|
|
||||
# # check the database and return true/false
|
||||
# end
|
||||
#
|
||||
def can(action = nil, subject = nil, conditions = nil, &block)
|
||||
can_definitions << CanDefinition.new(true, action, subject, conditions, block)
|
||||
end
|
||||
|
||||
@@ -131,7 +137,7 @@ module CanCan
|
||||
# product.invisible?
|
||||
# end
|
||||
#
|
||||
def cannot(action, subject, conditions = nil, &block)
|
||||
def cannot(action = nil, subject = nil, conditions = nil, &block)
|
||||
can_definitions << CanDefinition.new(false, action, subject, conditions, block)
|
||||
end
|
||||
|
||||
@@ -180,47 +186,105 @@ module CanCan
|
||||
@aliased_actions = {}
|
||||
end
|
||||
|
||||
# Returns a hash of conditions which match the given ability. This is useful if you need to generate a database
|
||||
# query based on the current ability.
|
||||
#
|
||||
# can :read, Article, :visible => true
|
||||
# conditions :read, Article # returns { :visible => true }
|
||||
#
|
||||
# Normally you will not call this method directly, but instead go through ActiveRecordAdditions#accessible_by method.
|
||||
#
|
||||
# If the ability is not defined then false is returned so be sure to take that into consideration.
|
||||
# If the ability is defined using a block then this will raise an exception since a hash of conditions cannot be
|
||||
# determined from that.
|
||||
def conditions(action, subject, options = {})
|
||||
can_definition = matching_can_definition(action, subject)
|
||||
if can_definition
|
||||
raise Error, "Cannot determine ability conditions from block for #{action.inspect} #{subject.inspect}" if can_definition.block
|
||||
can_definition.conditions(options) || {}
|
||||
else
|
||||
false
|
||||
# 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
|
||||
|
||||
# See ControllerAdditions#authorize! for documentation.
|
||||
def authorize!(action, subject, *args)
|
||||
message = nil
|
||||
if args.last.kind_of?(Hash) && args.last.has_key?(:message)
|
||||
message = args.pop[:message]
|
||||
end
|
||||
if cannot?(action, subject, *args)
|
||||
message ||= unauthorized_message(action, subject)
|
||||
raise AccessDenied.new(message, action, subject)
|
||||
end
|
||||
end
|
||||
|
||||
# Returns the associations used in conditions. This is usually used in the :joins option for a search.
|
||||
# See ActiveRecordAdditions#accessible_by for use in Active Record.
|
||||
def association_joins(action, subject)
|
||||
can_definition = matching_can_definition(action, subject)
|
||||
if can_definition
|
||||
raise Error, "Cannot determine association joins from block for #{action.inspect} #{subject.inspect}" if can_definition.block
|
||||
can_definition.association_joins
|
||||
def unauthorized_message(action, subject)
|
||||
keys = unauthorized_message_keys(action, subject)
|
||||
variables = {:action => action.to_s}
|
||||
variables[:subject] = (subject.class == Class ? subject : subject.class).to_s.downcase
|
||||
message = I18n.translate(nil, variables.merge(:scope => :unauthorized, :default => keys + [""]))
|
||||
message.blank? ? nil : message
|
||||
end
|
||||
|
||||
def attributes_for(action, subject)
|
||||
attributes = {}
|
||||
relevant_can_definitions(action, subject).map do |can_definition|
|
||||
attributes.merge!(can_definition.attributes_from_conditions) if can_definition.base_behavior
|
||||
end
|
||||
attributes
|
||||
end
|
||||
|
||||
def has_block?(action, subject)
|
||||
relevant_can_definitions(action, subject).any?(&:only_block?)
|
||||
end
|
||||
|
||||
def has_raw_sql?(action, subject)
|
||||
relevant_can_definitions(action, subject).any?(&:only_raw_sql?)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def unauthorized_message_keys(action, subject)
|
||||
subject = (subject.class == Class ? subject : subject.class).name.underscore unless subject.kind_of? Symbol
|
||||
[subject, :all].map do |try_subject|
|
||||
[aliases_for_action(action), :manage].flatten.map do |try_action|
|
||||
:"#{try_action}.#{try_subject}"
|
||||
end
|
||||
end.flatten
|
||||
end
|
||||
|
||||
# Accepts an array of 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
|
||||
|
||||
# Given an action, it will try to find all of the actions which are aliased to it.
|
||||
# This does the opposite kind of lookup as expand_actions.
|
||||
def aliases_for_action(action)
|
||||
results = [action]
|
||||
aliased_actions.each do |aliased_action, actions|
|
||||
results += aliases_for_action(aliased_action) if actions.include? action
|
||||
end
|
||||
results
|
||||
end
|
||||
|
||||
def can_definitions
|
||||
@can_definitions ||= []
|
||||
end
|
||||
|
||||
def matching_can_definition(action, subject)
|
||||
can_definitions.reverse.detect do |can_definition|
|
||||
can_definition.expand_actions(aliased_actions)
|
||||
can_definition.matches? action, subject
|
||||
# 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_match(action, subject)
|
||||
relevant_can_definitions(action, subject).each do |can_definition|
|
||||
if can_definition.only_raw_sql?
|
||||
raise Error, "The can? and cannot? call cannot be used with a raw sql 'can' definition. The checking code cannot be determined for #{action.inspect} #{subject.inspect}"
|
||||
end
|
||||
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
|
||||
|
||||
|
||||
@@ -20,12 +20,11 @@ module CanCan
|
||||
# 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)
|
||||
conditions = ability.conditions(action, self, :tableize => true) || {:id => nil}
|
||||
joins = ability.association_joins(action, self)
|
||||
if respond_to? :where
|
||||
where(conditions).joins(joins)
|
||||
query = ability.query(action, self)
|
||||
if respond_to?(:where) && respond_to?(:joins)
|
||||
where(query.conditions).joins(query.joins)
|
||||
else
|
||||
scoped(:conditions => conditions, :joins => joins)
|
||||
scoped(:conditions => query.conditions, :joins => query.joins)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -3,14 +3,15 @@ module CanCan
|
||||
# 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:
|
||||
include ActiveSupport::Inflector
|
||||
attr_reader :block
|
||||
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)
|
||||
@match_all = action.nil? && subject.nil?
|
||||
@base_behavior = base_behavior
|
||||
@actions = [action].flatten
|
||||
@subjects = [subject].flatten
|
||||
@@ -18,81 +19,95 @@ module CanCan
|
||||
@block = block
|
||||
end
|
||||
|
||||
# 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(aliased_actions)
|
||||
@expanded_actions = @actions.map do |action|
|
||||
aliased_actions[action] ? [action, *aliased_actions[action]] : action
|
||||
end.flatten
|
||||
# Matches both the subject and action, not necessarily the conditions
|
||||
def relevant?(action, subject)
|
||||
subject = subject.values.first if subject.kind_of? Hash
|
||||
@match_all || (matches_action?(action) && matches_subject?(subject))
|
||||
end
|
||||
|
||||
def matches?(action, subject)
|
||||
matches_action?(action) && matches_subject?(subject)
|
||||
end
|
||||
|
||||
def can?(action, subject, extra_args)
|
||||
result = can_without_base_behavior?(action, subject, extra_args)
|
||||
@base_behavior ? result : !result
|
||||
end
|
||||
|
||||
# Returns a hash of conditions. If the ":tableize => true" option is passed
|
||||
# it will pluralize the association conditions to match the table name.
|
||||
def conditions(options = {})
|
||||
if options[:tableize] && @conditions.kind_of?(Hash)
|
||||
@conditions.inject({}) do |tableized_conditions, (name, value)|
|
||||
name = tableize(name).to_sym if value.kind_of? Hash
|
||||
tableized_conditions[name] = value
|
||||
tableized_conditions
|
||||
end
|
||||
# Matches the block or conditions hash
|
||||
def matches_conditions?(action, subject, extra_args)
|
||||
if @match_all
|
||||
call_block_with_all(action, subject, extra_args)
|
||||
elsif @block && !subject_class?(subject)
|
||||
@block.call(subject, *extra_args)
|
||||
elsif @conditions.kind_of?(Hash) && subject.kind_of?(Hash)
|
||||
nested_subject_matches_conditions?(subject)
|
||||
elsif @conditions.kind_of?(Hash) && !subject_class?(subject)
|
||||
matches_conditions_hash?(subject)
|
||||
else
|
||||
@conditions
|
||||
# Don't stop at "cannot" definitions when there are conditions.
|
||||
@conditions.empty? ? true : @base_behavior
|
||||
end
|
||||
end
|
||||
|
||||
def association_joins(conditions = @conditions)
|
||||
joins = []
|
||||
conditions.each do |name, value|
|
||||
def tableized_conditions(conditions = @conditions)
|
||||
return conditions unless conditions.kind_of? Hash
|
||||
conditions.inject({}) do |result_hash, (name, value)|
|
||||
if value.kind_of? Hash
|
||||
nested = association_joins(value)
|
||||
if nested
|
||||
joins << {name => nested}
|
||||
else
|
||||
joins << name
|
||||
end
|
||||
name = name.to_s.tableize.to_sym
|
||||
value = tableized_conditions(value)
|
||||
end
|
||||
result_hash[name] = value
|
||||
result_hash
|
||||
end
|
||||
joins unless joins.empty?
|
||||
end
|
||||
|
||||
def only_block?
|
||||
conditions_empty? && !@block.nil?
|
||||
end
|
||||
|
||||
def only_raw_sql?
|
||||
@block.nil? && !conditions_empty? && !@conditions.kind_of?(Hash)
|
||||
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 if conditions.kind_of? Hash
|
||||
hash
|
||||
end
|
||||
|
||||
def attributes_from_conditions
|
||||
attributes = {}
|
||||
@conditions.each do |key, value|
|
||||
attributes[key] = value unless [Array, Range, Hash].include? value.class
|
||||
end if @conditions.kind_of? Hash
|
||||
attributes
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def subject_class?(subject)
|
||||
klass = (subject.kind_of?(Hash) ? subject.values.first : subject).class
|
||||
klass == Class || klass == Module
|
||||
end
|
||||
|
||||
def matches_action?(action)
|
||||
@expanded_actions.include?(:manage) || @expanded_actions.include?(action)
|
||||
end
|
||||
|
||||
def matches_subject?(subject)
|
||||
@subjects.include?(:all) || @subjects.include?(subject) || @subjects.any? { |sub| sub.kind_of?(Class) && subject.kind_of?(sub) }
|
||||
@subjects.include?(:all) || @subjects.include?(subject) || matches_subject_class?(subject)
|
||||
end
|
||||
|
||||
def can_without_base_behavior?(action, subject, extra_args)
|
||||
if @block
|
||||
call_block(action, subject, extra_args)
|
||||
elsif @conditions && subject.class != Class
|
||||
matches_conditions? subject
|
||||
else
|
||||
true
|
||||
end
|
||||
def matches_subject_class?(subject)
|
||||
@subjects.any? { |sub| sub.kind_of?(Module) && (subject.kind_of?(sub) || subject.class.to_s == sub.to_s || subject.kind_of?(Module) && subject.ancestors.include?(sub)) }
|
||||
end
|
||||
|
||||
def matches_conditions?(subject, conditions = @conditions)
|
||||
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? element, value }
|
||||
attribute.any? { |element| matches_conditions_hash? element, value }
|
||||
else
|
||||
matches_conditions? attribute, value
|
||||
matches_conditions_hash? attribute, value
|
||||
end
|
||||
elsif value.kind_of?(Array) || value.kind_of?(Range)
|
||||
value.include? attribute
|
||||
@@ -102,13 +117,17 @@ module CanCan
|
||||
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)
|
||||
def nested_subject_matches_conditions?(subject_hash)
|
||||
parent, child = subject_hash.shift
|
||||
matches_conditions_hash?(parent, @conditions[parent.class.name.downcase.to_sym] || {})
|
||||
end
|
||||
|
||||
def call_block_with_all(action, subject, extra_args)
|
||||
if subject.class == Class
|
||||
@block.call(action, subject, nil, *extra_args)
|
||||
else
|
||||
@block.call(action, subject.class, subject, *extra_args)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -11,15 +11,19 @@ module CanCan
|
||||
# load_and_authorize_resource
|
||||
# end
|
||||
#
|
||||
def load_and_authorize_resource(options = {})
|
||||
ResourceAuthorization.add_before_filter(self, :load_and_authorize_resource, options)
|
||||
def load_and_authorize_resource(*args)
|
||||
cancan_resource_class.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"
|
||||
# action.
|
||||
# Article.new(params[:article]) depending upon the action. The index action will
|
||||
# automatically set @articles to Article.accessible_by(current_ability).
|
||||
#
|
||||
# If a conditions hash is used in the Ability, the +new+ and +create+ actions will set
|
||||
# the initial attributes based on these conditions. This way these actions will satisfy
|
||||
# the ability restrictions.
|
||||
#
|
||||
# Call this method directly on the controller class.
|
||||
#
|
||||
@@ -41,6 +45,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,27 +68,37 @@ 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 or method.
|
||||
#
|
||||
# load_resource :nested => :author
|
||||
# [:+through_association+]
|
||||
# The name of the association to fetch the child records through the parent resource. This is normally not needed
|
||||
# because it defaults to the pluralized resource name.
|
||||
#
|
||||
# Deep nesting can be defined in an array.
|
||||
# [:+shallow+]
|
||||
# Pass +true+ to allow this resource to be loaded directly when parent is +nil+. Defaults to +false+.
|
||||
#
|
||||
# load_resource :nested => [:publisher, :author]
|
||||
# [:+singleton+]
|
||||
# Pass +true+ if this is a singleton resource through a +has_one+ association.
|
||||
#
|
||||
# [:+name+]
|
||||
# The name of the resource if it cannot be determined from controller (string or symbol).
|
||||
# [:+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 :name => :article
|
||||
#
|
||||
# [:+resource+]
|
||||
# [:+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]
|
||||
#
|
||||
@@ -81,11 +109,11 @@ module CanCan
|
||||
#
|
||||
# load_resource :new => :build
|
||||
#
|
||||
def load_resource(options = {})
|
||||
ResourceAuthorization.add_before_filter(self, :load_resource, options)
|
||||
def load_resource(*args)
|
||||
cancan_resource_class.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.
|
||||
@@ -98,6 +126,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:
|
||||
@@ -107,17 +148,66 @@ module CanCan
|
||||
# [:+except+]
|
||||
# Does not apply before filter to given actions.
|
||||
#
|
||||
# [:+name+]
|
||||
# The name of the resource if it cannot be determined from controller (string or symbol).
|
||||
# [:+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 :name => :article
|
||||
# [:+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.
|
||||
#
|
||||
# [:+resource+]
|
||||
# The class to use for the model (string or constant). Alternatively pass a symbol
|
||||
# to represent a resource which does not have a class.
|
||||
# [:+instance_name+]
|
||||
# The name of the instance variable for this resource.
|
||||
#
|
||||
def authorize_resource(options = {})
|
||||
ResourceAuthorization.add_before_filter(self, :authorize_resource, options)
|
||||
# [:+through+]
|
||||
# Authorize conditions on this parent resource when instance isn't available.
|
||||
#
|
||||
def authorize_resource(*args)
|
||||
cancan_resource_class.add_before_filter(self, :authorize_resource, *args)
|
||||
end
|
||||
|
||||
# Add this to a controller to ensure it performs authorization through +authorized+! or +authorize_resource+ call.
|
||||
# If neither of these authorization methods are called, a CanCan::AuthorizationNotPerformed exception will be raised.
|
||||
# This is normally added to the ApplicationController to ensure all controller actions do authorization.
|
||||
#
|
||||
# class ApplicationController < ActionController::Base
|
||||
# check_authorization
|
||||
# end
|
||||
#
|
||||
# Any arguments are passed to the +after_filter+ it triggers.
|
||||
#
|
||||
# See skip_authorization_check to bypass this check on specific controller actions.
|
||||
def check_authorization(*args)
|
||||
self.after_filter(*args) do |controller|
|
||||
unless controller.instance_variable_defined?(:@_authorized)
|
||||
raise AuthorizationNotPerformed, "This action failed the check_authorization because it does not authorize_resource. Add skip_authorization_check to bypass this check."
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Call this in the class of a controller to skip the check_authorization behavior on the actions.
|
||||
#
|
||||
# class HomeController < ApplicationController
|
||||
# skip_authorization_check :only => :index
|
||||
# end
|
||||
#
|
||||
# Any arguments are passed to the +before_filter+ it triggers.
|
||||
def skip_authorization_check(*args)
|
||||
self.before_filter(*args) do |controller|
|
||||
controller.instance_variable_set(:@_authorized, true)
|
||||
end
|
||||
end
|
||||
|
||||
def skip_authorization(*args)
|
||||
raise ImplementationRemoved, "The CanCan skip_authorization method has been renamed to skip_authorization_check. Please update your code."
|
||||
end
|
||||
|
||||
def cancan_resource_class
|
||||
if ancestors.map(&:to_s).include? "InheritedResources::Actions"
|
||||
InheritedResource
|
||||
else
|
||||
ControllerResource
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -139,6 +229,16 @@ module CanCan
|
||||
#
|
||||
# authorize! :read, @article, :message => "Not authorized to read #{@article.name}"
|
||||
#
|
||||
# You can also use I18n to customize the message. Action aliases defined in Ability work here.
|
||||
#
|
||||
# en:
|
||||
# unauthorized:
|
||||
# manage:
|
||||
# all: "Not authorized to %{action} %{subject}."
|
||||
# user: "Not allowed to manage other user accounts."
|
||||
# update:
|
||||
# project: "Not allowed to update this project."
|
||||
#
|
||||
# You can rescue from the exception in the controller to customize how unauthorized
|
||||
# access is displayed to the user.
|
||||
#
|
||||
@@ -153,12 +253,9 @@ module CanCan
|
||||
#
|
||||
# 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)
|
||||
def authorize!(*args)
|
||||
@_authorized = true
|
||||
current_ability.authorize!(*args)
|
||||
end
|
||||
|
||||
def unauthorized!(message = nil)
|
||||
@@ -191,6 +288,13 @@ module CanCan
|
||||
# <%= link_to "New Project", new_project_path %>
|
||||
# <% end %>
|
||||
#
|
||||
# If it's a nested resource, you can pass the parent instance in a hash. This way it will
|
||||
# check conditions which reach through that association.
|
||||
#
|
||||
# <% if can? :create, @category => Project %>
|
||||
# <%= link_to "New Project", new_project_path %>
|
||||
# <% end %>
|
||||
#
|
||||
# This simply calls "can?" on the current_ability. See Ability#can?.
|
||||
def can?(*args)
|
||||
current_ability.can?(*args)
|
||||
|
||||
@@ -1,54 +1,187 @@
|
||||
module CanCan
|
||||
# Used internally to load and authorize a given controller resource.
|
||||
# This manages finding or building an instance of the resource. If a
|
||||
# parent is given it will go through the association.
|
||||
# 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, options = {})
|
||||
raise ImplementationRemoved, "The :class option has been renamed to :resource for specifying the class in CanCan." if options.has_key? :class
|
||||
@controller = controller
|
||||
@name = name
|
||||
@parent = parent
|
||||
@options = options
|
||||
end
|
||||
|
||||
# Returns the class used for this resource. This can be overriden by the :resource option.
|
||||
# Sometimes one will use a symbol as the resource if a class does not exist for it. In that
|
||||
# case "find" and "build" should not be called on it.
|
||||
def model_class
|
||||
resource_class = @options[:resource]
|
||||
if resource_class.nil?
|
||||
@name.to_s.camelize.constantize
|
||||
elsif resource_class.kind_of? String
|
||||
resource_class.constantize
|
||||
else
|
||||
resource_class # could be a symbol
|
||||
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|
|
||||
controller.class.cancan_resource_class.new(controller, resource_name, options.except(:only, :except)).send(method)
|
||||
end
|
||||
end
|
||||
|
||||
def find(id)
|
||||
self.model_instance ||= base.find(id)
|
||||
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
|
||||
|
||||
# Build a new instance of this resource. If it is a class we just call "new" otherwise
|
||||
# it's an associaiton and "build" is used.
|
||||
def build(attributes)
|
||||
self.model_instance ||= (base.kind_of?(Class) ? base.new(attributes) : base.build(attributes))
|
||||
def load_and_authorize_resource
|
||||
load_resource
|
||||
authorize_resource
|
||||
end
|
||||
|
||||
def model_instance
|
||||
@controller.instance_variable_get("@#{@name}")
|
||||
def load_resource
|
||||
if parent? || member_action?
|
||||
self.resource_instance ||= load_resource_instance
|
||||
elsif load_collection?
|
||||
self.collection_instance ||= load_collection
|
||||
end
|
||||
end
|
||||
|
||||
def model_instance=(instance)
|
||||
@controller.instance_variable_set("@#{@name}", instance)
|
||||
def authorize_resource
|
||||
@controller.authorize!(authorization_action, resource_instance || resource_class_with_parent)
|
||||
end
|
||||
|
||||
private
|
||||
def parent?
|
||||
@options.has_key?(:parent) ? @options[:parent] : @name && @name != name_from_controller.to_sym
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
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 load_collection?
|
||||
resource_base.respond_to?(:accessible_by) &&
|
||||
!current_ability.has_block?(authorization_action, resource_class)
|
||||
end
|
||||
|
||||
def load_collection
|
||||
resource_base.accessible_by(current_ability)
|
||||
end
|
||||
|
||||
def build_resource
|
||||
if @options[:singleton] && resource_base.respond_to?("build_#{name}")
|
||||
resource = resource_base.send("build_#{name}")
|
||||
else
|
||||
resource = resource_base.send("new")
|
||||
end
|
||||
initial_attributes.each do |name, value|
|
||||
resource.send("#{name}=", value)
|
||||
end
|
||||
resource.attributes = @params[name] if @params[name]
|
||||
resource
|
||||
end
|
||||
|
||||
def initial_attributes
|
||||
current_ability.attributes_for(@params[:action].to_sym, resource_class)
|
||||
end
|
||||
|
||||
def find_resource
|
||||
if @options[:singleton] && resource_base.respond_to?(name)
|
||||
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_class_with_parent
|
||||
parent_resource ? {parent_resource => resource_class} : resource_class
|
||||
end
|
||||
|
||||
def resource_instance=(instance)
|
||||
@controller.instance_variable_set("@#{instance_name}", instance)
|
||||
end
|
||||
|
||||
def resource_instance
|
||||
@controller.instance_variable_get("@#{instance_name}")
|
||||
end
|
||||
|
||||
def collection_instance=(instance)
|
||||
@controller.instance_variable_set("@#{instance_name.to_s.pluralize}", instance)
|
||||
end
|
||||
|
||||
def collection_instance
|
||||
@controller.instance_variable_get("@#{instance_name.to_s.pluralize}")
|
||||
end
|
||||
|
||||
# The object that methods (such as "find", "new" or "build") are called on.
|
||||
# If there is a parent it will be the association, otherwise it will be the model's class.
|
||||
def base
|
||||
@parent ? @parent.model_instance.send(@name.to_s.pluralize) : model_class
|
||||
# If the :through option is passed it will go through an association on that instance.
|
||||
# If the :shallow option is passed it will use the resource_class if there's no parent
|
||||
# If the :singleton option is passed it won't use the association because it needs to be handled later.
|
||||
def resource_base
|
||||
if @options[:through]
|
||||
if parent_resource
|
||||
@options[:singleton] ? parent_resource : parent_resource.send(@options[:through_association] || name.to_s.pluralize)
|
||||
elsif @options[:shallow]
|
||||
resource_class
|
||||
else
|
||||
raise AccessDenied # maybe this should be a record not found error instead?
|
||||
end
|
||||
else
|
||||
resource_class
|
||||
end
|
||||
end
|
||||
|
||||
# The object to load this resource through.
|
||||
def parent_resource
|
||||
@options[:through] && [@options[:through]].flatten.map { |i| fetch_parent(i) }.compact.first
|
||||
end
|
||||
|
||||
def fetch_parent(name)
|
||||
if @controller.instance_variable_defined? "@#{name}"
|
||||
@controller.instance_variable_get("@#{name}")
|
||||
elsif @controller.respond_to? name
|
||||
@controller.send(name)
|
||||
end
|
||||
end
|
||||
|
||||
def current_ability
|
||||
@controller.send(:current_ability)
|
||||
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
|
||||
|
||||
@@ -5,6 +5,9 @@ module CanCan
|
||||
# Raised when removed code is called, an alternative solution is provided in message.
|
||||
class ImplementationRemoved < Error; end
|
||||
|
||||
# Raised when using check_authorization without calling authorized!
|
||||
class AuthorizationNotPerformed < 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.
|
||||
@@ -24,7 +27,8 @@ module CanCan
|
||||
# exception.default_message = "Default error message"
|
||||
# exception.message # => "Default error message"
|
||||
#
|
||||
# See ControllerAdditions#authorized! for more information on rescuing from this exception.
|
||||
# See ControllerAdditions#authorized! for more information on rescuing from this exception
|
||||
# and customizing the message using I18n.
|
||||
class AccessDenied < Error
|
||||
attr_reader :action, :subject
|
||||
attr_writer :default_message
|
||||
|
||||
18
lib/cancan/inherited_resource.rb
Normal file
18
lib/cancan/inherited_resource.rb
Normal file
@@ -0,0 +1,18 @@
|
||||
module CanCan
|
||||
# For use with Inherited Resources
|
||||
class InheritedResource < ControllerResource # :nodoc:
|
||||
def load_resource_instance
|
||||
if parent?
|
||||
@controller.send :parent
|
||||
elsif new_actions.include? @params[:action].to_sym
|
||||
@controller.send :build_resource
|
||||
else
|
||||
@controller.send :resource
|
||||
end
|
||||
end
|
||||
|
||||
def resource_base
|
||||
@controller.send :end_of_association_chain
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,4 +1,5 @@
|
||||
Spec::Matchers.define :be_able_to do |*args|
|
||||
RSpec = Spec unless defined? RSpec # for RSpec 1 compatability
|
||||
RSpec::Matchers.define :be_able_to do |*args|
|
||||
match do |ability|
|
||||
ability.can?(*args)
|
||||
end
|
||||
|
||||
97
lib/cancan/query.rb
Normal file
97
lib/cancan/query.rb
Normal 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
|
||||
@@ -1,70 +0,0 @@
|
||||
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 ResourceAuthorization # :nodoc:
|
||||
def self.add_before_filter(controller_class, method, options = {})
|
||||
controller_class.before_filter(options.slice(:only, :except)) do |controller|
|
||||
ResourceAuthorization.new(controller, controller.params, options.except(:only, :except)).send(method)
|
||||
end
|
||||
end
|
||||
|
||||
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
|
||||
if collection_actions.include? @params[:action].to_sym
|
||||
parent_resource
|
||||
else
|
||||
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.authorize!(@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
|
||||
@options[:name] || @params[:controller].sub("Controller", "").underscore.split('/').last.singularize
|
||||
end
|
||||
|
||||
def collection_actions
|
||||
[:index] + [@options[:collection]].flatten
|
||||
end
|
||||
|
||||
def new_actions
|
||||
[:new, :create] + [@options[:new]].flatten
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -16,50 +16,97 @@ 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 class with object if :all objects are accepted" do
|
||||
@ability.can :preview, :all do |object_class, object|
|
||||
[object_class, object]
|
||||
it "should pass nil to a block when no instance is passed" do
|
||||
@ability.can :read, Symbol do |sym|
|
||||
sym.should be_nil
|
||||
true
|
||||
end
|
||||
@ability.can?(:preview, 123).should == [Fixnum, 123]
|
||||
@ability.can?(:read, Symbol).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]
|
||||
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?(:preview, Hash).should == [Hash, nil]
|
||||
@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 action and object for global manage actions" do
|
||||
@ability.can :manage, Array do |action, object|
|
||||
[action, object]
|
||||
it "should not pass class with object if :all objects are accepted" do
|
||||
@ability.can :preview, :all do |object|
|
||||
object.should == 123
|
||||
@block_called = true
|
||||
end
|
||||
@ability.can?(:stuff, [1, 2]).should == [:stuff, [1, 2]]
|
||||
@ability.can?(:stuff, Array).should == [:stuff, nil]
|
||||
@ability.can?(:preview, 123)
|
||||
@block_called.should be_true
|
||||
end
|
||||
|
||||
it "should not call block when only class is passed, only return true" do
|
||||
@block_called = false
|
||||
@ability.can :preview, :all do |object|
|
||||
@block_called = true
|
||||
end
|
||||
@ability.can?(:preview, Hash).should be_true
|
||||
@block_called.should be_false
|
||||
end
|
||||
|
||||
it "should pass only object for global manage actions" do
|
||||
@ability.can :manage, String do |object|
|
||||
object.should == "foo"
|
||||
@block_called = true
|
||||
end
|
||||
@ability.can?(:stuff, "foo").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) { :modify_called }
|
||||
@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 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]
|
||||
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 always call block with arguments when passing no arguments to can" do
|
||||
@ability.can do |action, object_class, object|
|
||||
action.should == :foo
|
||||
object_class.should == 123.class
|
||||
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 pass nil to object when comparing class with can check" do
|
||||
@ability.can do |action, object_class, object|
|
||||
action.should == :foo
|
||||
object_class.should == Hash
|
||||
object.should be_nil
|
||||
@block_called = true
|
||||
end
|
||||
@ability.can?(:foo, Hash)
|
||||
@block_called.should be_true
|
||||
end
|
||||
|
||||
it "should automatically alias index and show into read calls" do
|
||||
@@ -69,10 +116,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
|
||||
@@ -91,9 +138,9 @@ describe CanCan::Ability do
|
||||
end
|
||||
|
||||
it "should be able to specify multiple classes and match any" do
|
||||
@ability.can :update, [String, Array]
|
||||
@ability.can :update, [String, Range]
|
||||
@ability.can?(:update, "foo").should be_true
|
||||
@ability.can?(:update, []).should be_true
|
||||
@ability.can?(:update, 1..3).should be_true
|
||||
@ability.can?(:update, 123).should be_false
|
||||
end
|
||||
|
||||
@@ -104,6 +151,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
|
||||
@@ -111,13 +165,35 @@ describe CanCan::Ability do
|
||||
@ability.can?(:read, 123).should be_false
|
||||
end
|
||||
|
||||
it "should support block on 'cannot' method" do
|
||||
it "should pass to previous can definition, if block returns false or nil" do
|
||||
@ability.can :read, :all
|
||||
@ability.cannot :read, Integer do |int|
|
||||
int > 5
|
||||
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
|
||||
|
||||
@@ -142,62 +218,170 @@ describe CanCan::Ability do
|
||||
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
|
||||
@ability.can :read, Range, :begin => 1, :end => 3
|
||||
@ability.can?(:read, 1..3).should be_true
|
||||
@ability.can?(:read, 1..4).should be_false
|
||||
@ability.can?(:read, Range).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
|
||||
@ability.can :read, Range, :begin => [1, 3, 5]
|
||||
@ability.can?(:read, 1..3).should be_true
|
||||
@ability.can?(:read, 2..4).should be_false
|
||||
@ability.can?(:read, 3..5).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
|
||||
@ability.can :read, Range, :begin => 1..3
|
||||
@ability.can?(:read, 1..10).should be_true
|
||||
@ability.can?(:read, 3..30).should be_true
|
||||
@ability.can?(:read, 4..40).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
|
||||
@ability.can :read, Range, :begin => { :to_i => 5 }
|
||||
@ability.can?(:read, 5..7).should be_true
|
||||
@ability.can?(:read, 6..8).should be_false
|
||||
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
|
||||
it "should match any element passed in to nesting if it's an array (for has_many associations)" do
|
||||
@ability.can :read, Range, :to_a => { :to_i => 3 }
|
||||
@ability.can?(:read, 1..5).should be_true
|
||||
@ability.can?(:read, 4..6).should be_false
|
||||
end
|
||||
|
||||
it "should return conditions for a given ability" do
|
||||
@ability.can :read, Array, :first => 1, :last => 3
|
||||
@ability.conditions(:show, Array).should == {:first => 1, :last => 3}
|
||||
it "should not stop at cannot definition when comparing class" do
|
||||
@ability.can :read, Range
|
||||
@ability.cannot :read, Range, :begin => 1
|
||||
@ability.can?(:read, 2..5).should be_true
|
||||
@ability.can?(:read, 1..5).should be_false
|
||||
@ability.can?(:read, Range).should be_true
|
||||
end
|
||||
|
||||
it "should raise an exception when a block is used on condition" do
|
||||
@ability.can :read, Array do |a|
|
||||
it "should stop at cannot definition when no hash is present" do
|
||||
@ability.can :read, :all
|
||||
@ability.cannot :read, Range
|
||||
@ability.can?(:read, 1..5).should be_false
|
||||
@ability.can?(:read, Range).should be_false
|
||||
end
|
||||
|
||||
it "should allow to check ability for Module" do
|
||||
module B; end
|
||||
class A; include B; end
|
||||
@ability.can :read, B
|
||||
@ability.can?(:read, A).should be_true
|
||||
@ability.can?(:read, A.new).should be_true
|
||||
end
|
||||
|
||||
it "should pass nil to a block for ability on Module when no instance is passed" do
|
||||
module B; end
|
||||
class A; include B; end
|
||||
@ability.can :read, B do |sym|
|
||||
sym.should be_nil
|
||||
true
|
||||
end
|
||||
lambda { @ability.conditions(:show, Array) }.should raise_error(CanCan::Error, "Cannot determine ability conditions from block for :show Array")
|
||||
@ability.can?(:read, B).should be_true
|
||||
@ability.can?(:read, A).should be_true
|
||||
end
|
||||
|
||||
it "should return an empty hash for conditions when there are no conditions" do
|
||||
@ability.can :read, Array
|
||||
@ability.conditions(:show, Array).should == {}
|
||||
it "passing a hash of subjects should check permissions through association" do
|
||||
@ability.can :read, Range, :string => {:length => 3}
|
||||
@ability.can?(:read, "foo" => Range).should be_true
|
||||
@ability.can?(:read, "foobar" => Range).should be_false
|
||||
@ability.can?(:read, 123 => Range).should be_true
|
||||
end
|
||||
|
||||
it "should return false when performed on an action which isn't defined" do
|
||||
@ability.conditions(:foo, Array).should == false
|
||||
it "should have initial attributes based on hash conditions of 'new' action" do
|
||||
@ability.can :manage, Range, :foo => "foo", :hash => {:skip => "hashes"}
|
||||
@ability.can :create, Range, :bar => 123, :array => %w[skip arrays]
|
||||
@ability.can :new, Range, :baz => "baz", :range => 1..3
|
||||
@ability.cannot :new, Range, :ignore => "me"
|
||||
@ability.attributes_for(:new, Range).should == {:foo => "foo", :bar => 123, :baz => "baz"}
|
||||
end
|
||||
|
||||
it "should has eated cheezburger" do
|
||||
lambda {
|
||||
@ability.can? :has, :cheezburger
|
||||
}.should raise_exception(CanCan::Error, "Nom nom nom. I eated it.")
|
||||
it "should raise access denied exception if ability us unauthorized to perform a certain action" do
|
||||
begin
|
||||
@ability.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
|
||||
@ability.can :read, :foo
|
||||
lambda { @ability.authorize!(:read, :foo) }.should_not raise_error
|
||||
end
|
||||
|
||||
it "should know when block is used in conditions" do
|
||||
@ability.can :read, :foo
|
||||
@ability.should_not have_block(:read, :foo)
|
||||
@ability.can :read, :foo do |foo|
|
||||
false
|
||||
end
|
||||
@ability.should have_block(:read, :foo)
|
||||
end
|
||||
|
||||
it "should know when raw sql is used in conditions" do
|
||||
@ability.can :read, :foo
|
||||
@ability.should_not have_raw_sql(:read, :foo)
|
||||
@ability.can :read, :foo, 'false'
|
||||
@ability.should have_raw_sql(:read, :foo)
|
||||
end
|
||||
|
||||
it "should raise access denied exception with default message if not specified" do
|
||||
begin
|
||||
@ability.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
|
||||
|
||||
describe "unauthorized message" do
|
||||
after(:each) do
|
||||
I18n.backend = nil
|
||||
end
|
||||
|
||||
it "should use action/subject in i18n" do
|
||||
I18n.backend.store_translations :en, :unauthorized => {:update => {:array => "foo"}}
|
||||
@ability.unauthorized_message(:update, Array).should == "foo"
|
||||
@ability.unauthorized_message(:update, [1, 2, 3]).should == "foo"
|
||||
@ability.unauthorized_message(:update, :missing).should be_nil
|
||||
end
|
||||
|
||||
it "should use symbol as subject directly" do
|
||||
I18n.backend.store_translations :en, :unauthorized => {:has => {:cheezburger => "Nom nom nom. I eated it."}}
|
||||
@ability.unauthorized_message(:has, :cheezburger).should == "Nom nom nom. I eated it."
|
||||
end
|
||||
|
||||
it "should fall back to 'manage' and 'all'" do
|
||||
I18n.backend.store_translations :en, :unauthorized => {
|
||||
:manage => {:all => "manage all", :array => "manage array"},
|
||||
:update => {:all => "update all", :array => "update array"}
|
||||
}
|
||||
@ability.unauthorized_message(:update, Array).should == "update array"
|
||||
@ability.unauthorized_message(:update, Hash).should == "update all"
|
||||
@ability.unauthorized_message(:foo, Array).should == "manage array"
|
||||
@ability.unauthorized_message(:foo, Hash).should == "manage all"
|
||||
end
|
||||
|
||||
it "should follow aliased actions" do
|
||||
I18n.backend.store_translations :en, :unauthorized => {:modify => {:array => "modify array"}}
|
||||
@ability.alias_action :update, :to => :modify
|
||||
@ability.unauthorized_message(:update, Array).should == "modify array"
|
||||
@ability.unauthorized_message(:edit, Array).should == "modify array"
|
||||
end
|
||||
|
||||
it "should have variables for action and subject" do
|
||||
I18n.backend.store_translations :en, :unauthorized => {:manage => {:all => "%{action} %{subject}"}} # old syntax for now in case testing with old I18n
|
||||
@ability.unauthorized_message(:update, Array).should == "update array"
|
||||
@ability.unauthorized_message(:edit, 1..3).should == "edit range"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -2,20 +2,22 @@ require "spec_helper"
|
||||
|
||||
describe CanCan::ActiveRecordAdditions do
|
||||
before(:each) do
|
||||
@model_class = Class.new
|
||||
@model_class = Class.new(Project)
|
||||
stub(@model_class).scoped { :scoped_stub }
|
||||
@model_class.send(:include, CanCan::ActiveRecordAdditions)
|
||||
@ability = Object.new
|
||||
@ability.extend(CanCan::Ability)
|
||||
end
|
||||
|
||||
it "should call where(:id => nil) when no ability is defined so no records are found" do
|
||||
stub(@model_class).where(:id => nil).stub!.joins(nil) { :no_where }
|
||||
@model_class.accessible_by(@ability, :read).should == :no_where
|
||||
it "should call where('true=false') when no ability is defined so no records are found" do
|
||||
stub(@model_class).joins { true } # just so it responds to .joins as well
|
||||
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).joins { true } # just so it responds to .joins as well
|
||||
stub(@model_class).where(:foos => { :bar => 1 }).stub!.joins([:foo]) { :found_records }
|
||||
@model_class.accessible_by(@ability, :read).should == :found_records
|
||||
end
|
||||
@@ -25,4 +27,49 @@ describe CanCan::ActiveRecordAdditions do
|
||||
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
|
||||
|
||||
it "should allow to define sql conditions by not hash" do
|
||||
@ability.can :read, @model_class, :foo => 1
|
||||
@ability.can :read, @model_class, ['bar = ?', 1]
|
||||
stub(@model_class).scoped( :conditions => '(bar = 1) OR (foo=1)', :joins => nil ) { :found_records }
|
||||
stub(@model_class).scoped{|*args| args.inspect}
|
||||
@model_class.accessible_by(@ability).should == :found_records
|
||||
end
|
||||
|
||||
it "should not allow to fetch records when ability with just block present" do
|
||||
@ability.can :read, @model_class do false end
|
||||
lambda {
|
||||
@model_class.accessible_by(@ability)
|
||||
}.should raise_error(CanCan::Error)
|
||||
end
|
||||
|
||||
it "should not allow to check ability on object when nonhash sql ability definition without block present" do
|
||||
@ability.can :read, @model_class, ['bar = ?', 1]
|
||||
lambda {
|
||||
@ability.can? :read, @model_class.new
|
||||
}.should raise_error(CanCan::Error)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
require "spec_helper"
|
||||
|
||||
# Most of CanDefinition functionality is tested in Ability specs
|
||||
describe CanCan::CanDefinition do
|
||||
before(:each) do
|
||||
@conditions = {}
|
||||
@@ -7,38 +8,50 @@ describe CanCan::CanDefinition do
|
||||
end
|
||||
|
||||
it "should return no association joins if none exist" do
|
||||
@can.association_joins.should be_nil
|
||||
@can.associations_hash.should == {}
|
||||
end
|
||||
|
||||
it "should return no association for joins if just attributes" do
|
||||
@conditions[:foo] = :bar
|
||||
@can.association_joins.should be_nil
|
||||
@can.associations_hash.should == {}
|
||||
end
|
||||
|
||||
it "should return single association for joins" do
|
||||
@conditions[:foo] = {:bar => 1}
|
||||
@can.association_joins.should == [:foo]
|
||||
@can.associations_hash.should == {:foo => {}}
|
||||
end
|
||||
|
||||
it "should return multiple associations for joins" do
|
||||
@conditions[:foo] = {:bar => 1}
|
||||
@conditions[:test] = {1 => 2}
|
||||
@can.association_joins.map(&:to_s).sort.should == [:foo, :test].map(&:to_s).sort
|
||||
@can.associations_hash.should == {:foo => {}, :test => {}}
|
||||
end
|
||||
|
||||
it "should return nested associations for joins" do
|
||||
@conditions[:foo] = {:bar => {1 => 2}}
|
||||
@can.association_joins.should == [{:foo => [:bar]}]
|
||||
@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.conditions(:tableize => true).should == { :foos => { :bar => 1}, :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.association_joins.should be_nil
|
||||
can.associations_hash.should == {}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -14,32 +14,10 @@ describe CanCan::ControllerAdditions 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
|
||||
it "authorize! should assign @_authorized instance variable and pass args to current ability" do
|
||||
mock(@controller.current_ability).authorize!(:foo, :bar)
|
||||
@controller.authorize!(:foo, :bar)
|
||||
@controller.instance_variable_get(:@_authorized).should be_true
|
||||
end
|
||||
|
||||
it "should have a current_ability method which generates an ability for the current user" do
|
||||
@@ -52,21 +30,57 @@ describe CanCan::ControllerAdditions do
|
||||
@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
|
||||
|
||||
it "skip_authorization_check should set up a before filter which sets @_authorized to true" do
|
||||
mock(@controller_class).before_filter(:filter_options) { |options, block| block.call(@controller) }
|
||||
@controller_class.skip_authorization_check(:filter_options)
|
||||
@controller.instance_variable_get(:@_authorized).should be_true
|
||||
end
|
||||
|
||||
it "check_authorization should trigger AuthorizationNotPerformed in after filter" do
|
||||
mock(@controller_class).after_filter(:some_options) { |options, block| block.call(@controller) }
|
||||
lambda {
|
||||
@controller_class.check_authorization(:some_options)
|
||||
}.should raise_error(CanCan::AuthorizationNotPerformed)
|
||||
end
|
||||
|
||||
it "check_authorization should not raise error when @_authorized is set" do
|
||||
@controller.instance_variable_set(:@_authorized, true)
|
||||
mock(@controller_class).after_filter(:some_options) { |options, block| block.call(@controller) }
|
||||
lambda {
|
||||
@controller_class.check_authorization(:some_options)
|
||||
}.should_not raise_error(CanCan::AuthorizationNotPerformed)
|
||||
end
|
||||
|
||||
it "cancan_resource_class should be ControllerResource by default" do
|
||||
@controller.class.cancan_resource_class.should == CanCan::ControllerResource
|
||||
end
|
||||
|
||||
it "cancan_resource_class should be InheritedResource when class includes InheritedResources::Actions" do
|
||||
stub(@controller.class).ancestors { ["InheritedResources::Actions"] }
|
||||
@controller.class.cancan_resource_class.should == CanCan::InheritedResource
|
||||
end
|
||||
end
|
||||
|
||||
@@ -2,58 +2,325 @@ require "spec_helper"
|
||||
|
||||
describe CanCan::ControllerResource do
|
||||
before(:each) do
|
||||
@controller = Object.new
|
||||
@params = HashWithIndifferentAccess.new(:controller => "projects")
|
||||
@controller = Object.new # simple stub for now
|
||||
@ability = Ability.new(nil)
|
||||
stub(@controller).params { @params }
|
||||
stub(@controller).current_ability { @ability }
|
||||
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
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
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
|
||||
it "should not load resource into an instance variable if already set" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
@controller.instance_variable_set(:@project, :some_project)
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
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
|
||||
it "should properly load resource for namespaced controller" do
|
||||
project = Project.create!
|
||||
@params.merge!(:controller => "admin/projects", :action => "show", :id => project.id)
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
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
|
||||
it "should properly load resource for namespaced controller when using '::' for namespace" do
|
||||
project = Project.create!
|
||||
@params.merge!(:controller => "Admin::ProjectsController", :action => "show", :id => project.id)
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
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
|
||||
it "should build a new resource with hash if params[:id] is not specified" do
|
||||
@params.merge!(:action => "create", :project => {:name => "foobar"})
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||
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
|
||||
it "should build a new resource with attributes from current ability" do
|
||||
@params.merge!(:action => "new")
|
||||
@ability.can(:create, Project, :name => "from conditions")
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).name.should == "from conditions"
|
||||
end
|
||||
|
||||
it "should use the model class option if provided" do
|
||||
stub(Person).find(123) { :some_resource }
|
||||
CanCan::ControllerResource.new(@controller, :ability, nil, :resource => Person).find(123)
|
||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||
it "should override initial attributes with params" do
|
||||
@params.merge!(:action => "new", :project => {:name => "from params"})
|
||||
@ability.can(:create, Project, :name => "from conditions")
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).name.should == "from params"
|
||||
end
|
||||
|
||||
it "should convert string to constant for resource" do
|
||||
CanCan::ControllerResource.new(@controller, :ability, nil, :resource => "Person").model_class.should == Person
|
||||
it "should build a collection when on index action when class responds to accessible_by" do
|
||||
stub(Project).accessible_by(@ability) { :found_projects }
|
||||
@params[:action] = "index"
|
||||
resource = CanCan::ControllerResource.new(@controller, :project)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
@controller.instance_variable_get(:@projects).should == :found_projects
|
||||
end
|
||||
|
||||
it "should raise an exception when specifying :class option since it is no longer used" do
|
||||
it "should not build a collection when on index action when class does not respond to accessible_by" do
|
||||
@params[:action] = "index"
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
@controller.instance_variable_defined?(:@projects).should be_false
|
||||
end
|
||||
|
||||
it "should not use accessible_by when defining abilities through a block" do
|
||||
stub(Project).accessible_by(@ability) { :found_projects }
|
||||
@params[:action] = "index"
|
||||
@ability.can(:read, Project) { |p| false }
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
@controller.instance_variable_defined?(:@projects).should be_false
|
||||
end
|
||||
|
||||
it "should perform authorization using controller action and loaded model" do
|
||||
@params[:action] = "show"
|
||||
@controller.instance_variable_set(:@project, :some_project)
|
||||
stub(@controller).authorize!(:show, :some_project) { 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, Project) { 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(:@project).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(Project).new { :some_project }
|
||||
resource = CanCan::ControllerResource.new(@controller, :new => :build)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
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(:@project).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, :category)
|
||||
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, :project)
|
||||
resource.should_not be_parent
|
||||
end
|
||||
|
||||
it "should be parent if specified in options" do
|
||||
resource = CanCan::ControllerResource.new(@controller, :project, {:parent => true})
|
||||
resource.should be_parent
|
||||
end
|
||||
|
||||
it "should not be parent if specified in options" do
|
||||
resource = CanCan::ControllerResource.new(@controller, :category, {:parent => false})
|
||||
resource.should_not be_parent
|
||||
end
|
||||
|
||||
it "should load parent resource through proper id parameter" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "index", :project_id => project.id)
|
||||
resource = CanCan::ControllerResource.new(@controller, :project, :parent => true)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "should load resource through the association of another parent resource using instance variable" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
category = Object.new
|
||||
@controller.instance_variable_set(:@category, category)
|
||||
stub(category).projects.stub!.find(123) { :some_project }
|
||||
resource = CanCan::ControllerResource.new(@controller, :through => :category)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "should load resource through the custom association name" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
category = Object.new
|
||||
@controller.instance_variable_set(:@category, category)
|
||||
stub(category).custom_projects.stub!.find(123) { :some_project }
|
||||
resource = CanCan::ControllerResource.new(@controller, :through => :category, :through_association => :custom_projects)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "should load resource through the association of another parent resource using method" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
category = Object.new
|
||||
stub(@controller).category { category }
|
||||
stub(category).projects.stub!.find(123) { :some_project }
|
||||
resource = CanCan::ControllerResource.new(@controller, :through => :category)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "should not load through parent resource if instance isn't loaded when shallow" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
resource = CanCan::ControllerResource.new(@controller, :through => :category, :shallow => true)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "should raise AccessDenied when attempting to load resource through nil" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
resource = CanCan::ControllerResource.new(@controller, :through => :category)
|
||||
lambda {
|
||||
CanCan::ControllerResource.new(@controller, :ability, nil, :class => Person)
|
||||
resource.load_resource
|
||||
}.should raise_error(CanCan::AccessDenied)
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
end
|
||||
|
||||
it "should authorize nested resource through parent association on index action" do
|
||||
@params.merge!(:action => "index")
|
||||
category = Object.new
|
||||
@controller.instance_variable_set(:@category, category)
|
||||
stub(@controller).authorize!(:index, category => Project) { raise CanCan::AccessDenied }
|
||||
resource = CanCan::ControllerResource.new(@controller, :through => :category)
|
||||
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||
end
|
||||
|
||||
it "should load through first matching if multiple are given" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
category = Object.new
|
||||
@controller.instance_variable_set(:@category, category)
|
||||
stub(category).projects.stub!.find(123) { :some_project }
|
||||
resource = CanCan::ControllerResource.new(@controller, :through => [:category, :user])
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "should find record through has_one association with :singleton option" do
|
||||
@params.merge!(:action => "show")
|
||||
category = Object.new
|
||||
@controller.instance_variable_set(:@category, category)
|
||||
stub(category).project { :some_project }
|
||||
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "should build record through has_one association with :singleton option" do
|
||||
@params.merge!(:action => "create", :project => {:name => "foobar"})
|
||||
category = Object.new
|
||||
@controller.instance_variable_set(:@category, category)
|
||||
stub(category).build_project { Project.new }
|
||||
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||
end
|
||||
|
||||
it "should find record through has_one association with :singleton and :shallow options" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true, :shallow => true)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "should build record through has_one association with :singleton and :shallow options" do
|
||||
@params.merge!(:action => "create", :project => {:name => "foobar"})
|
||||
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true, :shallow => true)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||
end
|
||||
|
||||
it "should only authorize :read action on parent resource" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "new", :project_id => project.id)
|
||||
stub(@controller).authorize!(:read, project) { raise CanCan::AccessDenied }
|
||||
resource = CanCan::ControllerResource.new(@controller, :project, :parent => true)
|
||||
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||
end
|
||||
|
||||
it "should load the model using a custom class" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
resource = CanCan::ControllerResource.new(@controller, :class => Project)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "should authorize based on resource name if class is false" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
stub(@controller).authorize!(:show, :project) { 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
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
stub(@controller).authorize!(:show, project) { raise CanCan::AccessDenied }
|
||||
resource = CanCan::ControllerResource.new(@controller, :instance_name => :custom_project)
|
||||
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||
@controller.instance_variable_get(:@custom_project).should == project
|
||||
end
|
||||
|
||||
it "should load resource using custom find_by attribute" do
|
||||
project = Project.create!(:name => "foo")
|
||||
@params.merge!(:action => "show", :id => "foo")
|
||||
resource = CanCan::ControllerResource.new(@controller, :find_by => :name)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
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 => Project)
|
||||
}.should raise_error(CanCan::ImplementationRemoved)
|
||||
end
|
||||
|
||||
it "should raise ImplementationRemoved exception when passing :nested option" do
|
||||
lambda {
|
||||
CanCan::ControllerResource.new(@controller, :nested => :project)
|
||||
}.should raise_error(CanCan::ImplementationRemoved)
|
||||
end
|
||||
end
|
||||
|
||||
40
spec/cancan/inherited_resource_spec.rb
Normal file
40
spec/cancan/inherited_resource_spec.rb
Normal file
@@ -0,0 +1,40 @@
|
||||
require "spec_helper"
|
||||
|
||||
describe CanCan::InheritedResource do
|
||||
before(:each) do
|
||||
@params = HashWithIndifferentAccess.new(:controller => "projects")
|
||||
@controller = Object.new # simple stub for now
|
||||
@ability = Ability.new(nil)
|
||||
stub(@controller).params { @params }
|
||||
stub(@controller).current_ability { @ability }
|
||||
end
|
||||
|
||||
it "show should load resource through @controller.resource" do
|
||||
@params[:action] = "show"
|
||||
stub(@controller).resource { :project_resource }
|
||||
CanCan::InheritedResource.new(@controller).load_resource
|
||||
@controller.instance_variable_get(:@project).should == :project_resource
|
||||
end
|
||||
|
||||
it "new should load through @controller.build_resource" do
|
||||
@params[:action] = "new"
|
||||
stub(@controller).build_resource { :project_resource }
|
||||
CanCan::InheritedResource.new(@controller).load_resource
|
||||
@controller.instance_variable_get(:@project).should == :project_resource
|
||||
end
|
||||
|
||||
it "index should load through @controller.parent when parent" do
|
||||
@params[:action] = "index"
|
||||
stub(@controller).parent { :project_resource }
|
||||
CanCan::InheritedResource.new(@controller, :parent => true).load_resource
|
||||
@controller.instance_variable_get(:@project).should == :project_resource
|
||||
end
|
||||
|
||||
it "index should load through @controller.end_of_association_chain" do
|
||||
@params[:action] = "index"
|
||||
stub(Project).accessible_by(@ability) { :projects }
|
||||
stub(@controller).end_of_association_chain { Project }
|
||||
CanCan::InheritedResource.new(@controller).load_resource
|
||||
@controller.instance_variable_get(:@projects).should == :projects
|
||||
end
|
||||
end
|
||||
107
spec/cancan/query_spec.rb
Normal file
107
spec/cancan/query_spec.rb
Normal 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, Project).conditions.should == "true=false"
|
||||
end
|
||||
|
||||
it "should return hash for single `can` definition" do
|
||||
@ability.can :read, Project, :blocked => false, :user_id => 1
|
||||
@ability.query(:read, Project).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, Project, :blocked => false
|
||||
@ability.can :read, Project, :admin => true
|
||||
@ability.query(:read, Project).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, Project, :blocked => false, :active => true
|
||||
@ability.can :read, Project, :admin => true
|
||||
@ability.query(:read, Project).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, Project, :blocked => false, :active => true
|
||||
@ability.can :read, Project, :admin => true
|
||||
@ability.query(:read, Project).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, Project
|
||||
@ability.query(:read, Project).conditions.should == "true=false"
|
||||
end
|
||||
|
||||
it "should return SQL for single `can` definition in front of default `cannot` condition" do
|
||||
@ability.cannot :read, Project
|
||||
@ability.can :read, Project, :blocked => false, :user_id => 1
|
||||
@ability.query(:read, Project).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, Project
|
||||
@ability.can :read, Project, :blocked => false, :user_id => 1
|
||||
@ability.query(:read, Project).conditions.should == 'true=true'
|
||||
end
|
||||
|
||||
it "should return false condition for single `cannot` definition" do
|
||||
@ability.cannot :read, Project, :blocked => true, :user_id => 1
|
||||
@ability.query(:read, Project).conditions.should == 'true=false'
|
||||
end
|
||||
|
||||
it "should return `false condition` for single `cannot` definition in front of default `cannot` condition" do
|
||||
@ability.cannot :read, Project
|
||||
@ability.cannot :read, Project, :blocked => true, :user_id => 1
|
||||
@ability.query(:read, Project).conditions.should == 'true=false'
|
||||
end
|
||||
|
||||
it "should return `not (sql)` for single `cannot` definition in front of default `can` condition" do
|
||||
@ability.can :read, Project
|
||||
@ability.cannot :read, Project, :blocked => true, :user_id => 1
|
||||
@ability.query(:read, Project).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, Project
|
||||
@ability.can :manage, Project, :id => 1
|
||||
@ability.can :update, Project, :manager_id => 1
|
||||
@ability.cannot :update, Project, :self_managed => true
|
||||
@ability.query(:update, Project).conditions.should == 'not (self_managed=true) AND ((manager_id=1) OR (id=1))'
|
||||
@ability.query(:manage, Project).conditions.should == {:id=>1}
|
||||
@ability.query(:read, Project).conditions.should == 'true=true'
|
||||
end
|
||||
|
||||
it "should have nil joins if no can definitions" do
|
||||
@ability.query(:read, Project).joins.should be_nil
|
||||
end
|
||||
|
||||
it "should have nil joins if no nested hashes specified in conditions" do
|
||||
@ability.can :read, Project, :blocked => false
|
||||
@ability.can :read, Project, :admin => true
|
||||
@ability.query(:read, Project).joins.should be_nil
|
||||
end
|
||||
|
||||
it "should merge separate joins into a single array" do
|
||||
@ability.can :read, Project, :project => { :blocked => false }
|
||||
@ability.can :read, Project, :company => { :admin => true }
|
||||
@ability.query(:read, Project).joins.inspect.should orderlessly_match([:company, :project].inspect)
|
||||
end
|
||||
|
||||
it "should merge same joins into a single array" do
|
||||
@ability.can :read, Project, :project => { :blocked => false }
|
||||
@ability.can :read, Project, :project => { :admin => true }
|
||||
@ability.query(:read, Project).joins.should == [:project]
|
||||
end
|
||||
|
||||
it "should merge complex, nested joins" do
|
||||
@ability.can :read, Project, :project => { :bar => {:test => true} }, :company => { :bar => {:test => true} }
|
||||
@ability.can :read, Project, :project => { :foo => {:bar => true}, :bar => {:zip => :zap} }
|
||||
@ability.query(:read, Project).joins.inspect.should orderlessly_match([{:project => [:bar, :foo]}, {:company => [:bar]}].inspect)
|
||||
end
|
||||
end
|
||||
@@ -1,135 +0,0 @@
|
||||
require "spec_helper"
|
||||
|
||||
describe CanCan::ResourceAuthorization do
|
||||
before(:each) do
|
||||
@controller = Object.new # simple stub for now
|
||||
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 properly load resource for namespaced controller when using '::' for namespace" do
|
||||
stub(Ability).find(123) { :some_resource }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "Admin::AbilitiesController", :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).authorize!(:show, :some_resource) { raise CanCan::AccessDenied }
|
||||
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).authorize!(:show, Ability) { raise CanCan::AccessDenied }
|
||||
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
|
||||
person = Object.new
|
||||
stub(Person).find(456) { person }
|
||||
stub(person).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(:@person).should == person
|
||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
||||
end
|
||||
|
||||
it "should load nested resource for collection action" do
|
||||
person = Object.new
|
||||
stub(Person).find(456) { person }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "index", :person_id => 456}, {:nested => :person})
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@person).should == person
|
||||
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}, {:resource => Person})
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||
end
|
||||
|
||||
it "should use :name option to determine resource name" do
|
||||
stub(Ability).find(123) { :some_resource }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "foo", :action => "show", :id => 123}, {:name => :ability})
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||
end
|
||||
end
|
||||
13
spec/matchers.rb
Normal file
13
spec/matchers.rb
Normal file
@@ -0,0 +1,13 @@
|
||||
RSpec::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
|
||||
2
spec/spec.opts
Normal file
2
spec/spec.opts
Normal file
@@ -0,0 +1,2 @@
|
||||
--color
|
||||
--backtrace
|
||||
@@ -1,14 +1,17 @@
|
||||
require 'rubygems'
|
||||
require 'spec'
|
||||
require 'active_support'
|
||||
require 'active_record'
|
||||
require 'action_controller'
|
||||
require 'action_view'
|
||||
require 'cancan'
|
||||
require 'bundler/setup'
|
||||
Bundler.require(:default)
|
||||
require 'supermodel' # shouldn't Bundler do this already?
|
||||
require 'active_support/all'
|
||||
require 'matchers'
|
||||
require 'cancan/matchers'
|
||||
|
||||
Spec::Runner.configure do |config|
|
||||
RSpec.configure do |config|
|
||||
config.mock_with :rr
|
||||
config.before(:each) do
|
||||
Project.delete_all
|
||||
Category.delete_all
|
||||
end
|
||||
end
|
||||
|
||||
class Ability
|
||||
@@ -18,6 +21,34 @@ class Ability
|
||||
end
|
||||
end
|
||||
|
||||
# this class helps out in testing nesting
|
||||
class Person
|
||||
class Category < SuperModel::Base
|
||||
has_many :projects
|
||||
end
|
||||
|
||||
class Project < SuperModel::Base
|
||||
belongs_to :category
|
||||
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user