Compare commits
91 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0c1646fee | ||
|
|
3f6cecbfcf | ||
|
|
fdd5ad022d | ||
|
|
3639ca90eb | ||
|
|
efa3ff1c0f | ||
|
|
9bee4a8d4b | ||
|
|
eb2826f135 | ||
|
|
a49269175e | ||
|
|
0de43c445b | ||
|
|
f9b181af05 | ||
|
|
80f1ab20fb | ||
|
|
37102fe6f8 | ||
|
|
ba999970b1 | ||
|
|
951d70e057 | ||
|
|
3a07d62782 | ||
|
|
2c2fa306cc | ||
|
|
28a9a0ac07 | ||
|
|
bcf2756ad2 | ||
|
|
c53ed1e497 | ||
|
|
07088a0cdc | ||
|
|
ff5aaf543b | ||
|
|
52435e97d9 | ||
|
|
e3eab13b86 | ||
|
|
79995e4309 | ||
|
|
8722fbc7a5 | ||
|
|
3901cbe499 | ||
|
|
471d54ce01 | ||
|
|
f23bbe04ef | ||
|
|
f1ea21b2a6 | ||
|
|
b2028c8aa7 | ||
|
|
929579f03b | ||
|
|
f9ad4858f5 | ||
|
|
5c4c179c5a | ||
|
|
78cbea5733 | ||
|
|
cff922915e | ||
|
|
2012311c40 | ||
|
|
55c8a5045b | ||
|
|
344832d199 | ||
|
|
52b33589dc | ||
|
|
04522c9bc6 | ||
|
|
120eafeabd | ||
|
|
e49190fc21 | ||
|
|
39bffe91ab | ||
|
|
3885f469d5 | ||
|
|
e2910a74ee | ||
|
|
57327119a8 | ||
|
|
71ceb83ded | ||
|
|
045a850565 | ||
|
|
9a14c706d2 | ||
|
|
12b0bff0b6 | ||
|
|
bc9ecb226d | ||
|
|
15ca8ade3b | ||
|
|
cef6c21232 | ||
|
|
685e926d96 | ||
|
|
bd9480cb51 | ||
|
|
f759ab7e54 | ||
|
|
6ccb4dd684 | ||
|
|
70b5f9a613 | ||
|
|
f9f71d679d | ||
|
|
fc867c9c0d | ||
|
|
ec616ae75b | ||
|
|
f7a494dc51 | ||
|
|
f5dce44697 | ||
|
|
e8d298c223 | ||
|
|
8628aa0038 | ||
|
|
bbb02f7c8f | ||
|
|
cc30e838c0 | ||
|
|
af9e77a79e | ||
|
|
4c5ba09f4c | ||
|
|
f8760b7149 | ||
|
|
2dc2a573f9 | ||
|
|
f9a498d2fc | ||
|
|
5183113d2d | ||
|
|
d315e22e7a | ||
|
|
2d31cbdf60 | ||
|
|
e14e1edec2 | ||
|
|
ebb8e1bf8b | ||
|
|
4339ac6546 | ||
|
|
5e1e6e182b | ||
|
|
9b8e84944c | ||
|
|
37c149182c | ||
|
|
a6959c0ab2 | ||
|
|
2ee6908a2a | ||
|
|
84c590e8c7 | ||
|
|
5ebca1f9bf | ||
|
|
f6aaa581ef | ||
|
|
dbcd93e095 | ||
|
|
d256aeb26e | ||
|
|
25bf479f48 | ||
|
|
ab82dcbc8f | ||
|
|
be74df0548 |
@@ -1,3 +1,61 @@
|
||||
1.6.1 (March 15, 2011)
|
||||
|
||||
* Use Item.new instead of build_item for singleton resource so it doesn't effect database - see issue #304
|
||||
|
||||
* Made accessible_by action default to :index and parent action default to :show instead of :read - see issue #302
|
||||
|
||||
* Reverted Inherited Resources "collection" override since it doesn't seem to be working - see issue #305
|
||||
|
||||
|
||||
1.6.0 (March 11, 2011)
|
||||
|
||||
* Added MetaWhere support - see issue #194 and #261
|
||||
|
||||
* Allow Active Record scopes in Ability conditions - see issue #257
|
||||
|
||||
* Added :if and :unless options to check_authorization - see issue #284
|
||||
|
||||
* Several Inherited Resources fixes (thanks aq1018, tanordheim and stefanoverna)
|
||||
|
||||
* Pass action name to accessible_by call when loading a collection (thanks amw)
|
||||
|
||||
* Added :prepend option to load_and_authorize_resource to load before other filters - see issue #290
|
||||
|
||||
* Fixed spacing issue in I18n message for multi-word model names - see issue #292
|
||||
|
||||
* Load resource collection for any action which doesn't have an "id" parameter - see issue #296
|
||||
|
||||
* Raise an exception when trying to make a Ability condition with both a hash of conditions and a block - see issue #269
|
||||
|
||||
|
||||
1.5.1 (January 20, 2011)
|
||||
|
||||
* Fixing deeply nested conditions in Active Record adapter - see issue #246
|
||||
|
||||
* Improving Mongoid support for multiple can and cannot definitions (thanks stellard) - see issue #239
|
||||
|
||||
|
||||
1.5.0 (January 11, 2011)
|
||||
|
||||
* Added an Ability generator - see issue #170
|
||||
|
||||
* Added DataMapper support (thanks natemueller)
|
||||
|
||||
* Added Mongoid support (thanks bowsersenior)
|
||||
|
||||
* Added skip_load_and_authorize_resource methods to controller class - see issue #164
|
||||
|
||||
* Added support for uncountable resources in index action - see issue #193
|
||||
|
||||
* Cleaned up README and added spec/README
|
||||
|
||||
* Internal: renamed CanDefinition to Rule
|
||||
|
||||
* Internal: added a model adapter layer for easily supporting more ORMs
|
||||
|
||||
* Internal: added .rvmrc to auto-switch to 1.8.7 with gemset - see issue #231
|
||||
|
||||
|
||||
1.4.1 (November 12, 2010)
|
||||
|
||||
* Renaming skip_authorization to skip_authorization_check - see issue #169
|
||||
|
||||
18
Gemfile
18
Gemfile
@@ -1,2 +1,20 @@
|
||||
source "http://rubygems.org"
|
||||
|
||||
case ENV["MODEL_ADAPTER"]
|
||||
when nil, "active_record"
|
||||
gem "sqlite3"
|
||||
gem "activerecord", :require => "active_record"
|
||||
gem "with_model"
|
||||
gem "meta_where"
|
||||
when "data_mapper"
|
||||
gem "dm-core", "~> 1.0.2"
|
||||
gem "dm-sqlite-adapter", "~> 1.0.2"
|
||||
gem "dm-migrations", "~> 1.0.2"
|
||||
when "mongoid"
|
||||
gem "bson_ext", "~> 1.1"
|
||||
gem "mongoid", "~> 2.0.0.beta.20"
|
||||
else
|
||||
raise "Unknown model adapter: #{ENV["MODEL_ADAPTER"]}"
|
||||
end
|
||||
|
||||
gemspec
|
||||
|
||||
2
LICENSE
2
LICENSE
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2010 Ryan Bates
|
||||
Copyright (c) 2011 Ryan Bates
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
|
||||
125
README.rdoc
125
README.rdoc
@@ -1,13 +1,13 @@
|
||||
= CanCan
|
||||
|
||||
Wiki[http://wiki.github.com/ryanb/cancan] | RDocs[http://rdoc.info/projects/ryanb/cancan] | Screencast[http://railscasts.com/episodes/192-authorization-with-cancan]
|
||||
Wiki[https://github.com/ryanb/cancan/wiki] | RDocs[http://rdoc.info/projects/ryanb/cancan] | Screencast[http://railscasts.com/episodes/192-authorization-with-cancan]
|
||||
|
||||
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
|
||||
|
||||
In <b>Rails 3</b>, add this to your Gemfile.
|
||||
In <b>Rails 3</b>, add this to your Gemfile and run the +bundle+ command.
|
||||
|
||||
gem "cancan"
|
||||
|
||||
@@ -22,40 +22,36 @@ Alternatively, you can install it as a plugin.
|
||||
|
||||
== Getting Started
|
||||
|
||||
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.
|
||||
CanCan expects a +current_user+ method to exist in the controller. First, set up some authentication (such as Authlogic[https://github.com/binarylogic/authlogic] or Devise[https://github.com/plataformatec/devise]). See {Changing Defaults}[https://github.com/ryanb/cancan/wiki/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
|
||||
=== 1. Define Abilities
|
||||
|
||||
def initialize(user)
|
||||
if user.admin?
|
||||
can :manage, :all
|
||||
else
|
||||
can :read, :all
|
||||
end
|
||||
end
|
||||
end
|
||||
User permissions are defined in an +Ability+ class. CanCan 1.5 includes a Rails 3 generator for creating this class.
|
||||
|
||||
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.
|
||||
rails g cancan:ability
|
||||
|
||||
The current user's permissions can be accessed using the "can?" and "cannot?" methods in the view and controller.
|
||||
See {Defining Abilities}[https://github.com/ryanb/cancan/wiki/defining-abilities] for details.
|
||||
|
||||
|
||||
=== 2. Check Abilities & Authorization
|
||||
|
||||
The current user's permissions can then be checked using the <tt>can?</tt> and <tt>cannot?</tt> methods in the view and controller.
|
||||
|
||||
<% if can? :update, @article %>
|
||||
<%= link_to "Edit", edit_article_path(@article) %>
|
||||
<% end %>
|
||||
|
||||
See {Checking Abilities}[http://wiki.github.com/ryanb/cancan/checking-abilities] for more information
|
||||
See {Checking Abilities}[https://github.com/ryanb/cancan/wiki/checking-abilities] for more information
|
||||
|
||||
The "authorize!" method in the controller will raise an exception if the user is not able to perform the given action.
|
||||
The <tt>authorize!</tt> method in the controller will raise an exception if the user is not able to perform the given action.
|
||||
|
||||
def show
|
||||
@article = Article.find(params[:id])
|
||||
authorize! :read, @article
|
||||
end
|
||||
|
||||
Setting this for every action can be tedious, therefore the +load_and_authorize_resource+ method is provided to automatically authorize all actions in a RESTful style resource controller. It will use a before filter to load the resource into an instance variable and authorize it for each action.
|
||||
Setting this for every action can be tedious, therefore the +load_and_authorize_resource+ method is provided to automatically authorize all actions in a RESTful style resource controller. It will use a before filter to load the resource into an instance variable and authorize it for every action.
|
||||
|
||||
class ArticlesController < ApplicationController
|
||||
load_and_authorize_resource
|
||||
@@ -65,98 +61,51 @@ Setting this for every action can be tedious, therefore the +load_and_authorize_
|
||||
end
|
||||
end
|
||||
|
||||
See {Authorizing Controller Actions}[http://wiki.github.com/ryanb/cancan/authorizing-controller-actions] for more information
|
||||
See {Authorizing Controller Actions}[https://github.com/ryanb/cancan/wiki/authorizing-controller-actions] for more information.
|
||||
|
||||
|
||||
=== 3. Handle Unauthorized Access
|
||||
|
||||
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[:alert] = exception.message
|
||||
redirect_to root_url
|
||||
redirect_to root_url, :alert => exception.message
|
||||
end
|
||||
end
|
||||
|
||||
See {Exception Handling}[http://wiki.github.com/ryanb/cancan/exception-handling] for more information.
|
||||
See {Exception Handling}[https://github.com/ryanb/cancan/wiki/exception-handling] for more information.
|
||||
|
||||
|
||||
== Defining Abilities
|
||||
=== 4. Lock It Down
|
||||
|
||||
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.
|
||||
If you want to ensure authorization happens on every action in your application, add +check_authorization+ to your ApplicationController.
|
||||
|
||||
The +can+ method is used to define permissions and requires two arguments. The first one is the action you're setting the permission for, the second one is the class of object you're setting it on.
|
||||
|
||||
can :update, Article
|
||||
|
||||
You can pass an array for either of these parameters to match any one. In this case the user will have the ability to update or destroy both articles and comments.
|
||||
|
||||
can [:update, :destroy], [Article, Comment]
|
||||
|
||||
Use :+manage+ to represent any action and :+all+ to represent any class. Here are some examples.
|
||||
|
||||
can :manage, Article # has permissions to do anything to articles
|
||||
can :read, :all # has permission to read any model
|
||||
can :manage, :all # has permission to do anything to any model
|
||||
|
||||
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
|
||||
|
||||
See {Defining Abilities with Hashes}[http://wiki.github.com/ryanb/cancan/defining-abilities-with-hashes] for more information.
|
||||
|
||||
Blocks can also be used if you need more control.
|
||||
|
||||
can :update, Project do |project|
|
||||
project.groups.include?(user.group)
|
||||
class ApplicationController < ActionController::Base
|
||||
check_authorization
|
||||
end
|
||||
|
||||
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.
|
||||
This will raise an exception if authorization is not performed in an action. If you want to skip this add +skip_authorization_check+ to a controller subclass. See {Ensure Authorization}[https://github.com/ryanb/cancan/wiki/Ensure-Authorization] for more information.
|
||||
|
||||
|
||||
== Aliasing Actions
|
||||
== Wiki Docs
|
||||
|
||||
You will usually be working with four actions when defining and checking permissions: :+read+, :+create+, :+update+, :+destroy+. These aren't the same as the 7 RESTful actions in Rails. CanCan automatically adds some default aliases for mapping those actions.
|
||||
|
||||
alias_action :index, :show, :to => :read
|
||||
alias_action :new, :to => :create
|
||||
alias_action :edit, :to => :update
|
||||
|
||||
Notice the +edit+ action is aliased to +update+. 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
|
||||
|
||||
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
|
||||
|
||||
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)
|
||||
|
||||
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.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/]
|
||||
* {Upgrading to 1.6}[https://github.com/ryanb/cancan/wiki/Upgrading-to-1.6]
|
||||
* {Defining Abilities}[https://github.com/ryanb/cancan/wiki/Defining-Abilities]
|
||||
* {Checking Abilities}[https://github.com/ryanb/cancan/wiki/Checking-Abilities]
|
||||
* {Authorizing Controller Actions}[https://github.com/ryanb/cancan/wiki/Authorizing-Controller-Actions]
|
||||
* {Exception Handling}[https://github.com/ryanb/cancan/wiki/Exception-Handling]
|
||||
* {Changing Defaults}[https://github.com/ryanb/cancan/wiki/Changing-Defaults]
|
||||
* {See more}[https://github.com/ryanb/cancan/wiki]
|
||||
|
||||
|
||||
== 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.
|
||||
If you have any issues with CanCan which you cannot find the solution to in the documentation[https://github.com/ryanb/cancan/wiki], please add an {issue on GitHub}[https://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.
|
||||
To get the specs running you should call +bundle+ and then +rake+. See the {spec/README}[https://github.com/ryanb/cancan/blob/master/spec/README.rdoc] for more information.
|
||||
|
||||
|
||||
== Special Thanks
|
||||
|
||||
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.
|
||||
CanCan was inspired by declarative_authorization[https://github.com/stffn/declarative_authorization/] and aegis[https://github.com/makandra/aegis]. Also many thanks to the CanCan contributors[https://github.com/ryanb/cancan/contributors]. See the CHANGELOG[https://github.com/ryanb/cancan/blob/master/CHANGELOG.rdoc] for the full list.
|
||||
|
||||
8
Rakefile
8
Rakefile
@@ -7,4 +7,12 @@ RSpec::Core::RakeTask.new do |t|
|
||||
t.verbose = false
|
||||
end
|
||||
|
||||
desc "Run specs for all adapters"
|
||||
task :spec_all do
|
||||
%w[active_record data_mapper mongoid].each do |model_adapter|
|
||||
puts "MODEL_ADAPTER = #{model_adapter}"
|
||||
system "rake spec MODEL_ADAPTER=#{model_adapter}"
|
||||
end
|
||||
end
|
||||
|
||||
task :default => :spec
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Gem::Specification.new do |s|
|
||||
s.name = "cancan"
|
||||
s.version = "1.4.1"
|
||||
s.version = "1.6.1"
|
||||
s.author = "Ryan Bates"
|
||||
s.email = "ryan@railscasts.com"
|
||||
s.homepage = "http://github.com/ryanb/cancan"
|
||||
@@ -10,7 +10,7 @@ Gem::Specification.new do |s|
|
||||
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 'rspec', '~> 2.1.0'
|
||||
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'
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
require 'cancan/ability'
|
||||
require 'cancan/can_definition'
|
||||
require 'cancan/rule'
|
||||
require 'cancan/controller_resource'
|
||||
require 'cancan/controller_additions'
|
||||
require 'cancan/active_record_additions'
|
||||
require 'cancan/model_additions'
|
||||
require 'cancan/exceptions'
|
||||
require 'cancan/query'
|
||||
require 'cancan/inherited_resource'
|
||||
|
||||
require 'cancan/model_adapters/abstract_adapter'
|
||||
require 'cancan/model_adapters/default_adapter'
|
||||
require 'cancan/model_adapters/active_record_adapter' if defined? ActiveRecord
|
||||
require 'cancan/model_adapters/data_mapper_adapter' if defined? DataMapper
|
||||
require 'cancan/model_adapters/mongoid_adapter' if defined? Mongoid
|
||||
|
||||
@@ -54,8 +54,8 @@ module CanCan
|
||||
#
|
||||
# Also see the RSpec Matchers to aid in testing.
|
||||
def 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)
|
||||
match = relevant_rules_for_match(action, subject).detect do |rule|
|
||||
rule.matches_conditions?(action, subject, extra_args)
|
||||
end
|
||||
match ? match.base_behavior : false
|
||||
end
|
||||
@@ -122,7 +122,7 @@ module CanCan
|
||||
# end
|
||||
#
|
||||
def can(action = nil, subject = nil, conditions = nil, &block)
|
||||
can_definitions << CanDefinition.new(true, action, subject, conditions, block)
|
||||
rules << Rule.new(true, action, subject, conditions, block)
|
||||
end
|
||||
|
||||
# Defines an ability which cannot be done. Accepts the same arguments as "can".
|
||||
@@ -138,7 +138,7 @@ module CanCan
|
||||
# end
|
||||
#
|
||||
def cannot(action = nil, subject = nil, conditions = nil, &block)
|
||||
can_definitions << CanDefinition.new(false, action, subject, conditions, block)
|
||||
rules << Rule.new(false, action, subject, conditions, block)
|
||||
end
|
||||
|
||||
# Alias one or more actions into another one.
|
||||
@@ -186,11 +186,9 @@ module CanCan
|
||||
@aliased_actions = {}
|
||||
end
|
||||
|
||||
# Returns a CanCan::Query instance to help generate database queries based on the ability.
|
||||
# If any relevant can definitions use a block then an exception will be raised because an
|
||||
# SQL query cannot be generated from blocks of code.
|
||||
def query(action, subject)
|
||||
Query.new(subject, relevant_can_definitions_for_query(action, subject))
|
||||
def model_adapter(model_class, action)
|
||||
adapter_class = ModelAdapters::AbstractAdapter.adapter_class(model_class)
|
||||
adapter_class.new(model_class, relevant_rules_for_query(action, model_class))
|
||||
end
|
||||
|
||||
# See ControllerAdditions#authorize! for documentation.
|
||||
@@ -208,25 +206,25 @@ module CanCan
|
||||
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
|
||||
variables[:subject] = (subject.class == Class ? subject : subject.class).to_s.underscore.humanize.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
|
||||
relevant_rules(action, subject).map do |rule|
|
||||
attributes.merge!(rule.attributes_from_conditions) if rule.base_behavior
|
||||
end
|
||||
attributes
|
||||
end
|
||||
|
||||
def has_block?(action, subject)
|
||||
relevant_can_definitions(action, subject).any?(&:only_block?)
|
||||
relevant_rules(action, subject).any?(&:only_block?)
|
||||
end
|
||||
|
||||
def has_raw_sql?(action, subject)
|
||||
relevant_can_definitions(action, subject).any?(&:only_raw_sql?)
|
||||
relevant_rules(action, subject).any?(&:only_raw_sql?)
|
||||
end
|
||||
|
||||
private
|
||||
@@ -259,30 +257,30 @@ module CanCan
|
||||
results
|
||||
end
|
||||
|
||||
def can_definitions
|
||||
@can_definitions ||= []
|
||||
def rules
|
||||
@rules ||= []
|
||||
end
|
||||
|
||||
# Returns an array of CanDefinition instances which match the action and subject
|
||||
# Returns an array of Rule 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
|
||||
def relevant_rules(action, subject)
|
||||
rules.reverse.select do |rule|
|
||||
rule.expanded_actions = expand_actions(rule.actions)
|
||||
rule.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?
|
||||
def relevant_rules_for_match(action, subject)
|
||||
relevant_rules(action, subject).each do |rule|
|
||||
if rule.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?
|
||||
def relevant_rules_for_query(action, subject)
|
||||
relevant_rules(action, subject).each do |rule|
|
||||
if rule.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
|
||||
|
||||
@@ -109,6 +109,9 @@ module CanCan
|
||||
#
|
||||
# load_resource :new => :build
|
||||
#
|
||||
# [:+prepend+]
|
||||
# Passing +true+ will use prepend_before_filter instead of a normal before_filter.
|
||||
#
|
||||
def load_resource(*args)
|
||||
cancan_resource_class.add_before_filter(self, :load_resource, *args)
|
||||
end
|
||||
@@ -162,10 +165,59 @@ module CanCan
|
||||
# [:+through+]
|
||||
# Authorize conditions on this parent resource when instance isn't available.
|
||||
#
|
||||
# [:+prepend+]
|
||||
# Passing +true+ will use prepend_before_filter instead of a normal before_filter.
|
||||
#
|
||||
def authorize_resource(*args)
|
||||
cancan_resource_class.add_before_filter(self, :authorize_resource, *args)
|
||||
end
|
||||
|
||||
# Skip both the loading and authorization behavior of CanCan for this given controller. This is primarily
|
||||
# useful to skip the behavior of a superclass. You can pass :only and :except options to specify which actions
|
||||
# to skip the effects on. It will apply to all actions by default.
|
||||
#
|
||||
# class ProjectsController < SomeOtherController
|
||||
# skip_load_and_authorize_resource :only => :index
|
||||
# end
|
||||
#
|
||||
# You can also pass the resource name as the first argument to skip that resource.
|
||||
def skip_load_and_authorize_resource(*args)
|
||||
skip_load_resource(*args)
|
||||
skip_authorize_resource(*args)
|
||||
end
|
||||
|
||||
# Skip both the loading behavior of CanCan. This is useful when using +load_and_authorize_resource+ but want to
|
||||
# only do authorization on certain actions. You can pass :only and :except options to specify which actions to
|
||||
# skip the effects on. It will apply to all actions by default.
|
||||
#
|
||||
# class ProjectsController < ApplicationController
|
||||
# load_and_authorize_resource
|
||||
# skip_load_resource :only => :index
|
||||
# end
|
||||
#
|
||||
# You can also pass the resource name as the first argument to skip that resource.
|
||||
def skip_load_resource(*args)
|
||||
options = args.extract_options!
|
||||
name = args.first
|
||||
cancan_skipper[:load][name] = options
|
||||
end
|
||||
|
||||
# Skip both the authorization behavior of CanCan. This is useful when using +load_and_authorize_resource+ but want to
|
||||
# only do loading on certain actions. You can pass :only and :except options to specify which actions to
|
||||
# skip the effects on. It will apply to all actions by default.
|
||||
#
|
||||
# class ProjectsController < ApplicationController
|
||||
# load_and_authorize_resource
|
||||
# skip_authorize_resource :only => :index
|
||||
# end
|
||||
#
|
||||
# You can also pass the resource name as the first argument to skip that resource.
|
||||
def skip_authorize_resource(*args)
|
||||
options = args.extract_options!
|
||||
name = args.first
|
||||
cancan_skipper[:authorize][name] = options
|
||||
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.
|
||||
@@ -174,16 +226,33 @@ module CanCan
|
||||
# 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)
|
||||
#
|
||||
# Options:
|
||||
# [:+only+]
|
||||
# Only applies to given actions.
|
||||
#
|
||||
# [:+except+]
|
||||
# Does not apply to given actions.
|
||||
#
|
||||
# [:+if+]
|
||||
# Supply the name of a controller method to be called. The authorization check only takes place if this returns true.
|
||||
#
|
||||
# check_authorization :if => :admin_controller?
|
||||
#
|
||||
# [:+unless+]
|
||||
# Supply the name of a controller method to be called. The authorization check only takes place if this returns false.
|
||||
#
|
||||
# check_authorization :unless => :devise_controller?
|
||||
#
|
||||
def check_authorization(options = {})
|
||||
self.after_filter(options.slice(:only, :except)) do |controller|
|
||||
return if controller.instance_variable_defined?(:@_authorized)
|
||||
return if options[:if] && !controller.send(options[:if])
|
||||
return if options[:unless] && controller.send(options[:unless])
|
||||
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.
|
||||
#
|
||||
@@ -209,6 +278,10 @@ module CanCan
|
||||
ControllerResource
|
||||
end
|
||||
end
|
||||
|
||||
def cancan_skipper
|
||||
@_cancan_skipper ||= {:authorize => {}, :load => {}}
|
||||
end
|
||||
end
|
||||
|
||||
def self.included(base)
|
||||
@@ -244,8 +317,7 @@ module CanCan
|
||||
#
|
||||
# class ApplicationController < ActionController::Base
|
||||
# rescue_from CanCan::AccessDenied do |exception|
|
||||
# flash[:error] = exception.message
|
||||
# redirect_to root_url
|
||||
# redirect_to root_url, :alert => exception.message
|
||||
# end
|
||||
# end
|
||||
#
|
||||
|
||||
@@ -5,7 +5,8 @@ module CanCan
|
||||
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|
|
||||
before_filter_method = options.delete(:prepend) ? :prepend_before_filter : :before_filter
|
||||
controller_class.send(before_filter_method, options.slice(:only, :except)) do |controller|
|
||||
controller.class.cancan_resource_class.new(controller, resource_name, options.except(:only, :except)).send(method)
|
||||
end
|
||||
end
|
||||
@@ -26,21 +27,38 @@ module CanCan
|
||||
end
|
||||
|
||||
def load_resource
|
||||
if parent? || member_action?
|
||||
unless skip?(:load)
|
||||
if load_instance?
|
||||
self.resource_instance ||= load_resource_instance
|
||||
elsif load_collection?
|
||||
self.collection_instance ||= load_collection
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def authorize_resource
|
||||
unless skip?(:authorize)
|
||||
@controller.authorize!(authorization_action, resource_instance || resource_class_with_parent)
|
||||
end
|
||||
end
|
||||
|
||||
def parent?
|
||||
@options.has_key?(:parent) ? @options[:parent] : @name && @name != name_from_controller.to_sym
|
||||
end
|
||||
|
||||
def skip?(behavior) # This could probably use some refactoring
|
||||
options = @controller.class.cancan_skipper[behavior][@name]
|
||||
if options.nil?
|
||||
false
|
||||
elsif options == {}
|
||||
true
|
||||
elsif options[:except] && ![options[:except]].flatten.include?(@params[:action].to_sym)
|
||||
true
|
||||
elsif [options[:only]].flatten.include?(@params[:action].to_sym)
|
||||
true
|
||||
end
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
def load_resource_instance
|
||||
@@ -51,42 +69,43 @@ module CanCan
|
||||
end
|
||||
end
|
||||
|
||||
def load_instance?
|
||||
parent? || member_action?
|
||||
end
|
||||
|
||||
def load_collection?
|
||||
resource_base.respond_to?(:accessible_by) &&
|
||||
!current_ability.has_block?(authorization_action, resource_class)
|
||||
resource_base.respond_to?(:accessible_by) && !current_ability.has_block?(authorization_action, resource_class)
|
||||
end
|
||||
|
||||
def load_collection
|
||||
resource_base.accessible_by(current_ability)
|
||||
resource_base.accessible_by(current_ability, authorization_action)
|
||||
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")
|
||||
resource = resource_base.new(@params[name] || {})
|
||||
resource.send("#{parent_name}=", parent_resource) if @options[:singleton] && parent_resource
|
||||
initial_attributes.each do |attr_name, value|
|
||||
resource.send("#{attr_name}=", value)
|
||||
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)
|
||||
current_ability.attributes_for(@params[:action].to_sym, resource_class).delete_if do |key, value|
|
||||
@params[name] && @params[name].include?(key)
|
||||
end
|
||||
end
|
||||
|
||||
def find_resource
|
||||
if @options[:singleton] && resource_base.respond_to?(name)
|
||||
resource_base.send(name)
|
||||
if @options[:singleton] && parent_resource.respond_to?(name)
|
||||
parent_resource.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
|
||||
parent? ? :show : @params[:action].to_sym
|
||||
end
|
||||
|
||||
def id_param
|
||||
@@ -94,7 +113,7 @@ module CanCan
|
||||
end
|
||||
|
||||
def member_action?
|
||||
!collection_actions.include? @params[:action].to_sym
|
||||
new_actions.include?(@params[:action].to_sym) || (@params[:id] && !collection_actions.include?(@params[:action].to_sym))
|
||||
end
|
||||
|
||||
# Returns the class used for this resource. This can be overriden by the :class option.
|
||||
@@ -118,7 +137,7 @@ module CanCan
|
||||
end
|
||||
|
||||
def resource_instance
|
||||
@controller.instance_variable_get("@#{instance_name}")
|
||||
@controller.instance_variable_get("@#{instance_name}") if load_instance?
|
||||
end
|
||||
|
||||
def collection_instance=(instance)
|
||||
@@ -136,7 +155,7 @@ module CanCan
|
||||
def resource_base
|
||||
if @options[:through]
|
||||
if parent_resource
|
||||
@options[:singleton] ? parent_resource : parent_resource.send(@options[:through_association] || name.to_s.pluralize)
|
||||
@options[:singleton] ? resource_class : parent_resource.send(@options[:through_association] || name.to_s.pluralize)
|
||||
elsif @options[:shallow]
|
||||
resource_class
|
||||
else
|
||||
@@ -147,9 +166,13 @@ module CanCan
|
||||
end
|
||||
end
|
||||
|
||||
def parent_name
|
||||
@options[:through] && [@options[:through]].flatten.detect { |i| fetch_parent(i) }
|
||||
end
|
||||
|
||||
# The object to load this resource through.
|
||||
def parent_resource
|
||||
@options[:through] && [@options[:through]].flatten.map { |i| fetch_parent(i) }.compact.first
|
||||
parent_name && fetch_parent(parent_name)
|
||||
end
|
||||
|
||||
def fetch_parent(name)
|
||||
|
||||
@@ -2,6 +2,9 @@ module CanCan
|
||||
# A general CanCan exception
|
||||
class Error < StandardError; end
|
||||
|
||||
# Raised when behavior is not implemented, usually used in an abstract class.
|
||||
class NotImplemented < Error; end
|
||||
|
||||
# Raised when removed code is called, an alternative solution is provided in message.
|
||||
class ImplementationRemoved < Error; end
|
||||
|
||||
|
||||
@@ -3,7 +3,8 @@ module CanCan
|
||||
class InheritedResource < ControllerResource # :nodoc:
|
||||
def load_resource_instance
|
||||
if parent?
|
||||
@controller.send :parent
|
||||
@controller.send :association_chain
|
||||
@controller.instance_variable_get("@#{instance_name}")
|
||||
elsif new_actions.include? @params[:action].to_sym
|
||||
@controller.send :build_resource
|
||||
else
|
||||
|
||||
51
lib/cancan/model_adapters/abstract_adapter.rb
Normal file
51
lib/cancan/model_adapters/abstract_adapter.rb
Normal file
@@ -0,0 +1,51 @@
|
||||
module CanCan
|
||||
module ModelAdapters
|
||||
class AbstractAdapter
|
||||
def self.inherited(subclass)
|
||||
@subclasses ||= []
|
||||
@subclasses << subclass
|
||||
end
|
||||
|
||||
def self.adapter_class(model_class)
|
||||
@subclasses.detect { |subclass| subclass.for_class?(model_class) } || DefaultAdapter
|
||||
end
|
||||
|
||||
# Used to determine if the given adapter should be used for the passed in class.
|
||||
def self.for_class?(member_class)
|
||||
false # override in subclass
|
||||
end
|
||||
|
||||
# Used to determine if this model adapter will override the matching behavior for a hash of conditions.
|
||||
# If this returns true then matches_conditions_hash? will be called. See Rule#matches_conditions_hash
|
||||
def self.override_conditions_hash_matching?(subject, conditions)
|
||||
false
|
||||
end
|
||||
|
||||
# Override if override_conditions_hash_matching? returns true
|
||||
def self.matches_conditions_hash?(subject, conditions)
|
||||
raise NotImplemented, "This model adapter does not support matching on a conditions hash."
|
||||
end
|
||||
|
||||
# Used to determine if this model adapter will override the matching behavior for a specific condition.
|
||||
# If this returns true then matches_condition? will be called. See Rule#matches_conditions_hash
|
||||
def self.override_condition_matching?(subject, name, value)
|
||||
false
|
||||
end
|
||||
|
||||
# Override if override_condition_matching? returns true
|
||||
def self.matches_condition?(subject, name, value)
|
||||
raise NotImplemented, "This model adapter does not support matching on a specific condition."
|
||||
end
|
||||
|
||||
def initialize(model_class, rules)
|
||||
@model_class = model_class
|
||||
@rules = rules
|
||||
end
|
||||
|
||||
def database_records
|
||||
# This should be overridden in a subclass to return records which match @rules
|
||||
raise NotImplemented, "This model adapter does not support fetching records from the database."
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
165
lib/cancan/model_adapters/active_record_adapter.rb
Normal file
165
lib/cancan/model_adapters/active_record_adapter.rb
Normal file
@@ -0,0 +1,165 @@
|
||||
module CanCan
|
||||
module ModelAdapters
|
||||
class ActiveRecordAdapter < AbstractAdapter
|
||||
def self.for_class?(model_class)
|
||||
model_class <= ActiveRecord::Base
|
||||
end
|
||||
|
||||
def self.override_condition_matching?(subject, name, value)
|
||||
name.kind_of?(MetaWhere::Column) if defined? MetaWhere
|
||||
end
|
||||
|
||||
def self.matches_condition?(subject, name, value)
|
||||
subject_value = subject.send(name.column)
|
||||
if name.method.to_s.ends_with? "_any"
|
||||
value.any? { |v| meta_where_match? subject_value, name.method.to_s.sub("_any", ""), v }
|
||||
elsif name.method.to_s.ends_with? "_all"
|
||||
value.all? { |v| meta_where_match? subject_value, name.method.to_s.sub("_all", ""), v }
|
||||
else
|
||||
meta_where_match? subject_value, name.method, value
|
||||
end
|
||||
end
|
||||
|
||||
def self.meta_where_match?(subject_value, method, value)
|
||||
case method.to_sym
|
||||
when :eq then subject_value == value
|
||||
when :not_eq then subject_value != value
|
||||
when :in then value.include?(subject_value)
|
||||
when :not_in then !value.include?(subject_value)
|
||||
when :lt then subject_value < value
|
||||
when :lteq then subject_value <= value
|
||||
when :gt then subject_value > value
|
||||
when :gteq then subject_value >= value
|
||||
when :matches then subject_value =~ Regexp.new("^" + Regexp.escape(value).gsub("%", ".*") + "$", true)
|
||||
when :does_not_match then !meta_where_match?(subject_value, :matches, value)
|
||||
else raise NotImplemented, "The #{method} MetaWhere condition is not supported."
|
||||
end
|
||||
end
|
||||
|
||||
# Returns conditions intended to be used inside a database query. Normally you will not call this
|
||||
# method directly, but instead go through ModelAdditions#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 @rules.size == 1 && @rules.first.base_behavior
|
||||
# Return the conditions directly if there's just one definition
|
||||
tableized_conditions(@rules.first.conditions).dup
|
||||
else
|
||||
@rules.reverse.inject(false_sql) do |sql, rule|
|
||||
merge_conditions(sql, tableized_conditions(rule.conditions).dup, rule.base_behavior)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def tableized_conditions(conditions, model_class = @model_class)
|
||||
return conditions unless conditions.kind_of? Hash
|
||||
conditions.inject({}) do |result_hash, (name, value)|
|
||||
if value.kind_of? Hash
|
||||
association_class = model_class.reflect_on_association(name).class_name.constantize
|
||||
name = model_class.reflect_on_association(name).table_name.to_sym
|
||||
value = tableized_conditions(value, association_class)
|
||||
end
|
||||
result_hash[name] = value
|
||||
result_hash
|
||||
end
|
||||
end
|
||||
|
||||
# Returns the associations used in conditions for the :joins option of a search.
|
||||
# See ModelAdditions#accessible_by
|
||||
def joins
|
||||
joins_hash = {}
|
||||
@rules.each do |rule|
|
||||
merge_joins(joins_hash, rule.associations_hash)
|
||||
end
|
||||
clean_joins(joins_hash) unless joins_hash.empty?
|
||||
end
|
||||
|
||||
def database_records
|
||||
if override_scope
|
||||
override_scope
|
||||
elsif @model_class.respond_to?(:where) && @model_class.respond_to?(:joins)
|
||||
@model_class.where(conditions).joins(joins)
|
||||
else
|
||||
@model_class.scoped(:conditions => conditions, :joins => joins)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def override_scope
|
||||
conditions = @rules.map(&:conditions).compact
|
||||
if conditions.any? { |c| c.kind_of?(ActiveRecord::Relation) }
|
||||
if conditions.size == 1
|
||||
conditions.first
|
||||
else
|
||||
rule = @rules.detect { |rule| rule.conditions.kind_of?(ActiveRecord::Relation) }
|
||||
raise Error, "Unable to merge an Active Record scope with other conditions. Instead use a hash or SQL for #{rule.actions.first} #{rule.subjects.first} ability."
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
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)
|
||||
@model_class.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
|
||||
end
|
||||
|
||||
ActiveRecord::Base.class_eval do
|
||||
include CanCan::ModelAdditions
|
||||
end
|
||||
33
lib/cancan/model_adapters/data_mapper_adapter.rb
Normal file
33
lib/cancan/model_adapters/data_mapper_adapter.rb
Normal file
@@ -0,0 +1,33 @@
|
||||
module CanCan
|
||||
module ModelAdapters
|
||||
class DataMapperAdapter < AbstractAdapter
|
||||
def self.for_class?(model_class)
|
||||
model_class <= DataMapper::Resource
|
||||
end
|
||||
|
||||
def self.override_conditions_hash_matching?(subject, conditions)
|
||||
conditions.any? { |k,v| !k.kind_of?(Symbol) }
|
||||
end
|
||||
|
||||
def self.matches_conditions_hash?(subject, conditions)
|
||||
subject.class.all(:conditions => conditions).include?(subject) # TODO don't use a database query here for performance and other instances
|
||||
end
|
||||
|
||||
def database_records
|
||||
scope = @model_class.all(:conditions => ["0=1"])
|
||||
conditions.each do |condition|
|
||||
scope += @model_class.all(:conditions => condition)
|
||||
end
|
||||
scope
|
||||
end
|
||||
|
||||
def conditions
|
||||
@rules.map(&:conditions)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
DataMapper::Model.class_eval do
|
||||
include CanCan::ModelAdditions::ClassMethods
|
||||
end
|
||||
7
lib/cancan/model_adapters/default_adapter.rb
Normal file
7
lib/cancan/model_adapters/default_adapter.rb
Normal file
@@ -0,0 +1,7 @@
|
||||
module CanCan
|
||||
module ModelAdapters
|
||||
class DefaultAdapter < AbstractAdapter
|
||||
# This adapter is used when no matching adapter is found
|
||||
end
|
||||
end
|
||||
end
|
||||
38
lib/cancan/model_adapters/mongoid_adapter.rb
Normal file
38
lib/cancan/model_adapters/mongoid_adapter.rb
Normal file
@@ -0,0 +1,38 @@
|
||||
module CanCan
|
||||
module ModelAdapters
|
||||
class MongoidAdapter < AbstractAdapter
|
||||
def self.for_class?(model_class)
|
||||
model_class <= Mongoid::Document
|
||||
end
|
||||
|
||||
def self.override_conditions_hash_matching?(subject, conditions)
|
||||
conditions.any? { |k,v| !k.kind_of?(Symbol) }
|
||||
end
|
||||
|
||||
def self.matches_conditions_hash?(subject, conditions)
|
||||
# To avoid hitting the db, retrieve the raw Mongo selector from
|
||||
# the Mongoid Criteria and use Mongoid::Matchers#matches?
|
||||
subject.matches?( subject.class.where(conditions).selector )
|
||||
end
|
||||
|
||||
def database_records
|
||||
if @rules.size == 0
|
||||
@model_class.where(:_id => {'$exists' => false, '$type' => 7}) # return no records in Mongoid
|
||||
else
|
||||
@rules.inject(@model_class.all) do |records, rule|
|
||||
if rule.base_behavior
|
||||
records.or(rule.conditions)
|
||||
else
|
||||
records.excludes(rule.conditions)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# simplest way to add `accessible_by` to all Mongoid Documents
|
||||
module Mongoid::Document::ClassMethods
|
||||
include CanCan::ModelAdditions::ClassMethods
|
||||
end
|
||||
@@ -1,9 +1,10 @@
|
||||
module CanCan
|
||||
# This module is automatically included into all Active Record models.
|
||||
module ActiveRecordAdditions
|
||||
|
||||
# This module adds the accessible_by class method to a model. It is included in the model adapters.
|
||||
module ModelAdditions
|
||||
module ClassMethods
|
||||
# Returns a scope which fetches only the records that the passed ability
|
||||
# can perform a given action on. The action defaults to :read. This
|
||||
# can perform a given action on. The action defaults to :index. This
|
||||
# is usually called from a controller and passed the +current_ability+.
|
||||
#
|
||||
# @articles = Article.accessible_by(current_ability)
|
||||
@@ -17,15 +18,9 @@ module CanCan
|
||||
#
|
||||
# @articles = Article.accessible_by(current_ability, :update)
|
||||
#
|
||||
# Here only the articles which the user can update are returned. This
|
||||
# internally uses Ability#conditions method, see that for more information.
|
||||
def accessible_by(ability, action = :read)
|
||||
query = ability.query(action, self)
|
||||
if respond_to?(:where) && respond_to?(:joins)
|
||||
where(query.conditions).joins(query.joins)
|
||||
else
|
||||
scoped(:conditions => query.conditions, :joins => query.joins)
|
||||
end
|
||||
# Here only the articles which the user can update are returned.
|
||||
def accessible_by(ability, action = :index)
|
||||
ability.model_adapter(self, action).database_records
|
||||
end
|
||||
end
|
||||
|
||||
@@ -34,9 +29,3 @@ module CanCan
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if defined? ActiveRecord
|
||||
ActiveRecord::Base.class_eval do
|
||||
include CanCan::ActiveRecordAdditions
|
||||
end
|
||||
end
|
||||
@@ -1,97 +0,0 @@
|
||||
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
|
||||
@@ -2,8 +2,8 @@ module CanCan
|
||||
# This class is used internally and should only be called through Ability.
|
||||
# it holds the information about a "can" call made on Ability and provides
|
||||
# helpful methods to determine permission checking and conditions hash generation.
|
||||
class CanDefinition # :nodoc:
|
||||
attr_reader :base_behavior, :actions
|
||||
class Rule # :nodoc:
|
||||
attr_reader :base_behavior, :subjects, :actions, :conditions
|
||||
attr_writer :expanded_actions
|
||||
|
||||
# The first argument when initializing is the base_behavior which is a true/false
|
||||
@@ -11,6 +11,7 @@ module CanCan
|
||||
# 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)
|
||||
raise Error, "You are not able to supply a block with a hash of conditions in #{action} #{subject} ability. Use either one." if conditions.kind_of?(Hash) && !block.nil?
|
||||
@match_all = action.nil? && subject.nil?
|
||||
@base_behavior = base_behavior
|
||||
@actions = [action].flatten
|
||||
@@ -21,7 +22,7 @@ module CanCan
|
||||
|
||||
# Matches both the subject and action, not necessarily the conditions
|
||||
def relevant?(action, subject)
|
||||
subject = subject.values.first if subject.kind_of? Hash
|
||||
subject = subject.values.first if subject.class == Hash
|
||||
@match_all || (matches_action?(action) && matches_subject?(subject))
|
||||
end
|
||||
|
||||
@@ -31,7 +32,7 @@ module CanCan
|
||||
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)
|
||||
elsif @conditions.kind_of?(Hash) && subject.class == Hash
|
||||
nested_subject_matches_conditions?(subject)
|
||||
elsif @conditions.kind_of?(Hash) && !subject_class?(subject)
|
||||
matches_conditions_hash?(subject)
|
||||
@@ -41,18 +42,6 @@ module CanCan
|
||||
end
|
||||
end
|
||||
|
||||
def tableized_conditions(conditions = @conditions)
|
||||
return conditions unless conditions.kind_of? Hash
|
||||
conditions.inject({}) do |result_hash, (name, value)|
|
||||
if value.kind_of? Hash
|
||||
name = name.to_s.tableize.to_sym
|
||||
value = tableized_conditions(value)
|
||||
end
|
||||
result_hash[name] = value
|
||||
result_hash
|
||||
end
|
||||
end
|
||||
|
||||
def only_block?
|
||||
conditions_empty? && !@block.nil?
|
||||
end
|
||||
@@ -100,8 +89,21 @@ module CanCan
|
||||
@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
|
||||
|
||||
# Checks if the given subject matches the given conditions hash.
|
||||
# This behavior can be overriden by a model adapter by defining two class methods:
|
||||
# override_matching_for_conditions?(subject, conditions) and
|
||||
# matches_conditions_hash?(subject, conditions)
|
||||
def matches_conditions_hash?(subject, conditions = @conditions)
|
||||
if conditions.empty?
|
||||
true
|
||||
else
|
||||
if model_adapter(subject).override_conditions_hash_matching? subject, conditions
|
||||
model_adapter(subject).matches_conditions_hash? subject, conditions
|
||||
else
|
||||
conditions.all? do |name, value|
|
||||
if model_adapter(subject).override_condition_matching? subject, name, value
|
||||
model_adapter(subject).matches_condition? subject, name, value
|
||||
else
|
||||
attribute = subject.send(name)
|
||||
if value.kind_of?(Hash)
|
||||
if attribute.kind_of? Array
|
||||
@@ -116,6 +118,9 @@ module CanCan
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def nested_subject_matches_conditions?(subject_hash)
|
||||
parent, child = subject_hash.shift
|
||||
@@ -129,5 +134,9 @@ module CanCan
|
||||
@block.call(action, subject.class, subject, *extra_args)
|
||||
end
|
||||
end
|
||||
|
||||
def model_adapter(subject)
|
||||
ModelAdapters::AbstractAdapter.adapter_class(subject_class?(subject) ? subject : subject.class)
|
||||
end
|
||||
end
|
||||
end
|
||||
4
lib/generators/cancan/ability/USAGE
Normal file
4
lib/generators/cancan/ability/USAGE
Normal file
@@ -0,0 +1,4 @@
|
||||
Description:
|
||||
The cancan:ability generator creates an Ability class in the models
|
||||
directory. You can move this file anywhere you want as long as it
|
||||
is in the load path.
|
||||
11
lib/generators/cancan/ability/ability_generator.rb
Normal file
11
lib/generators/cancan/ability/ability_generator.rb
Normal file
@@ -0,0 +1,11 @@
|
||||
module Cancan
|
||||
module Generators
|
||||
class AbilityGenerator < Rails::Generators::Base
|
||||
source_root File.expand_path('../templates', __FILE__)
|
||||
|
||||
def generate_ability
|
||||
copy_file "ability.rb", "app/models/ability.rb"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
28
lib/generators/cancan/ability/templates/ability.rb
Normal file
28
lib/generators/cancan/ability/templates/ability.rb
Normal file
@@ -0,0 +1,28 @@
|
||||
class Ability
|
||||
include CanCan::Ability
|
||||
|
||||
def initialize(user)
|
||||
# Define abilities for the passed in user here. For example:
|
||||
#
|
||||
# user ||= User.new # guest user (not logged in)
|
||||
# if user.admin?
|
||||
# can :manage, :all
|
||||
# else
|
||||
# can :read, :all
|
||||
# end
|
||||
#
|
||||
# The first argument to `can` is the action you are giving the user permission to do.
|
||||
# If you pass :manage it will apply to every action. Other common actions here are
|
||||
# :read, :create, :update and :destroy.
|
||||
#
|
||||
# The second argument is the resource the user can perform the action on. If you pass
|
||||
# :all it will apply to every resource. Otherwise pass a Ruby class of the resource.
|
||||
#
|
||||
# The third argument is an optional hash of conditions to further filter the objects.
|
||||
# For example, here the user can only update published articles.
|
||||
#
|
||||
# can :update, Article, :published => true
|
||||
#
|
||||
# See the wiki for details: https://github.com/ryanb/cancan/wiki/Defining-Abilities
|
||||
end
|
||||
end
|
||||
28
spec/README.rdoc
Normal file
28
spec/README.rdoc
Normal file
@@ -0,0 +1,28 @@
|
||||
= CanCan Specs
|
||||
|
||||
== Running the specs
|
||||
|
||||
To run the specs first run the +bundle+ command to install the necessary gems and the +rake+ command to run the specs.
|
||||
|
||||
bundle
|
||||
rake
|
||||
|
||||
The specs currently require Ruby 1.8.7. Ruby 1.9.2 support will be coming soon.
|
||||
|
||||
|
||||
== Model Adapters
|
||||
|
||||
CanCan offers separate specs for different model adapters (such as Mongoid and Data Mapper). By default it will use Active Record but you can change this by setting the +MODEL_ADAPTER+ environment variable before running. You can run the +bundle+ command with this as well to ensure you have the installed gems.
|
||||
|
||||
MODEL_ADAPTER=data_mapper bundle
|
||||
MODEL_ADAPTER=data_mapper rake
|
||||
|
||||
The different model adapters you can specify are:
|
||||
|
||||
* active_record (default)
|
||||
* data_mapper
|
||||
* mongoid
|
||||
|
||||
You can also run the +spec_all+ rake task to run specs for each adapter.
|
||||
|
||||
rake spec_all
|
||||
@@ -32,7 +32,7 @@ describe CanCan::Ability do
|
||||
@ability.can?(:read, Symbol).should be_true
|
||||
end
|
||||
|
||||
it "should pass to previous can definition, if block returns false or nil" do
|
||||
it "should pass to previous rule, if block returns false or nil" do
|
||||
@ability.can :read, Symbol
|
||||
@ability.can :read, Integer do |i|
|
||||
i < 5
|
||||
@@ -144,7 +144,7 @@ describe CanCan::Ability do
|
||||
@ability.can?(:update, 123).should be_false
|
||||
end
|
||||
|
||||
it "should support custom objects in the can definition" do
|
||||
it "should support custom objects in the rule" do
|
||||
@ability.can :read, :stats
|
||||
@ability.can?(:read, :stats).should be_true
|
||||
@ability.can?(:update, :stats).should be_false
|
||||
@@ -165,7 +165,7 @@ describe CanCan::Ability do
|
||||
@ability.can?(:read, 123).should be_false
|
||||
end
|
||||
|
||||
it "should pass to previous can definition, if block returns false or nil" do
|
||||
it "should pass to previous rule, if block returns false or nil" do
|
||||
@ability.can :read, :all
|
||||
@ability.cannot :read, Integer do |int|
|
||||
int > 10 ? nil : ( int > 5 )
|
||||
@@ -291,6 +291,12 @@ describe CanCan::Ability do
|
||||
@ability.can?(:read, 123 => Range).should be_true
|
||||
end
|
||||
|
||||
it "should allow to check ability on Hash-like object" do
|
||||
class Container < Hash; end
|
||||
@ability.can :read, Container
|
||||
@ability.can?(:read, Container.new).should be_true
|
||||
end
|
||||
|
||||
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]
|
||||
@@ -343,6 +349,22 @@ describe CanCan::Ability do
|
||||
end
|
||||
end
|
||||
|
||||
it "should determine model adapter class by asking AbstractAdapter" do
|
||||
model_class = Object.new
|
||||
adapter_class = Object.new
|
||||
stub(CanCan::ModelAdapters::AbstractAdapter).adapter_class(model_class) { adapter_class }
|
||||
stub(adapter_class).new(model_class, []) { :adapter_instance }
|
||||
@ability.model_adapter(model_class, :read).should == :adapter_instance
|
||||
end
|
||||
|
||||
it "should raise an error when attempting to use a block with a hash condition since it's not likely what they want" do
|
||||
lambda {
|
||||
@ability.can :read, Array, :published => true do
|
||||
false
|
||||
end
|
||||
}.should raise_error(CanCan::Error, "You are not able to supply a block with a hash of conditions in read Array ability. Use either one.")
|
||||
end
|
||||
|
||||
describe "unauthorized message" do
|
||||
after(:each) do
|
||||
I18n.backend = nil
|
||||
@@ -381,6 +403,7 @@ describe CanCan::Ability do
|
||||
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(:update, ArgumentError).should == "update argument error"
|
||||
@ability.unauthorized_message(:edit, 1..3).should == "edit range"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
require "spec_helper"
|
||||
|
||||
describe CanCan::ActiveRecordAdditions do
|
||||
before(:each) do
|
||||
@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('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
|
||||
|
||||
it "should default to :read ability and use scoped when where isn't available" do
|
||||
@ability.can :read, @model_class, :foo => {:bar => 1}
|
||||
stub(@model_class).scoped(:conditions => {:foos => {:bar => 1}}, :joins => [:foo]) { :found_records }
|
||||
@model_class.accessible_by(@ability).should == :found_records
|
||||
end
|
||||
|
||||
it "should merge association joins and sanitize conditions" do
|
||||
@ability.can :read, @model_class, :foo => {:bar => 1}
|
||||
@ability.can :read, @model_class, :too => {:car => 1, :far => {:bar => 1}}
|
||||
|
||||
condition_variants = [
|
||||
'(toos.fars.bar=1 AND toos.car=1) OR (foos.bar=1)', # faked sql sanitizer is stupid ;-)
|
||||
'(toos.car=1 AND toos.fars.bar=1) OR (foos.bar=1)'
|
||||
]
|
||||
joins_variants = [
|
||||
[:foo, {:too => [:far]}],
|
||||
[{:too => [:far]}, :foo]
|
||||
]
|
||||
|
||||
condition_variants.each do |condition|
|
||||
joins_variants.each do |joins|
|
||||
stub(@model_class).scoped( :conditions => condition, :joins => joins ) { :found_records }
|
||||
end
|
||||
end
|
||||
# @ability.conditions(:read, @model_class).should == '(too.car=1 AND too.far.bar=1) OR (foo.bar=1)'
|
||||
# @ability.associations_hash(:read, @model_class).should == [{:too => [:far]}, :foo]
|
||||
@model_class.accessible_by(@ability).should == :found_records
|
||||
end
|
||||
|
||||
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,57 +0,0 @@
|
||||
require "spec_helper"
|
||||
|
||||
# Most of CanDefinition functionality is tested in Ability specs
|
||||
describe CanCan::CanDefinition do
|
||||
before(:each) do
|
||||
@conditions = {}
|
||||
@can = CanCan::CanDefinition.new(true, :read, Integer, @conditions, nil)
|
||||
end
|
||||
|
||||
it "should return no association joins if none exist" do
|
||||
@can.associations_hash.should == {}
|
||||
end
|
||||
|
||||
it "should return no association for joins if just attributes" do
|
||||
@conditions[:foo] = :bar
|
||||
@can.associations_hash.should == {}
|
||||
end
|
||||
|
||||
it "should return single association for joins" do
|
||||
@conditions[:foo] = {:bar => 1}
|
||||
@can.associations_hash.should == {:foo => {}}
|
||||
end
|
||||
|
||||
it "should return multiple associations for joins" do
|
||||
@conditions[:foo] = {:bar => 1}
|
||||
@conditions[:test] = {1 => 2}
|
||||
@can.associations_hash.should == {:foo => {}, :test => {}}
|
||||
end
|
||||
|
||||
it "should return nested associations for joins" do
|
||||
@conditions[:foo] = {:bar => {1 => 2}}
|
||||
@can.associations_hash.should == {:foo => {:bar => {}}}
|
||||
end
|
||||
|
||||
it "should tableize correctly for absurdly complex permissions" do
|
||||
@conditions[:unit] = {:property=>{:landlord=>{:weasle_id=>560}}}
|
||||
@conditions[:test] = 1
|
||||
@can.tableized_conditions.should == {:units => {:properties => {:landlords=>{:weasle_id=>560}}}, :test => 1}
|
||||
end
|
||||
|
||||
it "should tableize correctly for complex permissions" do
|
||||
@conditions[:unit] = {:property=>{:landlord_id=>560}}
|
||||
@conditions[:test] = 1
|
||||
@can.tableized_conditions.should == {:units => {:properties => {:landlord_id=>560}}, :test => 1}
|
||||
end
|
||||
|
||||
it "should return table names in conditions for association joins" do
|
||||
@conditions[:foo] = {:bar => 1}
|
||||
@conditions[:test] = 1
|
||||
@can.tableized_conditions.should == {:foos => {:bar => 1}, :test => 1}
|
||||
end
|
||||
|
||||
it "should return no association joins if conditions is nil" do
|
||||
can = CanCan::CanDefinition.new(true, :read, Integer, nil, nil)
|
||||
can.associations_hash.should == {}
|
||||
end
|
||||
end
|
||||
@@ -42,6 +42,11 @@ describe CanCan::ControllerAdditions do
|
||||
@controller_class.load_and_authorize_resource :project, :foo => :bar
|
||||
end
|
||||
|
||||
it "load_and_authorize_resource with :prepend should prepend the before filter" do
|
||||
mock(@controller_class).prepend_before_filter({})
|
||||
@controller_class.load_and_authorize_resource :foo => :bar, :prepend => true
|
||||
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) }
|
||||
@@ -61,17 +66,33 @@ describe CanCan::ControllerAdditions do
|
||||
end
|
||||
|
||||
it "check_authorization should trigger AuthorizationNotPerformed in after filter" do
|
||||
mock(@controller_class).after_filter(:some_options) { |options, block| block.call(@controller) }
|
||||
mock(@controller_class).after_filter(:only => [:test]) { |options, block| block.call(@controller) }
|
||||
lambda {
|
||||
@controller_class.check_authorization(:some_options)
|
||||
@controller_class.check_authorization(:only => [:test])
|
||||
}.should raise_error(CanCan::AuthorizationNotPerformed)
|
||||
end
|
||||
|
||||
it "check_authorization should not trigger AuthorizationNotPerformed when :if is false" do
|
||||
stub(@controller).check_auth? { false }
|
||||
mock(@controller_class).after_filter({}) { |options, block| block.call(@controller) }
|
||||
lambda {
|
||||
@controller_class.check_authorization(:if => :check_auth?)
|
||||
}.should_not raise_error(CanCan::AuthorizationNotPerformed)
|
||||
end
|
||||
|
||||
it "check_authorization should not trigger AuthorizationNotPerformed when :unless is true" do
|
||||
stub(@controller).engine_controller? { true }
|
||||
mock(@controller_class).after_filter({}) { |options, block| block.call(@controller) }
|
||||
lambda {
|
||||
@controller_class.check_authorization(:unless => :engine_controller?)
|
||||
}.should_not 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) }
|
||||
mock(@controller_class).after_filter(:only => [:test]) { |options, block| block.call(@controller) }
|
||||
lambda {
|
||||
@controller_class.check_authorization(:some_options)
|
||||
@controller_class.check_authorization(:only => [:test])
|
||||
}.should_not raise_error(CanCan::AuthorizationNotPerformed)
|
||||
end
|
||||
|
||||
@@ -83,4 +104,34 @@ describe CanCan::ControllerAdditions do
|
||||
stub(@controller.class).ancestors { ["InheritedResources::Actions"] }
|
||||
@controller.class.cancan_resource_class.should == CanCan::InheritedResource
|
||||
end
|
||||
|
||||
it "cancan_skipper should be an empty hash with :authorize and :load options and remember changes" do
|
||||
@controller_class.cancan_skipper.should == {:authorize => {}, :load => {}}
|
||||
@controller_class.cancan_skipper[:load] = true
|
||||
@controller_class.cancan_skipper[:load].should == true
|
||||
end
|
||||
|
||||
it "skip_authorize_resource should add itself to the cancan skipper with given model name and options" do
|
||||
@controller_class.skip_authorize_resource(:project, :only => [:index, :show])
|
||||
@controller_class.cancan_skipper[:authorize][:project].should == {:only => [:index, :show]}
|
||||
@controller_class.skip_authorize_resource(:only => [:index, :show])
|
||||
@controller_class.cancan_skipper[:authorize][nil].should == {:only => [:index, :show]}
|
||||
@controller_class.skip_authorize_resource(:article)
|
||||
@controller_class.cancan_skipper[:authorize][:article].should == {}
|
||||
end
|
||||
|
||||
it "skip_load_resource should add itself to the cancan skipper with given model name and options" do
|
||||
@controller_class.skip_load_resource(:project, :only => [:index, :show])
|
||||
@controller_class.cancan_skipper[:load][:project].should == {:only => [:index, :show]}
|
||||
@controller_class.skip_load_resource(:only => [:index, :show])
|
||||
@controller_class.cancan_skipper[:load][nil].should == {:only => [:index, :show]}
|
||||
@controller_class.skip_load_resource(:article)
|
||||
@controller_class.cancan_skipper[:load][:article].should == {}
|
||||
end
|
||||
|
||||
it "skip_load_and_authore_resource should add itself to the cancan skipper with given model name and options" do
|
||||
@controller_class.skip_load_and_authorize_resource(:project, :only => [:index, :show])
|
||||
@controller_class.cancan_skipper[:load][:project].should == {:only => [:index, :show]}
|
||||
@controller_class.cancan_skipper[:authorize][:project].should == {:only => [:index, :show]}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -3,10 +3,12 @@ require "spec_helper"
|
||||
describe CanCan::ControllerResource do
|
||||
before(:each) do
|
||||
@params = HashWithIndifferentAccess.new(:controller => "projects")
|
||||
@controller = Object.new # simple stub for now
|
||||
@controller_class = Class.new
|
||||
@controller = @controller_class.new
|
||||
@ability = Ability.new(nil)
|
||||
stub(@controller).params { @params }
|
||||
stub(@controller).current_ability { @ability }
|
||||
stub(@controller_class).cancan_skipper { {:authorize => {}, :load => {}} }
|
||||
end
|
||||
|
||||
it "should load the resource into an instance variable if params[:id] is specified" do
|
||||
@@ -65,7 +67,7 @@ describe CanCan::ControllerResource do
|
||||
end
|
||||
|
||||
it "should build a collection when on index action when class responds to accessible_by" do
|
||||
stub(Project).accessible_by(@ability) { :found_projects }
|
||||
stub(Project).accessible_by(@ability, :index) { :found_projects }
|
||||
@params[:action] = "index"
|
||||
resource = CanCan::ControllerResource.new(@controller, :project)
|
||||
resource.load_resource
|
||||
@@ -91,8 +93,24 @@ describe CanCan::ControllerResource do
|
||||
@controller.instance_variable_defined?(:@projects).should be_false
|
||||
end
|
||||
|
||||
it "should not authorize single resource in collection action" do
|
||||
@params[:action] = "index"
|
||||
@controller.instance_variable_set(:@project, :some_project)
|
||||
stub(@controller).authorize!(:index, Project) { raise CanCan::AccessDenied }
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||
end
|
||||
|
||||
it "should authorize parent resource in collection action" do
|
||||
@params[:action] = "index"
|
||||
@controller.instance_variable_set(:@category, :some_category)
|
||||
stub(@controller).authorize!(:show, :some_category) { raise CanCan::AccessDenied }
|
||||
resource = CanCan::ControllerResource.new(@controller, :category, :parent => true)
|
||||
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||
end
|
||||
|
||||
it "should perform authorization using controller action and loaded model" do
|
||||
@params[:action] = "show"
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
@controller.instance_variable_set(:@project, :some_project)
|
||||
stub(@controller).authorize!(:show, :some_project) { raise CanCan::AccessDenied }
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
@@ -100,27 +118,36 @@ describe CanCan::ControllerResource do
|
||||
end
|
||||
|
||||
it "should perform authorization using controller action and non loaded model" do
|
||||
@params[:action] = "show"
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
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"
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
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"
|
||||
it "should not build a single resource when on custom collection action even with id" do
|
||||
@params.merge!(:action => "sort", :id => 123)
|
||||
resource = CanCan::ControllerResource.new(@controller, :collection => [:sort, :list])
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
end
|
||||
|
||||
it "should load a collection resource when on custom action with no id param" do
|
||||
stub(Project).accessible_by(@ability, :sort) { :found_projects }
|
||||
@params[:action] = "sort"
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
resource.load_resource
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
@controller.instance_variable_get(:@projects).should == :found_projects
|
||||
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 }
|
||||
@@ -232,7 +259,7 @@ describe CanCan::ControllerResource do
|
||||
end
|
||||
|
||||
it "should find record through has_one association with :singleton option" do
|
||||
@params.merge!(:action => "show")
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
category = Object.new
|
||||
@controller.instance_variable_set(:@category, category)
|
||||
stub(category).project { :some_project }
|
||||
@@ -241,14 +268,14 @@ describe CanCan::ControllerResource do
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "should build record through has_one association with :singleton option" do
|
||||
it "should not build record through has_one association with :singleton option because it can cause it to delete it in the database" do
|
||||
@params.merge!(:action => "create", :project => {:name => "foobar"})
|
||||
category = Object.new
|
||||
category = Category.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"
|
||||
@controller.instance_variable_get(:@project).category.should == category
|
||||
end
|
||||
|
||||
it "should find record through has_one association with :singleton and :shallow options" do
|
||||
@@ -266,10 +293,10 @@ describe CanCan::ControllerResource do
|
||||
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||
end
|
||||
|
||||
it "should only authorize :read action on parent resource" do
|
||||
it "should only authorize :show action on parent resource" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "new", :project_id => project.id)
|
||||
stub(@controller).authorize!(:read, project) { raise CanCan::AccessDenied }
|
||||
stub(@controller).authorize!(:show, project) { raise CanCan::AccessDenied }
|
||||
resource = CanCan::ControllerResource.new(@controller, :project, :parent => true)
|
||||
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||
end
|
||||
@@ -323,4 +350,52 @@ describe CanCan::ControllerResource do
|
||||
CanCan::ControllerResource.new(@controller, :nested => :project)
|
||||
}.should raise_error(CanCan::ImplementationRemoved)
|
||||
end
|
||||
|
||||
it "should skip resource behavior for :only actions in array" do
|
||||
stub(@controller_class).cancan_skipper { {:load => {nil => {:only => [:index, :show]}}} }
|
||||
@params.merge!(:action => "index")
|
||||
CanCan::ControllerResource.new(@controller).skip?(:load).should be_true
|
||||
CanCan::ControllerResource.new(@controller, :some_resource).skip?(:load).should be_false
|
||||
@params.merge!(:action => "show")
|
||||
CanCan::ControllerResource.new(@controller).skip?(:load).should be_true
|
||||
@params.merge!(:action => "other_action")
|
||||
CanCan::ControllerResource.new(@controller).skip?(:load).should be_false
|
||||
end
|
||||
|
||||
it "should skip resource behavior for :only one action on resource" do
|
||||
stub(@controller_class).cancan_skipper { {:authorize => {:project => {:only => :index}}} }
|
||||
@params.merge!(:action => "index")
|
||||
CanCan::ControllerResource.new(@controller).skip?(:authorize).should be_false
|
||||
CanCan::ControllerResource.new(@controller, :project).skip?(:authorize).should be_true
|
||||
@params.merge!(:action => "other_action")
|
||||
CanCan::ControllerResource.new(@controller, :project).skip?(:authorize).should be_false
|
||||
end
|
||||
|
||||
it "should skip resource behavior :except actions in array" do
|
||||
stub(@controller_class).cancan_skipper { {:load => {nil => {:except => [:index, :show]}}} }
|
||||
@params.merge!(:action => "index")
|
||||
CanCan::ControllerResource.new(@controller).skip?(:load).should be_false
|
||||
@params.merge!(:action => "show")
|
||||
CanCan::ControllerResource.new(@controller).skip?(:load).should be_false
|
||||
@params.merge!(:action => "other_action")
|
||||
CanCan::ControllerResource.new(@controller).skip?(:load).should be_true
|
||||
CanCan::ControllerResource.new(@controller, :some_resource).skip?(:load).should be_false
|
||||
end
|
||||
|
||||
it "should skip resource behavior :except one action on resource" do
|
||||
stub(@controller_class).cancan_skipper { {:authorize => {:project => {:except => :index}}} }
|
||||
@params.merge!(:action => "index")
|
||||
CanCan::ControllerResource.new(@controller, :project).skip?(:authorize).should be_false
|
||||
@params.merge!(:action => "other_action")
|
||||
CanCan::ControllerResource.new(@controller).skip?(:authorize).should be_false
|
||||
CanCan::ControllerResource.new(@controller, :project).skip?(:authorize).should be_true
|
||||
end
|
||||
|
||||
it "should skip loading and authorization" do
|
||||
stub(@controller_class).cancan_skipper { {:authorize => {nil => {}}, :load => {nil => {}}} }
|
||||
@params.merge!(:action => "new")
|
||||
resource = CanCan::ControllerResource.new(@controller)
|
||||
lambda { resource.load_and_authorize_resource }.should_not raise_error
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
end
|
||||
end
|
||||
|
||||
@@ -3,14 +3,16 @@ require "spec_helper"
|
||||
describe CanCan::InheritedResource do
|
||||
before(:each) do
|
||||
@params = HashWithIndifferentAccess.new(:controller => "projects")
|
||||
@controller = Object.new # simple stub for now
|
||||
@controller_class = Class.new
|
||||
@controller = @controller_class.new
|
||||
@ability = Ability.new(nil)
|
||||
stub(@controller).params { @params }
|
||||
stub(@controller).current_ability { @ability }
|
||||
stub(@controller_class).cancan_skipper { {:authorize => {}, :load => {}} }
|
||||
end
|
||||
|
||||
it "show should load resource through @controller.resource" do
|
||||
@params[:action] = "show"
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
stub(@controller).resource { :project_resource }
|
||||
CanCan::InheritedResource.new(@controller).load_resource
|
||||
@controller.instance_variable_get(:@project).should == :project_resource
|
||||
@@ -23,16 +25,16 @@ describe CanCan::InheritedResource do
|
||||
@controller.instance_variable_get(:@project).should == :project_resource
|
||||
end
|
||||
|
||||
it "index should load through @controller.parent when parent" do
|
||||
it "index should load through @controller.association_chain when parent" do
|
||||
@params[:action] = "index"
|
||||
stub(@controller).parent { :project_resource }
|
||||
stub(@controller).association_chain { @controller.instance_variable_set(:@project, :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(Project).accessible_by(@ability, :index) { :projects }
|
||||
stub(@controller).end_of_association_chain { Project }
|
||||
CanCan::InheritedResource.new(@controller).load_resource
|
||||
@controller.instance_variable_get(:@projects).should == :projects
|
||||
|
||||
263
spec/cancan/model_adapters/active_record_adapter_spec.rb
Normal file
263
spec/cancan/model_adapters/active_record_adapter_spec.rb
Normal file
@@ -0,0 +1,263 @@
|
||||
if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
|
||||
require "spec_helper"
|
||||
|
||||
RSpec.configure do |config|
|
||||
config.extend WithModel
|
||||
end
|
||||
|
||||
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
|
||||
|
||||
describe CanCan::ModelAdapters::ActiveRecordAdapter do
|
||||
with_model :category do
|
||||
table do |t|
|
||||
t.boolean "visible"
|
||||
end
|
||||
model do
|
||||
has_many :articles
|
||||
end
|
||||
end
|
||||
|
||||
with_model :article do
|
||||
table do |t|
|
||||
t.string "name"
|
||||
t.boolean "published"
|
||||
t.boolean "secret"
|
||||
t.integer "priority"
|
||||
t.integer "category_id"
|
||||
end
|
||||
model do
|
||||
belongs_to :category
|
||||
has_many :comments
|
||||
end
|
||||
end
|
||||
|
||||
with_model :comment do
|
||||
table do |t|
|
||||
t.boolean "spam"
|
||||
t.integer "article_id"
|
||||
end
|
||||
model do
|
||||
belongs_to :article
|
||||
end
|
||||
end
|
||||
|
||||
before(:each) do
|
||||
Article.delete_all
|
||||
Comment.delete_all
|
||||
@ability = Object.new
|
||||
@ability.extend(CanCan::Ability)
|
||||
@article_table = Article.table_name
|
||||
@comment_table = Comment.table_name
|
||||
end
|
||||
|
||||
it "should be for only active record classes" do
|
||||
CanCan::ModelAdapters::ActiveRecordAdapter.should_not be_for_class(Object)
|
||||
CanCan::ModelAdapters::ActiveRecordAdapter.should be_for_class(Article)
|
||||
CanCan::ModelAdapters::AbstractAdapter.adapter_class(Article).should == CanCan::ModelAdapters::ActiveRecordAdapter
|
||||
end
|
||||
|
||||
it "should not fetch any records when no abilities are defined" do
|
||||
Article.create!
|
||||
Article.accessible_by(@ability).should be_empty
|
||||
end
|
||||
|
||||
it "should fetch all articles when one can read all" do
|
||||
@ability.can :read, Article
|
||||
article = Article.create!
|
||||
Article.accessible_by(@ability).should == [article]
|
||||
end
|
||||
|
||||
it "should fetch only the articles that are published" do
|
||||
@ability.can :read, Article, :published => true
|
||||
article1 = Article.create!(:published => true)
|
||||
article2 = Article.create!(:published => false)
|
||||
Article.accessible_by(@ability).should == [article1]
|
||||
end
|
||||
|
||||
it "should fetch any articles which are published or secret" do
|
||||
@ability.can :read, Article, :published => true
|
||||
@ability.can :read, Article, :secret => true
|
||||
article1 = Article.create!(:published => true, :secret => false)
|
||||
article2 = Article.create!(:published => true, :secret => true)
|
||||
article3 = Article.create!(:published => false, :secret => true)
|
||||
article4 = Article.create!(:published => false, :secret => false)
|
||||
Article.accessible_by(@ability).should == [article1, article2, article3]
|
||||
end
|
||||
|
||||
it "should fetch only the articles that are published and not secret" do
|
||||
@ability.can :read, Article, :published => true
|
||||
@ability.cannot :read, Article, :secret => true
|
||||
article1 = Article.create!(:published => true, :secret => false)
|
||||
article2 = Article.create!(:published => true, :secret => true)
|
||||
article3 = Article.create!(:published => false, :secret => true)
|
||||
article4 = Article.create!(:published => false, :secret => false)
|
||||
Article.accessible_by(@ability).should == [article1]
|
||||
end
|
||||
|
||||
it "should only read comments for articles which are published" do
|
||||
@ability.can :read, Comment, :article => { :published => true }
|
||||
comment1 = Comment.create!(:article => Article.create!(:published => true))
|
||||
comment2 = Comment.create!(:article => Article.create!(:published => false))
|
||||
Comment.accessible_by(@ability).should == [comment1]
|
||||
end
|
||||
|
||||
it "should only read comments for visible categories through articles" do
|
||||
@ability.can :read, Comment, :article => { :category => { :visible => true } }
|
||||
comment1 = Comment.create!(:article => Article.create!(:category => Category.create!(:visible => true)))
|
||||
comment2 = Comment.create!(:article => Article.create!(:category => Category.create!(:visible => false)))
|
||||
Comment.accessible_by(@ability).should == [comment1]
|
||||
end
|
||||
|
||||
it "should allow conditions in SQL and merge with hash conditions" do
|
||||
@ability.can :read, Article, :published => true
|
||||
@ability.can :read, Article, ["secret=?", true]
|
||||
article1 = Article.create!(:published => true, :secret => false)
|
||||
article2 = Article.create!(:published => true, :secret => true)
|
||||
article3 = Article.create!(:published => false, :secret => true)
|
||||
article4 = Article.create!(:published => false, :secret => false)
|
||||
Article.accessible_by(@ability).should == [article1, article2, article3]
|
||||
end
|
||||
|
||||
it "should allow a scope for conditions" do
|
||||
@ability.can :read, Article, Article.where(:secret => true)
|
||||
article1 = Article.create!(:secret => true)
|
||||
article2 = Article.create!(:secret => false)
|
||||
Article.accessible_by(@ability).should == [article1]
|
||||
end
|
||||
|
||||
it "should raise an exception when trying to merge scope with other conditions" do
|
||||
@ability.can :read, Article, :published => true
|
||||
@ability.can :read, Article, Article.where(:secret => true)
|
||||
lambda { Article.accessible_by(@ability) }.should raise_error(CanCan::Error, "Unable to merge an Active Record scope with other conditions. Instead use a hash or SQL for read Article ability.")
|
||||
end
|
||||
|
||||
it "should not allow to fetch records when ability with just block present" do
|
||||
@ability.can :read, Article do
|
||||
false
|
||||
end
|
||||
lambda { Article.accessible_by(@ability) }.should raise_error(CanCan::Error)
|
||||
end
|
||||
|
||||
it "should not allow to check ability on object against SQL conditions without block" do
|
||||
@ability.can :read, Article, ["secret=?", true]
|
||||
lambda { @ability.can? :read, Article.new }.should raise_error(CanCan::Error)
|
||||
end
|
||||
|
||||
it "should have false conditions if no abilities match" do
|
||||
@ability.model_adapter(Article, :read).conditions.should == "'t'='f'"
|
||||
end
|
||||
|
||||
it "should return false conditions for cannot clause" do
|
||||
@ability.cannot :read, Article
|
||||
@ability.model_adapter(Article, :read).conditions.should == "'t'='f'"
|
||||
end
|
||||
|
||||
it "should return SQL for single `can` definition in front of default `cannot` condition" do
|
||||
@ability.cannot :read, Article
|
||||
@ability.can :read, Article, :published => false, :secret => true
|
||||
@ability.model_adapter(Article, :read).conditions.should orderlessly_match(%Q["#{@article_table}"."published" = 'f' AND "#{@article_table}"."secret" = 't'])
|
||||
end
|
||||
|
||||
it "should return true condition for single `can` definition in front of default `can` condition" do
|
||||
@ability.can :read, Article
|
||||
@ability.can :read, Article, :published => false, :secret => true
|
||||
@ability.model_adapter(Article, :read).conditions.should == "'t'='t'"
|
||||
end
|
||||
|
||||
it "should return `false condition` for single `cannot` definition in front of default `cannot` condition" do
|
||||
@ability.cannot :read, Article
|
||||
@ability.cannot :read, Article, :published => false, :secret => true
|
||||
@ability.model_adapter(Article, :read).conditions.should == "'t'='f'"
|
||||
end
|
||||
|
||||
it "should return `not (sql)` for single `cannot` definition in front of default `can` condition" do
|
||||
@ability.can :read, Article
|
||||
@ability.cannot :read, Article, :published => false, :secret => true
|
||||
@ability.model_adapter(Article, :read).conditions.should orderlessly_match(%Q["not (#{@article_table}"."published" = 'f' AND "#{@article_table}"."secret" = 't')])
|
||||
end
|
||||
|
||||
it "should return appropriate sql conditions in complex case" do
|
||||
@ability.can :read, Article
|
||||
@ability.can :manage, Article, :id => 1
|
||||
@ability.can :update, Article, :published => true
|
||||
@ability.cannot :update, Article, :secret => true
|
||||
@ability.model_adapter(Article, :update).conditions.should == %Q[not ("#{@article_table}"."secret" = 't') AND (("#{@article_table}"."published" = 't') OR ("#{@article_table}"."id" = 1))]
|
||||
@ability.model_adapter(Article, :manage).conditions.should == {:id => 1}
|
||||
@ability.model_adapter(Article, :read).conditions.should == "'t'='t'"
|
||||
end
|
||||
|
||||
it "should not forget conditions when calling with SQL string" do
|
||||
@ability.can :read, Article, :published => true
|
||||
@ability.can :read, Article, ['secret=?', false]
|
||||
adapter = @ability.model_adapter(Article, :read)
|
||||
2.times do
|
||||
adapter.conditions.should == %Q[(secret='f') OR ("#{@article_table}"."published" = 't')]
|
||||
end
|
||||
end
|
||||
|
||||
it "should have nil joins if no rules" do
|
||||
@ability.model_adapter(Article, :read).joins.should be_nil
|
||||
end
|
||||
|
||||
it "should have nil joins if no nested hashes specified in conditions" do
|
||||
@ability.can :read, Article, :published => false
|
||||
@ability.can :read, Article, :secret => true
|
||||
@ability.model_adapter(Article, :read).joins.should be_nil
|
||||
end
|
||||
|
||||
it "should merge separate joins into a single array" do
|
||||
@ability.can :read, Article, :project => { :blocked => false }
|
||||
@ability.can :read, Article, :company => { :admin => true }
|
||||
@ability.model_adapter(Article, :read).joins.inspect.should orderlessly_match([:company, :project].inspect)
|
||||
end
|
||||
|
||||
it "should merge same joins into a single array" do
|
||||
@ability.can :read, Article, :project => { :blocked => false }
|
||||
@ability.can :read, Article, :project => { :admin => true }
|
||||
@ability.model_adapter(Article, :read).joins.should == [:project]
|
||||
end
|
||||
|
||||
it "should restrict articles given a MetaWhere condition" do
|
||||
@ability.can :read, Article, :priority.lt => 2
|
||||
article1 = Article.create!(:priority => 1)
|
||||
article2 = Article.create!(:priority => 3)
|
||||
Article.accessible_by(@ability).should == [article1]
|
||||
@ability.should be_able_to(:read, article1)
|
||||
@ability.should_not be_able_to(:read, article2)
|
||||
end
|
||||
|
||||
it "should match any MetaWhere condition" do
|
||||
adapter = CanCan::ModelAdapters::ActiveRecordAdapter
|
||||
article1 = Article.new(:priority => 1, :name => "Hello World")
|
||||
adapter.matches_condition?(article1, :priority.eq, 1).should be_true
|
||||
adapter.matches_condition?(article1, :priority.eq, 2).should be_false
|
||||
adapter.matches_condition?(article1, :priority.eq_any, [1, 2]).should be_true
|
||||
adapter.matches_condition?(article1, :priority.eq_any, [2, 3]).should be_false
|
||||
adapter.matches_condition?(article1, :priority.eq_all, [1, 1]).should be_true
|
||||
adapter.matches_condition?(article1, :priority.eq_all, [1, 2]).should be_false
|
||||
adapter.matches_condition?(article1, :priority.ne, 2).should be_true
|
||||
adapter.matches_condition?(article1, :priority.ne, 1).should be_false
|
||||
adapter.matches_condition?(article1, :priority.in, [1, 2]).should be_true
|
||||
adapter.matches_condition?(article1, :priority.in, [2, 3]).should be_false
|
||||
adapter.matches_condition?(article1, :priority.nin, [2, 3]).should be_true
|
||||
adapter.matches_condition?(article1, :priority.nin, [1, 2]).should be_false
|
||||
adapter.matches_condition?(article1, :priority.lt, 2).should be_true
|
||||
adapter.matches_condition?(article1, :priority.lt, 1).should be_false
|
||||
adapter.matches_condition?(article1, :priority.lteq, 1).should be_true
|
||||
adapter.matches_condition?(article1, :priority.lteq, 0).should be_false
|
||||
adapter.matches_condition?(article1, :priority.gt, 0).should be_true
|
||||
adapter.matches_condition?(article1, :priority.gt, 1).should be_false
|
||||
adapter.matches_condition?(article1, :priority.gteq, 1).should be_true
|
||||
adapter.matches_condition?(article1, :priority.gteq, 2).should be_false
|
||||
adapter.matches_condition?(article1, :name.like, "%ello worl%").should be_true
|
||||
adapter.matches_condition?(article1, :name.like, "hello world").should be_true
|
||||
adapter.matches_condition?(article1, :name.like, "hello%").should be_true
|
||||
adapter.matches_condition?(article1, :name.like, "h%d").should be_true
|
||||
adapter.matches_condition?(article1, :name.like, "%helo%").should be_false
|
||||
adapter.matches_condition?(article1, :name.like, "hello").should be_false
|
||||
adapter.matches_condition?(article1, :name.like, "hello.world").should be_false
|
||||
adapter.matches_condition?(article1, :name.nlike, "%helo%").should be_true
|
||||
adapter.matches_condition?(article1, :name.nlike, "%ello worl%").should be_false
|
||||
end
|
||||
end
|
||||
end
|
||||
115
spec/cancan/model_adapters/data_mapper_adapter_spec.rb
Normal file
115
spec/cancan/model_adapters/data_mapper_adapter_spec.rb
Normal file
@@ -0,0 +1,115 @@
|
||||
if ENV["MODEL_ADAPTER"] == "data_mapper"
|
||||
require "spec_helper"
|
||||
|
||||
DataMapper.setup(:default, 'sqlite::memory:')
|
||||
|
||||
class Article
|
||||
include DataMapper::Resource
|
||||
property :id, Serial
|
||||
property :published, Boolean, :default => false
|
||||
property :secret, Boolean, :default => false
|
||||
property :priority, Integer
|
||||
has n, :comments
|
||||
end
|
||||
|
||||
class Comment
|
||||
include DataMapper::Resource
|
||||
property :id, Serial
|
||||
property :spam, Boolean, :default => false
|
||||
belongs_to :article
|
||||
end
|
||||
|
||||
DataMapper.finalize
|
||||
DataMapper.auto_migrate!
|
||||
|
||||
describe CanCan::ModelAdapters::DataMapperAdapter do
|
||||
before(:each) do
|
||||
Article.destroy
|
||||
Comment.destroy
|
||||
@ability = Object.new
|
||||
@ability.extend(CanCan::Ability)
|
||||
end
|
||||
|
||||
it "should be for only data mapper classes" do
|
||||
CanCan::ModelAdapters::DataMapperAdapter.should_not be_for_class(Object)
|
||||
CanCan::ModelAdapters::DataMapperAdapter.should be_for_class(Article)
|
||||
CanCan::ModelAdapters::AbstractAdapter.adapter_class(Article).should == CanCan::ModelAdapters::DataMapperAdapter
|
||||
end
|
||||
|
||||
it "should not fetch any records when no abilities are defined" do
|
||||
Article.create
|
||||
Article.accessible_by(@ability).should be_empty
|
||||
end
|
||||
|
||||
it "should fetch all articles when one can read all" do
|
||||
@ability.can :read, Article
|
||||
article = Article.create
|
||||
Article.accessible_by(@ability).should == [article]
|
||||
end
|
||||
|
||||
it "should fetch only the articles that are published" do
|
||||
@ability.can :read, Article, :published => true
|
||||
article1 = Article.create(:published => true)
|
||||
article2 = Article.create(:published => false)
|
||||
Article.accessible_by(@ability).should == [article1]
|
||||
end
|
||||
|
||||
it "should fetch any articles which are published or secret" do
|
||||
@ability.can :read, Article, :published => true
|
||||
@ability.can :read, Article, :secret => true
|
||||
article1 = Article.create(:published => true, :secret => false)
|
||||
article2 = Article.create(:published => true, :secret => true)
|
||||
article3 = Article.create(:published => false, :secret => true)
|
||||
article4 = Article.create(:published => false, :secret => false)
|
||||
Article.accessible_by(@ability).should == [article1, article2, article3]
|
||||
end
|
||||
|
||||
it "should fetch only the articles that are published and not secret" do
|
||||
pending "the `cannot` may require some custom SQL, maybe abstract out from Active Record adapter"
|
||||
@ability.can :read, Article, :published => true
|
||||
@ability.cannot :read, Article, :secret => true
|
||||
article1 = Article.create(:published => true, :secret => false)
|
||||
article2 = Article.create(:published => true, :secret => true)
|
||||
article3 = Article.create(:published => false, :secret => true)
|
||||
article4 = Article.create(:published => false, :secret => false)
|
||||
Article.accessible_by(@ability).should == [article1]
|
||||
end
|
||||
|
||||
it "should only read comments for articles which are published" do
|
||||
@ability.can :read, Comment, :article => { :published => true }
|
||||
comment1 = Comment.create(:article => Article.create!(:published => true))
|
||||
comment2 = Comment.create(:article => Article.create!(:published => false))
|
||||
Comment.accessible_by(@ability).should == [comment1]
|
||||
end
|
||||
|
||||
it "should allow conditions in SQL and merge with hash conditions" do
|
||||
@ability.can :read, Article, :published => true
|
||||
@ability.can :read, Article, ["secret=?", true]
|
||||
article1 = Article.create(:published => true, :secret => false)
|
||||
article4 = Article.create(:published => false, :secret => false)
|
||||
Article.accessible_by(@ability).should == [article1]
|
||||
end
|
||||
|
||||
it "should match gt comparison" do
|
||||
@ability.can :read, Article, :priority.gt => 3
|
||||
article1 = Article.create(:priority => 4)
|
||||
article2 = Article.create(:priority => 3)
|
||||
Article.accessible_by(@ability).should == [article1]
|
||||
@ability.should be_able_to(:read, article1)
|
||||
@ability.should_not be_able_to(:read, article2)
|
||||
end
|
||||
|
||||
it "should match gte comparison" do
|
||||
@ability.can :read, Article, :priority.gte => 3
|
||||
article1 = Article.create(:priority => 4)
|
||||
article2 = Article.create(:priority => 3)
|
||||
article3 = Article.create(:priority => 2)
|
||||
Article.accessible_by(@ability).should == [article1, article2]
|
||||
@ability.should be_able_to(:read, article1)
|
||||
@ability.should be_able_to(:read, article2)
|
||||
@ability.should_not be_able_to(:read, article3)
|
||||
end
|
||||
|
||||
# TODO: add more comparison specs
|
||||
end
|
||||
end
|
||||
7
spec/cancan/model_adapters/default_adapter_spec.rb
Normal file
7
spec/cancan/model_adapters/default_adapter_spec.rb
Normal file
@@ -0,0 +1,7 @@
|
||||
require "spec_helper"
|
||||
|
||||
describe CanCan::ModelAdapters::DefaultAdapter do
|
||||
it "should be default for generic classes" do
|
||||
CanCan::ModelAdapters::AbstractAdapter.adapter_class(Object).should == CanCan::ModelAdapters::DefaultAdapter
|
||||
end
|
||||
end
|
||||
185
spec/cancan/model_adapters/mongoid_adapter_spec.rb
Normal file
185
spec/cancan/model_adapters/mongoid_adapter_spec.rb
Normal file
@@ -0,0 +1,185 @@
|
||||
if ENV["MODEL_ADAPTER"] == "mongoid"
|
||||
require "spec_helper"
|
||||
|
||||
class MongoidCategory
|
||||
include Mongoid::Document
|
||||
|
||||
references_many :mongoid_projects
|
||||
end
|
||||
|
||||
class MongoidProject
|
||||
include Mongoid::Document
|
||||
|
||||
referenced_in :mongoid_category
|
||||
end
|
||||
|
||||
Mongoid.configure do |config|
|
||||
config.master = Mongo::Connection.new('127.0.0.1', 27017).db("cancan_mongoid_spec")
|
||||
end
|
||||
|
||||
describe CanCan::ModelAdapters::MongoidAdapter do
|
||||
context "Mongoid defined" do
|
||||
before(:each) do
|
||||
@ability = Object.new
|
||||
@ability.extend(CanCan::Ability)
|
||||
end
|
||||
|
||||
after(:each) do
|
||||
Mongoid.master.collections.select do |collection|
|
||||
collection.name !~ /system/
|
||||
end.each(&:drop)
|
||||
end
|
||||
|
||||
it "should be for only Mongoid classes" do
|
||||
CanCan::ModelAdapters::MongoidAdapter.should_not be_for_class(Object)
|
||||
CanCan::ModelAdapters::MongoidAdapter.should be_for_class(MongoidProject)
|
||||
CanCan::ModelAdapters::AbstractAdapter.adapter_class(MongoidProject).should == CanCan::ModelAdapters::MongoidAdapter
|
||||
end
|
||||
|
||||
it "should compare properties on mongoid documents with the conditions hash" do
|
||||
model = MongoidProject.new
|
||||
@ability.can :read, MongoidProject, :id => model.id
|
||||
@ability.should be_able_to(:read, model)
|
||||
end
|
||||
|
||||
it "should return [] when no ability is defined so no records are found" do
|
||||
MongoidProject.create(:title => 'Sir')
|
||||
MongoidProject.create(:title => 'Lord')
|
||||
MongoidProject.create(:title => 'Dude')
|
||||
|
||||
MongoidProject.accessible_by(@ability, :read).entries.should == []
|
||||
end
|
||||
|
||||
it "should return the correct records based on the defined ability" do
|
||||
@ability.can :read, MongoidProject, :title => "Sir"
|
||||
sir = MongoidProject.create(:title => 'Sir')
|
||||
lord = MongoidProject.create(:title => 'Lord')
|
||||
dude = MongoidProject.create(:title => 'Dude')
|
||||
|
||||
MongoidProject.accessible_by(@ability, :read).entries.should == [sir]
|
||||
end
|
||||
|
||||
it "should return everything when the defined ability is manage all" do
|
||||
@ability.can :manage, :all
|
||||
sir = MongoidProject.create(:title => 'Sir')
|
||||
lord = MongoidProject.create(:title => 'Lord')
|
||||
dude = MongoidProject.create(:title => 'Dude')
|
||||
|
||||
MongoidProject.accessible_by(@ability, :read).entries.should == [sir, lord, dude]
|
||||
end
|
||||
|
||||
|
||||
describe "Mongoid::Criteria where clause Symbol extensions using MongoDB expressions" do
|
||||
it "should handle :field.in" do
|
||||
obj = MongoidProject.create(:title => 'Sir')
|
||||
@ability.can :read, MongoidProject, :title.in => ["Sir", "Madam"]
|
||||
@ability.can?(:read, obj).should == true
|
||||
MongoidProject.accessible_by(@ability, :read).should == [obj]
|
||||
|
||||
obj2 = MongoidProject.create(:title => 'Lord')
|
||||
@ability.can?(:read, obj2).should == false
|
||||
end
|
||||
|
||||
describe "activates only when there are Criteria in the hash" do
|
||||
it "Calls where on the model class when there are criteria" do
|
||||
obj = MongoidProject.create(:title => 'Bird')
|
||||
@conditions = {:title.nin => ["Fork", "Spoon"]}
|
||||
|
||||
@ability.can :read, MongoidProject, @conditions
|
||||
@ability.should be_able_to(:read, obj)
|
||||
end
|
||||
it "Calls the base version if there are no mongoid criteria" do
|
||||
obj = MongoidProject.new(:title => 'Bird')
|
||||
@conditions = {:id => obj.id}
|
||||
@ability.can :read, MongoidProject, @conditions
|
||||
@ability.should be_able_to(:read, obj)
|
||||
end
|
||||
end
|
||||
|
||||
it "should handle :field.nin" do
|
||||
obj = MongoidProject.create(:title => 'Sir')
|
||||
@ability.can :read, MongoidProject, :title.nin => ["Lord", "Madam"]
|
||||
@ability.can?(:read, obj).should == true
|
||||
MongoidProject.accessible_by(@ability, :read).should == [obj]
|
||||
|
||||
obj2 = MongoidProject.create(:title => 'Lord')
|
||||
@ability.can?(:read, obj2).should == false
|
||||
end
|
||||
|
||||
it "should handle :field.size" do
|
||||
obj = MongoidProject.create(:titles => ['Palatin', 'Margrave'])
|
||||
@ability.can :read, MongoidProject, :titles.size => 2
|
||||
@ability.can?(:read, obj).should == true
|
||||
MongoidProject.accessible_by(@ability, :read).should == [obj]
|
||||
|
||||
obj2 = MongoidProject.create(:titles => ['Palatin', 'Margrave', 'Marquis'])
|
||||
@ability.can?(:read, obj2).should == false
|
||||
end
|
||||
|
||||
it "should handle :field.exists" do
|
||||
obj = MongoidProject.create(:titles => ['Palatin', 'Margrave'])
|
||||
@ability.can :read, MongoidProject, :titles.exists => true
|
||||
@ability.can?(:read, obj).should == true
|
||||
MongoidProject.accessible_by(@ability, :read).should == [obj]
|
||||
|
||||
obj2 = MongoidProject.create
|
||||
@ability.can?(:read, obj2).should == false
|
||||
end
|
||||
|
||||
it "should handle :field.gt" do
|
||||
obj = MongoidProject.create(:age => 50)
|
||||
@ability.can :read, MongoidProject, :age.gt => 45
|
||||
@ability.can?(:read, obj).should == true
|
||||
MongoidProject.accessible_by(@ability, :read).should == [obj]
|
||||
|
||||
obj2 = MongoidProject.create(:age => 40)
|
||||
@ability.can?(:read, obj2).should == false
|
||||
end
|
||||
|
||||
it "should handle instance not saved to database" do
|
||||
obj = MongoidProject.new(:title => 'Sir')
|
||||
@ability.can :read, MongoidProject, :title.in => ["Sir", "Madam"]
|
||||
@ability.can?(:read, obj).should == true
|
||||
|
||||
# accessible_by only returns saved records
|
||||
MongoidProject.accessible_by(@ability, :read).entries.should == []
|
||||
|
||||
obj2 = MongoidProject.new(:title => 'Lord')
|
||||
@ability.can?(:read, obj2).should == false
|
||||
end
|
||||
end
|
||||
|
||||
it "should call where with matching ability conditions" do
|
||||
obj = MongoidProject.create(:foo => {:bar => 1})
|
||||
@ability.can :read, MongoidProject, :foo => {:bar => 1}
|
||||
MongoidProject.accessible_by(@ability, :read).entries.first.should == obj
|
||||
end
|
||||
|
||||
it "should exclude from the result if set to cannot" do
|
||||
obj = MongoidProject.create(:bar => 1)
|
||||
obj2 = MongoidProject.create(:bar => 2)
|
||||
@ability.can :read, MongoidProject
|
||||
@ability.cannot :read, MongoidProject, :bar => 2
|
||||
MongoidProject.accessible_by(@ability, :read).entries.should == [obj]
|
||||
end
|
||||
|
||||
it "should combine the rules" do
|
||||
obj = MongoidProject.create(:bar => 1)
|
||||
obj2 = MongoidProject.create(:bar => 2)
|
||||
obj3 = MongoidProject.create(:bar => 3)
|
||||
@ability.can :read, MongoidProject, :bar => 1
|
||||
@ability.can :read, MongoidProject, :bar => 2
|
||||
MongoidProject.accessible_by(@ability, :read).entries.should =~ [obj, obj2]
|
||||
end
|
||||
|
||||
it "should not allow to fetch records when ability with just block present" do
|
||||
@ability.can :read, MongoidProject do
|
||||
false
|
||||
end
|
||||
lambda {
|
||||
MongoidProject.accessible_by(@ability)
|
||||
}.should raise_error(CanCan::Error)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,107 +0,0 @@
|
||||
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
|
||||
39
spec/cancan/rule_spec.rb
Normal file
39
spec/cancan/rule_spec.rb
Normal file
@@ -0,0 +1,39 @@
|
||||
require "spec_helper"
|
||||
|
||||
# Most of Rule functionality is tested in Ability specs
|
||||
describe CanCan::Rule do
|
||||
before(:each) do
|
||||
@conditions = {}
|
||||
@rule = CanCan::Rule.new(true, :read, Integer, @conditions, nil)
|
||||
end
|
||||
|
||||
it "should return no association joins if none exist" do
|
||||
@rule.associations_hash.should == {}
|
||||
end
|
||||
|
||||
it "should return no association for joins if just attributes" do
|
||||
@conditions[:foo] = :bar
|
||||
@rule.associations_hash.should == {}
|
||||
end
|
||||
|
||||
it "should return single association for joins" do
|
||||
@conditions[:foo] = {:bar => 1}
|
||||
@rule.associations_hash.should == {:foo => {}}
|
||||
end
|
||||
|
||||
it "should return multiple associations for joins" do
|
||||
@conditions[:foo] = {:bar => 1}
|
||||
@conditions[:test] = {1 => 2}
|
||||
@rule.associations_hash.should == {:foo => {}, :test => {}}
|
||||
end
|
||||
|
||||
it "should return nested associations for joins" do
|
||||
@conditions[:foo] = {:bar => {1 => 2}}
|
||||
@rule.associations_hash.should == {:foo => {:bar => {}}}
|
||||
end
|
||||
|
||||
it "should return no association joins if conditions is nil" do
|
||||
rule = CanCan::Rule.new(true, :read, Integer, nil, nil)
|
||||
rule.associations_hash.should == {}
|
||||
end
|
||||
end
|
||||
@@ -1,6 +1,8 @@
|
||||
require 'rubygems'
|
||||
require 'bundler/setup'
|
||||
|
||||
Bundler.require(:default)
|
||||
|
||||
require 'supermodel' # shouldn't Bundler do this already?
|
||||
require 'active_support/all'
|
||||
require 'matchers'
|
||||
@@ -27,28 +29,5 @@ 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
|
||||
attr_accessor :category # why doesn't SuperModel do this automatically?
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user