Compare commits
99 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
872e4cfba8 | ||
|
|
787511a208 | ||
|
|
92995d791e | ||
|
|
ebf77ed647 | ||
|
|
9a7c427373 | ||
|
|
cf263c105d | ||
|
|
79180de372 | ||
|
|
dbcd93e095 | ||
|
|
d256aeb26e | ||
|
|
25bf479f48 | ||
|
|
ab82dcbc8f | ||
|
|
be74df0548 | ||
|
|
f901c367fc | ||
|
|
67cd83dd96 | ||
|
|
6c3e87eea9 | ||
|
|
fa766e71ed | ||
|
|
b0cec5251c | ||
|
|
18b45d5cfc | ||
|
|
8f49f28713 | ||
|
|
12037d7f43 | ||
|
|
1f81b8dd1e | ||
|
|
3391c5a0d7 | ||
|
|
c11ffb6fd1 | ||
|
|
264e2d2b68 | ||
|
|
ebef3cc745 | ||
|
|
cef55c95e7 | ||
|
|
7e0e72276e | ||
|
|
ff9a91705b | ||
|
|
a0f73fe0f7 | ||
|
|
e2c341b8d3 | ||
|
|
f236b1b5a4 | ||
|
|
0b270f2d0f | ||
|
|
961df90ecd | ||
|
|
4eee637270 | ||
|
|
a5ff826e40 | ||
|
|
9d915457af | ||
|
|
158c908d3b | ||
|
|
bf9b8ad1a6 | ||
|
|
1af6c6f395 | ||
|
|
7c5243321f | ||
|
|
721939babd | ||
|
|
a744377ac9 | ||
|
|
1be5bf7a57 | ||
|
|
c88cb8f459 | ||
|
|
737f8acff5 | ||
|
|
a5f838a964 | ||
|
|
66314a89f8 | ||
|
|
b1fb179aaf | ||
|
|
6105edc6a7 | ||
|
|
04b523eea4 | ||
|
|
5a353c1cba | ||
|
|
4fe44af45d |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1 +1,5 @@
|
|||||||
|
*.swp
|
||||||
|
**/*.swp
|
||||||
*.gem
|
*.gem
|
||||||
|
Gemfile.lock
|
||||||
|
.bundle
|
||||||
|
|||||||
23
.rvmrc
Normal file
23
.rvmrc
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
# adapted from: http://rvm.beginrescueend.com/workflow/rvmrc/
|
||||||
|
|
||||||
|
ruby_string="1.8.7"
|
||||||
|
gemset_name="cancan"
|
||||||
|
|
||||||
|
if rvm list strings | grep -q "${ruby_string}" ; then
|
||||||
|
|
||||||
|
# Load or create the specified environment
|
||||||
|
if [[ -d "${rvm_path:-$HOME/.rvm}/environments" \
|
||||||
|
&& -s "${rvm_path:-$HOME/.rvm}/environments/${ruby_string}@${gemset_name}" ]] ; then
|
||||||
|
\. "${rvm_path:-$HOME/.rvm}/environments/${ruby_string}@${gemset_name}"
|
||||||
|
else
|
||||||
|
rvm --create "${ruby_string}@${gemset_name}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
else
|
||||||
|
|
||||||
|
# Notify the user to install the desired interpreter before proceeding.
|
||||||
|
echo "${ruby_string} was not found, please run 'rvm install ${ruby_string}' and then cd back into the project directory."
|
||||||
|
|
||||||
|
fi
|
||||||
@@ -1,3 +1,81 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
* Adding :through_association option to load_resource (thanks hunterae) - see issue #171
|
||||||
|
|
||||||
|
* The :shallow option now works with the :singleton option (thanks nandalopes) - see issue #187
|
||||||
|
|
||||||
|
* Play nicely with quick_scopes gem (thanks ramontayag) - see issue #183
|
||||||
|
|
||||||
|
* Fix odd behavior when "cache_classes = false" (thanks mphalliday) - see issue #174
|
||||||
|
|
||||||
|
|
||||||
|
1.4.0 (October 5, 2010)
|
||||||
|
|
||||||
|
* Adding Gemfile; to get specs running just +bundle+ and +rake+ - see issue #163
|
||||||
|
|
||||||
|
* Stop at 'cannot' definition when there are no conditions - see issue #161
|
||||||
|
|
||||||
|
* The :through option will now call a method with that name if instance variable doesn't exist - see issue #146
|
||||||
|
|
||||||
|
* Adding :shallow option to load_resource to bring back old behavior of fetching a child without a parent
|
||||||
|
|
||||||
|
* Raise AccessDenied error when loading a child and parent resource isn't found
|
||||||
|
|
||||||
|
* Abilities defined on a module will apply to anything that includes that module - see issue #150 and #152
|
||||||
|
|
||||||
|
* Abilities can be defined with a string of SQL in addition to a block so accessible_by works with a block - see issue #150
|
||||||
|
|
||||||
|
* Adding better support for InheritedResource - see issue #23
|
||||||
|
|
||||||
|
* Loading the collection instance variable (for index action) using accessible_by - see issue #137
|
||||||
|
|
||||||
|
* Adding action and subject variables to I18n unauthorized message - closes #142
|
||||||
|
|
||||||
|
* Adding check_authorization and skip_authorization controller class methods to ensure authorization is performed (thanks justinko) - see issue #135
|
||||||
|
|
||||||
|
* Setting initial attributes based on ability conditions in new/create actions - see issue #114
|
||||||
|
|
||||||
|
* Check parent attributes for nested association in index action - see issue #121
|
||||||
|
|
||||||
|
* Supporting nesting in can? method using hash - see issue #121
|
||||||
|
|
||||||
|
* Adding I18n support for Access Denied messages (thanks EppO) - see issue #103
|
||||||
|
|
||||||
|
* Passing no arguments to +can+ definition will pass action, class, and object to block - see issue #129
|
||||||
|
|
||||||
|
* Don't pass action to block in +can+ definition when using :+manage+ option - see issue #129
|
||||||
|
|
||||||
|
* No longer calling block in +can+ definition when checking on class - see issue #116
|
||||||
|
|
||||||
|
|
||||||
|
1.3.4 (August 31, 2010)
|
||||||
|
|
||||||
|
* Don't stop at +cannot+ with hash conditions when checking class (thanks tamoya) - see issue #131
|
||||||
|
|
||||||
|
|
||||||
1.3.3 (August 20, 2010)
|
1.3.3 (August 20, 2010)
|
||||||
|
|
||||||
* Switching to Rspec namespace to remove deprecation warning in Rspec 2 - see issue #119
|
* Switching to Rspec namespace to remove deprecation warning in Rspec 2 - see issue #119
|
||||||
|
|||||||
19
Gemfile
Normal file
19
Gemfile
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
source "http://rubygems.org"
|
||||||
|
|
||||||
|
case ENV["MODEL_ADAPTER"]
|
||||||
|
when nil, "active_record"
|
||||||
|
gem "sqlite3-ruby", :require => "sqlite3"
|
||||||
|
gem "activerecord", :require => "active_record"
|
||||||
|
gem "with_model"
|
||||||
|
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.19"
|
||||||
|
else
|
||||||
|
raise "Unknown model adapter: #{ENV["MODEL_ADAPTER"]}"
|
||||||
|
end
|
||||||
|
|
||||||
|
gemspec
|
||||||
2
LICENSE
2
LICENSE
@@ -1,4 +1,4 @@
|
|||||||
Copyright (c) 2009 Ryan Bates
|
Copyright (c) 2011 Ryan Bates
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
a copy of this software and associated documentation files (the
|
a copy of this software and associated documentation files (the
|
||||||
|
|||||||
122
README.rdoc
122
README.rdoc
@@ -1,52 +1,42 @@
|
|||||||
= CanCan
|
= 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 solution for Ruby on Rails for restricting what a given user is allowed to access throughout the application. It does not care how your user roles are defined, it simply focusses on keeping permission logic in a single location (the +Ability+ class) so it is not duplicated across controllers, views, and database queries.
|
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.
|
||||||
|
|
||||||
By default, the +current_user+ method is required, so if you have not already, set up some authentication (such as Authlogic[http://github.com/binarylogic/authlogic] or Devise[http://github.com/plataformatec/devise]). See {Changing Defaults}[http://wiki.github.com/ryanb/cancan/changing-defaults] if you need different behavior.
|
|
||||||
|
|
||||||
|
|
||||||
== Installation
|
== Installation
|
||||||
|
|
||||||
To install CanCan, include the gem in the environment.rb in Rails 2.3.
|
In <b>Rails 3</b>, add this to your Gemfile.
|
||||||
|
|
||||||
config.gem "cancan"
|
|
||||||
|
|
||||||
Or the Gemfile in Rails 3.
|
|
||||||
|
|
||||||
gem "cancan"
|
gem "cancan"
|
||||||
|
|
||||||
Alternatively it can be installed as a plugin.
|
In <b>Rails 2</b>, add this to your environment.rb file.
|
||||||
|
|
||||||
script/plugin install git://github.com/ryanb/cancan.git
|
config.gem "cancan"
|
||||||
|
|
||||||
|
Alternatively, you can install it as a plugin.
|
||||||
|
|
||||||
|
rails plugin install git://github.com/ryanb/cancan.git
|
||||||
|
|
||||||
|
|
||||||
== Getting Started
|
== Getting Started
|
||||||
|
|
||||||
First, define a class called +Ability+ in "models/ability.rb" or anywhere else in the load path. It should look something like this.
|
CanCan expects a +current_user+ method to exist in controllers. 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 to customize this behavior.
|
||||||
|
|
||||||
class Ability
|
Next, make an +Ability+ class. CanCan 1.5 includes a generator for this.
|
||||||
include CanCan::Ability
|
|
||||||
|
|
||||||
def initialize(user)
|
rails g cancan:ability
|
||||||
if user.admin?
|
|
||||||
can :manage, :all
|
|
||||||
else
|
|
||||||
can :read, :all
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
This is where all permissions will go. See the "Defining Abilities" section below for more information.
|
This is where the user permission will be defined. See the comments in models/ability.rb and {Defining Abilities}[https://github.com/ryanb/cancan/wiki/defining-abilities] for details.
|
||||||
|
|
||||||
The current user's permissions can be accessed using the "can?" and "cannot?" methods in the view and controller.
|
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 %>
|
<% if can? :update, @article %>
|
||||||
<%= link_to "Edit", edit_article_path(@article) %>
|
<%= link_to "Edit", edit_article_path(@article) %>
|
||||||
<% end %>
|
<% 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 "authorize!" method in the controller will raise an exception if the user is not able to perform the given action.
|
||||||
|
|
||||||
@@ -65,88 +55,38 @@ Setting this for every action can be tedious, therefore the +load_and_authorize_
|
|||||||
end
|
end
|
||||||
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.
|
||||||
|
|
||||||
If the user authorization fails, a CanCan::AccessDenied exception will be raised. You can catch this and modify its behavior in the +ApplicationController+.
|
If the user authorization fails, a <tt>CanCan::AccessDenied</tt> exception will be raised. You can catch this and modify its behavior in the +ApplicationController+.
|
||||||
|
|
||||||
class ApplicationController < ActionController::Base
|
class ApplicationController < ActionController::Base
|
||||||
rescue_from CanCan::AccessDenied do |exception|
|
rescue_from CanCan::AccessDenied do |exception|
|
||||||
flash[:error] = exception.message
|
flash[:alert] = exception.message
|
||||||
redirect_to root_url
|
redirect_to root_url
|
||||||
end
|
end
|
||||||
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
|
== Wiki Docs
|
||||||
|
|
||||||
As shown above, the +Ability+ class is where all user permissions are defined. The user model is passed into the initialize method so the permissions can be modified based on any user attributes. CanCan makes no assumptions about how roles are handled in your application. See {Role Based Authorization}[http://wiki.github.com/ryanb/cancan/role-based-authorization] for an example.
|
* {Upgrading to 1.5}[https://github.com/ryanb/cancan/wiki/Upgrading-to-1.5]
|
||||||
|
* {Defining Abilities}[https://github.com/ryanb/cancan/wiki/Defining-Abilities]
|
||||||
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.
|
* {Checking Abilities}[https://github.com/ryanb/cancan/wiki/Checking-Abilities]
|
||||||
|
* {Authorizing Controller Actions}[https://github.com/ryanb/cancan/wiki/Authorizing-Controller-Actions]
|
||||||
can :update, Article
|
* {Exception Handling}[https://github.com/ryanb/cancan/wiki/Exception-Handling]
|
||||||
|
* {Changing Defaults}[https://github.com/ryanb/cancan/wiki/Changing-Defaults]
|
||||||
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.
|
* {See more}[https://github.com/ryanb/cancan/wiki]
|
||||||
|
|
||||||
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 restrict what the user is able to access. Here the user will only have permission to read active projects which he owns.
|
|
||||||
|
|
||||||
can :read, Project, :active => true, :user_id => user.id
|
|
||||||
|
|
||||||
See {Defining Abilities with Hashes}[http://wiki.github.com/ryanb/cancan/defining-abilities-with-hashes] for more information.
|
|
||||||
|
|
||||||
Blocks can also be used if you need more control.
|
|
||||||
|
|
||||||
can :update, Project do |project|
|
|
||||||
project && project.groups.include?(user.group)
|
|
||||||
end
|
|
||||||
|
|
||||||
If the block returns true then the user has that :+update+ ability for that project, otherwise he will be denied access. See {Defining Abilities with Blocks}[http://wiki.github.com/ryanb/cancan/defining-abilities-with-blocks] for more information.
|
|
||||||
|
|
||||||
|
|
||||||
== Aliasing Actions
|
== Questions or Problems?
|
||||||
|
|
||||||
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.
|
If you have any issues with CanCan which you cannot find the solution to in the documentation, please add an {issue on GitHub}[https://github.com/ryanb/cancan/issues] or fork the project and send a pull request.
|
||||||
|
|
||||||
alias_action :index, :show, :to => :read
|
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. See the {spec/README}[https://github.com/ryanb/cancan/blob/master/spec/README.rdoc] for more information.
|
||||||
alias_action :new, :to => :create
|
|
||||||
alias_action :edit, :to => :update
|
|
||||||
|
|
||||||
Notice the +edit+ action is aliased to +update+. If the user is able to update a record he also has permission to edit it. You can define your own aliases in the +Ability+ class
|
|
||||||
|
|
||||||
alias_action :update, :destroy, :to => :modify
|
|
||||||
can :modify, Comment
|
|
||||||
can? :update, Comment # => true
|
|
||||||
|
|
||||||
See {Custom Actions}[http://wiki.github.com/ryanb/cancan/custom-actions] for information on adding other actions.
|
|
||||||
|
|
||||||
|
|
||||||
== Fetching Records
|
|
||||||
|
|
||||||
In the controller +index+ action you may want to fetch only the records which the user has permission to read. You can do this with the +accessible_by+ scope.
|
|
||||||
|
|
||||||
@articles = Article.accessible_by(current_ability)
|
|
||||||
|
|
||||||
See {Fetching Records}[http://wiki.github.com/ryanb/cancan/fetching-records] for more information.
|
|
||||||
|
|
||||||
|
|
||||||
== Additional Docs
|
|
||||||
|
|
||||||
* {Upgrading to 1.3}[http://wiki.github.com/ryanb/cancan/upgrading-to-13]
|
|
||||||
* {Nested Resources}[http://wiki.github.com/ryanb/cancan/nested-resources]
|
|
||||||
* {Testing Abilities}[http://wiki.github.com/ryanb/cancan/testing-abilities]
|
|
||||||
* {Accessing Request Data}[http://wiki.github.com/ryanb/cancan/accessing-request-data]
|
|
||||||
* {Admin Namespace}[http://wiki.github.com/ryanb/cancan/admin-namespace]
|
|
||||||
* {See more}[http://wiki.github.com/ryanb/cancan/]
|
|
||||||
|
|
||||||
== Special Thanks
|
== 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.
|
||||||
|
|||||||
17
Rakefile
17
Rakefile
@@ -1,13 +1,18 @@
|
|||||||
require 'rubygems'
|
require 'rubygems'
|
||||||
require 'rake'
|
require 'rake'
|
||||||
require 'spec/rake/spectask'
|
require 'rspec/core/rake_task'
|
||||||
|
|
||||||
spec_files = Rake::FileList["spec/**/*_spec.rb"]
|
desc "Run RSpec"
|
||||||
|
RSpec::Core::RakeTask.new do |t|
|
||||||
|
t.verbose = false
|
||||||
|
end
|
||||||
|
|
||||||
desc "Run specs"
|
desc "Run specs for all adapters"
|
||||||
Spec::Rake::SpecTask.new do |t|
|
task :spec_all do
|
||||||
t.spec_files = spec_files
|
%w[active_record data_mapper mongoid].each do |model_adapter|
|
||||||
t.spec_opts = ["-c"]
|
puts "MODEL_ADAPTER = #{model_adapter}"
|
||||||
|
system "rake spec MODEL_ADAPTER=#{model_adapter}"
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
task :default => :spec
|
task :default => :spec
|
||||||
@@ -1,15 +1,20 @@
|
|||||||
Gem::Specification.new do |s|
|
Gem::Specification.new do |s|
|
||||||
s.name = "cancan"
|
s.name = "cancan"
|
||||||
s.version = "1.3.3"
|
s.version = "1.5.0"
|
||||||
s.author = "Ryan Bates"
|
s.author = "Ryan Bates"
|
||||||
s.email = "ryan@railscasts.com"
|
s.email = "ryan@railscasts.com"
|
||||||
s.homepage = "http://github.com/ryanb/cancan"
|
s.homepage = "http://github.com/ryanb/cancan"
|
||||||
s.summary = "Simple authorization solution for Rails."
|
s.summary = "Simple authorization solution for Rails."
|
||||||
s.description = "Simple authorization solution for Rails which is decoupled from user roles. All permissions are stored in a single location."
|
s.description = "Simple authorization solution for Rails which is decoupled from user roles. All permissions are stored in a single location."
|
||||||
|
|
||||||
s.files = Dir["{lib,spec}/**/*", "[A-Z]*", "init.rb"]
|
s.files = Dir["{lib,spec}/**/*", "[A-Z]*", "init.rb"] - ["Gemfile.lock"]
|
||||||
s.require_path = "lib"
|
s.require_path = "lib"
|
||||||
|
|
||||||
|
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'
|
||||||
|
|
||||||
s.rubyforge_project = s.name
|
s.rubyforge_project = s.name
|
||||||
s.required_rubygems_version = ">= 1.3.4"
|
s.required_rubygems_version = ">= 1.3.4"
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
require 'cancan/ability'
|
require 'cancan/ability'
|
||||||
require 'cancan/can_definition'
|
require 'cancan/rule'
|
||||||
require 'cancan/controller_resource'
|
require 'cancan/controller_resource'
|
||||||
require 'cancan/controller_additions'
|
require 'cancan/controller_additions'
|
||||||
require 'cancan/active_record_additions'
|
require 'cancan/model_additions'
|
||||||
require 'cancan/exceptions'
|
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
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ module CanCan
|
|||||||
# end
|
# end
|
||||||
#
|
#
|
||||||
module Ability
|
module Ability
|
||||||
# Use to check if the user has permission to perform a given action on an object.
|
# Check if the user has permission to perform a given action on an object.
|
||||||
#
|
#
|
||||||
# can? :destroy, @project
|
# can? :destroy, @project
|
||||||
#
|
#
|
||||||
@@ -24,6 +24,11 @@ module CanCan
|
|||||||
#
|
#
|
||||||
# can? :create, Project
|
# can? :create, Project
|
||||||
#
|
#
|
||||||
|
# Nested resources can be passed through a hash, this way conditions which are
|
||||||
|
# dependent upon the association will work when using a class.
|
||||||
|
#
|
||||||
|
# can? :create, @category => Project
|
||||||
|
#
|
||||||
# Any additional arguments will be passed into the "can" block definition. This
|
# Any additional arguments will be passed into the "can" block definition. This
|
||||||
# can be used to pass more information about the user's request for example.
|
# can be used to pass more information about the user's request for example.
|
||||||
#
|
#
|
||||||
@@ -49,9 +54,8 @@ module CanCan
|
|||||||
#
|
#
|
||||||
# Also see the RSpec Matchers to aid in testing.
|
# Also see the RSpec Matchers to aid in testing.
|
||||||
def can?(action, subject, *extra_args)
|
def can?(action, subject, *extra_args)
|
||||||
raise Error, "Nom nom nom. I eated it." if action == :has && subject == :cheezburger
|
match = relevant_rules_for_match(action, subject).detect do |rule|
|
||||||
match = relevant_can_definitions(action, subject).detect do |can_definition|
|
rule.matches_conditions?(action, subject, extra_args)
|
||||||
can_definition.matches_conditions?(action, subject, extra_args)
|
|
||||||
end
|
end
|
||||||
match ? match.base_behavior : false
|
match ? match.base_behavior : false
|
||||||
end
|
end
|
||||||
@@ -70,55 +74,55 @@ module CanCan
|
|||||||
# can :update, Article
|
# can :update, Article
|
||||||
#
|
#
|
||||||
# You can pass an array for either of these parameters to match any one.
|
# You can pass an array for either of these parameters to match any one.
|
||||||
|
# Here the user has the ability to update or destroy both articles and comments.
|
||||||
#
|
#
|
||||||
# can [:update, :destroy], [Article, Comment]
|
# can [:update, :destroy], [Article, Comment]
|
||||||
#
|
#
|
||||||
# In this case the user has the ability to update or destroy both articles and comments.
|
# You can pass :all to match any object and :manage to match any action. Here are some examples.
|
||||||
#
|
#
|
||||||
# You can pass a hash of conditions as the third argument.
|
# can :manage, :all
|
||||||
|
# can :update, :all
|
||||||
|
# can :manage, Project
|
||||||
|
#
|
||||||
|
# You can pass a hash of conditions as the third argument. Here the user can only see active projects which he owns.
|
||||||
#
|
#
|
||||||
# can :read, Project, :active => true, :user_id => user.id
|
# can :read, Project, :active => true, :user_id => user.id
|
||||||
#
|
#
|
||||||
# Here the user can only see active projects which he owns. See ActiveRecordAdditions#accessible_by
|
# See ActiveRecordAdditions#accessible_by for how to use this in database queries. These conditions
|
||||||
# for how to use this in database queries.
|
# are also used for initial attributes when building a record in ControllerAdditions#load_resource.
|
||||||
#
|
#
|
||||||
# If the conditions hash does not give you enough control over defining abilities, you can use a block to
|
# If the conditions hash does not give you enough control over defining abilities, you can use a block
|
||||||
# write any Ruby code you want.
|
# along with any Ruby code you want.
|
||||||
#
|
#
|
||||||
# can :update, Project do |project|
|
# can :update, Project do |project|
|
||||||
# project && project.groups.include?(user.group)
|
# project.groups.include?(user.group)
|
||||||
# end
|
# end
|
||||||
#
|
#
|
||||||
# If the block returns true then the user has that :update ability for that project, otherwise he
|
# If the block returns true then the user has that :update ability for that project, otherwise he
|
||||||
# will be denied access. It's possible for the passed in model to be nil if one isn't specified,
|
# will be denied access. The downside to using a block is that it cannot be used to generate
|
||||||
# so be sure to take that into consideration.
|
# conditions for database queries.
|
||||||
#
|
#
|
||||||
# The downside to using a block is that it cannot be used to generate conditions for database queries.
|
# You can pass custom objects into this "can" method, this is usually done with a symbol
|
||||||
#
|
|
||||||
# You can pass :all to reference every type of object. In this case the object type will be passed
|
|
||||||
# into the block as well (just in case object is nil).
|
|
||||||
#
|
|
||||||
# can :read, :all do |object_class, object|
|
|
||||||
# object_class != Order
|
|
||||||
# end
|
|
||||||
#
|
|
||||||
# Here the user has permission to read all objects except orders.
|
|
||||||
#
|
|
||||||
# You can also pass :manage as the action which will match any action. In this case the action is
|
|
||||||
# passed to the block.
|
|
||||||
#
|
|
||||||
# can :manage, Comment do |action, comment|
|
|
||||||
# action != :destroy
|
|
||||||
# end
|
|
||||||
#
|
|
||||||
# You can pass custom objects into this "can" method, this is usually done through a symbol
|
|
||||||
# and is useful if a class isn't available to define permissions on.
|
# and is useful if a class isn't available to define permissions on.
|
||||||
#
|
#
|
||||||
# can :read, :stats
|
# can :read, :stats
|
||||||
# can? :read, :stats # => true
|
# can? :read, :stats # => true
|
||||||
#
|
#
|
||||||
def can(action, subject, conditions = nil, &block)
|
# IMPORTANT: Neither a hash of conditions or a block will be used when checking permission on a class.
|
||||||
can_definitions << CanDefinition.new(true, action, subject, conditions, block)
|
#
|
||||||
|
# can :update, Project, :priority => 3
|
||||||
|
# can? :update, Project # => true
|
||||||
|
#
|
||||||
|
# If you pass no arguments to +can+, the action, class, and object will be passed to the block and the
|
||||||
|
# block will always be executed. This allows you to override the full behavior if the permissions are
|
||||||
|
# defined in an external source such as the database.
|
||||||
|
#
|
||||||
|
# can do |action, object_class, object|
|
||||||
|
# # check the database and return true/false
|
||||||
|
# end
|
||||||
|
#
|
||||||
|
def can(action = nil, subject = nil, conditions = nil, &block)
|
||||||
|
rules << Rule.new(true, action, subject, conditions, block)
|
||||||
end
|
end
|
||||||
|
|
||||||
# Defines an ability which cannot be done. Accepts the same arguments as "can".
|
# Defines an ability which cannot be done. Accepts the same arguments as "can".
|
||||||
@@ -133,8 +137,8 @@ module CanCan
|
|||||||
# product.invisible?
|
# product.invisible?
|
||||||
# end
|
# end
|
||||||
#
|
#
|
||||||
def cannot(action, subject, conditions = nil, &block)
|
def cannot(action = nil, subject = nil, conditions = nil, &block)
|
||||||
can_definitions << CanDefinition.new(false, action, subject, conditions, block)
|
rules << Rule.new(false, action, subject, conditions, block)
|
||||||
end
|
end
|
||||||
|
|
||||||
# Alias one or more actions into another one.
|
# Alias one or more actions into another one.
|
||||||
@@ -182,16 +186,59 @@ module CanCan
|
|||||||
@aliased_actions = {}
|
@aliased_actions = {}
|
||||||
end
|
end
|
||||||
|
|
||||||
# Returns a CanCan::Query instance to help generate database queries based on the ability.
|
def model_adapter(model_class, action)
|
||||||
# If any relevant can definitions use a block then an exception will be raised because an
|
adapter_class = ModelAdapters::AbstractAdapter.adapter_class(model_class)
|
||||||
# SQL query cannot be generated from blocks of code.
|
adapter_class.new(model_class, relevant_rules_for_query(action, model_class))
|
||||||
def query(action, subject)
|
end
|
||||||
Query.new(subject, relevant_can_definitions_for_query(action, subject))
|
|
||||||
|
# See ControllerAdditions#authorize! for documentation.
|
||||||
|
def authorize!(action, subject, *args)
|
||||||
|
message = nil
|
||||||
|
if args.last.kind_of?(Hash) && args.last.has_key?(:message)
|
||||||
|
message = args.pop[:message]
|
||||||
|
end
|
||||||
|
if cannot?(action, subject, *args)
|
||||||
|
message ||= unauthorized_message(action, subject)
|
||||||
|
raise AccessDenied.new(message, action, subject)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def unauthorized_message(action, subject)
|
||||||
|
keys = unauthorized_message_keys(action, subject)
|
||||||
|
variables = {:action => action.to_s}
|
||||||
|
variables[:subject] = (subject.class == Class ? subject : subject.class).to_s.downcase
|
||||||
|
message = I18n.translate(nil, variables.merge(:scope => :unauthorized, :default => keys + [""]))
|
||||||
|
message.blank? ? nil : message
|
||||||
|
end
|
||||||
|
|
||||||
|
def attributes_for(action, subject)
|
||||||
|
attributes = {}
|
||||||
|
relevant_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_rules(action, subject).any?(&:only_block?)
|
||||||
|
end
|
||||||
|
|
||||||
|
def has_raw_sql?(action, subject)
|
||||||
|
relevant_rules(action, subject).any?(&:only_raw_sql?)
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
# Accepts a hash of aliased actions and returns an array of actions which match.
|
def unauthorized_message_keys(action, subject)
|
||||||
|
subject = (subject.class == Class ? subject : subject.class).name.underscore unless subject.kind_of? Symbol
|
||||||
|
[subject, :all].map do |try_subject|
|
||||||
|
[aliases_for_action(action), :manage].flatten.map do |try_action|
|
||||||
|
:"#{try_action}.#{try_subject}"
|
||||||
|
end
|
||||||
|
end.flatten
|
||||||
|
end
|
||||||
|
|
||||||
|
# Accepts an array of actions and returns an array of actions which match.
|
||||||
# This should be called before "matches?" and other checking methods since they
|
# This should be called before "matches?" and other checking methods since they
|
||||||
# rely on the actions to be expanded.
|
# rely on the actions to be expanded.
|
||||||
def expand_actions(actions)
|
def expand_actions(actions)
|
||||||
@@ -200,23 +247,41 @@ module CanCan
|
|||||||
end.flatten
|
end.flatten
|
||||||
end
|
end
|
||||||
|
|
||||||
def can_definitions
|
# Given an action, it will try to find all of the actions which are aliased to it.
|
||||||
@can_definitions ||= []
|
# This does the opposite kind of lookup as expand_actions.
|
||||||
|
def aliases_for_action(action)
|
||||||
|
results = [action]
|
||||||
|
aliased_actions.each do |aliased_action, actions|
|
||||||
|
results += aliases_for_action(aliased_action) if actions.include? action
|
||||||
|
end
|
||||||
|
results
|
||||||
end
|
end
|
||||||
|
|
||||||
# Returns an array of CanDefinition instances which match the action and subject
|
def rules
|
||||||
|
@rules ||= []
|
||||||
|
end
|
||||||
|
|
||||||
|
# Returns an array of Rule instances which match the action and subject
|
||||||
# This does not take into consideration any hash conditions or block statements
|
# This does not take into consideration any hash conditions or block statements
|
||||||
def relevant_can_definitions(action, subject)
|
def relevant_rules(action, subject)
|
||||||
can_definitions.reverse.select do |can_definition|
|
rules.reverse.select do |rule|
|
||||||
can_definition.expanded_actions = expand_actions(can_definition.actions)
|
rule.expanded_actions = expand_actions(rule.actions)
|
||||||
can_definition.relevant? action, subject
|
rule.relevant? action, subject
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def relevant_can_definitions_for_query(action, subject)
|
def relevant_rules_for_match(action, subject)
|
||||||
relevant_can_definitions(action, subject).each do |can_definition|
|
relevant_rules(action, subject).each do |rule|
|
||||||
if can_definition.only_block?
|
if rule.only_raw_sql?
|
||||||
raise Error, "Cannot determine SQL conditions or joins from block for #{action.inspect} #{subject.inspect}"
|
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_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
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,104 +0,0 @@
|
|||||||
module CanCan
|
|
||||||
# This class is used internally and should only be called through Ability.
|
|
||||||
# it holds the information about a "can" call made on Ability and provides
|
|
||||||
# helpful methods to determine permission checking and conditions hash generation.
|
|
||||||
class CanDefinition # :nodoc:
|
|
||||||
attr_reader :base_behavior, :actions
|
|
||||||
attr_writer :expanded_actions
|
|
||||||
|
|
||||||
# The first argument when initializing is the base_behavior which is a true/false
|
|
||||||
# value. True for "can" and false for "cannot". The next two arguments are the action
|
|
||||||
# and subject respectively (such as :read, @project). The third argument is a hash
|
|
||||||
# of conditions and the last one is the block passed to the "can" call.
|
|
||||||
def initialize(base_behavior, action, subject, conditions, block)
|
|
||||||
@base_behavior = base_behavior
|
|
||||||
@actions = [action].flatten
|
|
||||||
@subjects = [subject].flatten
|
|
||||||
@conditions = conditions || {}
|
|
||||||
@block = block
|
|
||||||
end
|
|
||||||
|
|
||||||
# Matches both the subject and action, not necessarily the conditions
|
|
||||||
def relevant?(action, subject)
|
|
||||||
matches_action?(action) && matches_subject?(subject)
|
|
||||||
end
|
|
||||||
|
|
||||||
# Matches the block or conditions hash
|
|
||||||
def matches_conditions?(action, subject, extra_args)
|
|
||||||
if @block
|
|
||||||
call_block(action, subject, extra_args)
|
|
||||||
elsif @conditions.kind_of?(Hash) && subject.class != Class
|
|
||||||
matches_conditions_hash?(subject)
|
|
||||||
else
|
|
||||||
true
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def tableized_conditions(conditions = @conditions)
|
|
||||||
conditions.inject({}) do |result_hash, (name, value)|
|
|
||||||
if value.kind_of? Hash
|
|
||||||
name = name.to_s.tableize.to_sym
|
|
||||||
value = tableized_conditions(value)
|
|
||||||
end
|
|
||||||
result_hash[name] = value
|
|
||||||
result_hash
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def only_block?
|
|
||||||
conditions_empty? && !@block.nil?
|
|
||||||
end
|
|
||||||
|
|
||||||
def conditions_empty?
|
|
||||||
@conditions == {} || @conditions.nil?
|
|
||||||
end
|
|
||||||
|
|
||||||
def associations_hash(conditions = @conditions)
|
|
||||||
hash = {}
|
|
||||||
conditions.map do |name, value|
|
|
||||||
hash[name] = associations_hash(value) if value.kind_of? Hash
|
|
||||||
end
|
|
||||||
hash
|
|
||||||
end
|
|
||||||
|
|
||||||
private
|
|
||||||
|
|
||||||
def matches_action?(action)
|
|
||||||
@expanded_actions.include?(:manage) || @expanded_actions.include?(action)
|
|
||||||
end
|
|
||||||
|
|
||||||
def matches_subject?(subject)
|
|
||||||
@subjects.include?(:all) || @subjects.include?(subject) || matches_subject_class?(subject)
|
|
||||||
end
|
|
||||||
|
|
||||||
def matches_subject_class?(subject)
|
|
||||||
@subjects.any? { |sub| sub.kind_of?(Class) && (subject.kind_of?(sub) || subject.kind_of?(Class) && subject.ancestors.include?(sub)) }
|
|
||||||
end
|
|
||||||
|
|
||||||
def matches_conditions_hash?(subject, conditions = @conditions)
|
|
||||||
conditions.all? do |name, value|
|
|
||||||
attribute = subject.send(name)
|
|
||||||
if value.kind_of?(Hash)
|
|
||||||
if attribute.kind_of? Array
|
|
||||||
attribute.any? { |element| matches_conditions_hash? element, value }
|
|
||||||
else
|
|
||||||
matches_conditions_hash? attribute, value
|
|
||||||
end
|
|
||||||
elsif value.kind_of?(Array) || value.kind_of?(Range)
|
|
||||||
value.include? attribute
|
|
||||||
else
|
|
||||||
attribute == value
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def call_block(action, subject, extra_args)
|
|
||||||
block_args = []
|
|
||||||
block_args << action if @expanded_actions.include?(:manage)
|
|
||||||
block_args << (subject.class == Class ? subject : subject.class) if @subjects.include?(:all)
|
|
||||||
block_args << (subject.class == Class ? nil : subject)
|
|
||||||
block_args += extra_args
|
|
||||||
@block.call(*block_args)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -12,14 +12,18 @@ module CanCan
|
|||||||
# end
|
# end
|
||||||
#
|
#
|
||||||
def load_and_authorize_resource(*args)
|
def load_and_authorize_resource(*args)
|
||||||
ControllerResource.add_before_filter(self, :load_and_authorize_resource, *args)
|
cancan_resource_class.add_before_filter(self, :load_and_authorize_resource, *args)
|
||||||
end
|
end
|
||||||
|
|
||||||
# Sets up a before filter which loads the model resource into an instance variable.
|
# Sets up a before filter which loads the model resource into an instance variable.
|
||||||
# For example, given an ArticlesController it will load the current article into the @article
|
# For example, given an ArticlesController it will load the current article into the @article
|
||||||
# instance variable. It does this by either calling Article.find(params[:id]) or
|
# instance variable. It does this by either calling Article.find(params[:id]) or
|
||||||
# Article.new(params[:article]) depending upon the action. It does nothing for the "index"
|
# Article.new(params[:article]) depending upon the action. The index action will
|
||||||
# action.
|
# automatically set @articles to Article.accessible_by(current_ability).
|
||||||
|
#
|
||||||
|
# If a conditions hash is used in the Ability, the +new+ and +create+ actions will set
|
||||||
|
# the initial attributes based on these conditions. This way these actions will satisfy
|
||||||
|
# the ability restrictions.
|
||||||
#
|
#
|
||||||
# Call this method directly on the controller class.
|
# Call this method directly on the controller class.
|
||||||
#
|
#
|
||||||
@@ -65,7 +69,14 @@ module CanCan
|
|||||||
# Does not apply before filter to given actions.
|
# Does not apply before filter to given actions.
|
||||||
#
|
#
|
||||||
# [:+through+]
|
# [:+through+]
|
||||||
# Load this resource through another one. This should match the name of the parent instance variable.
|
# Load this resource through another one. This should match the name of the parent instance variable or method.
|
||||||
|
#
|
||||||
|
# [:+through_association+]
|
||||||
|
# The name of the association to fetch the child records through the parent resource. This is normally not needed
|
||||||
|
# because it defaults to the pluralized resource name.
|
||||||
|
#
|
||||||
|
# [:+shallow+]
|
||||||
|
# Pass +true+ to allow this resource to be loaded directly when parent is +nil+. Defaults to +false+.
|
||||||
#
|
#
|
||||||
# [:+singleton+]
|
# [:+singleton+]
|
||||||
# Pass +true+ if this is a singleton resource through a +has_one+ association.
|
# Pass +true+ if this is a singleton resource through a +has_one+ association.
|
||||||
@@ -99,7 +110,7 @@ module CanCan
|
|||||||
# load_resource :new => :build
|
# load_resource :new => :build
|
||||||
#
|
#
|
||||||
def load_resource(*args)
|
def load_resource(*args)
|
||||||
ControllerResource.add_before_filter(self, :load_resource, *args)
|
cancan_resource_class.add_before_filter(self, :load_resource, *args)
|
||||||
end
|
end
|
||||||
|
|
||||||
# Sets up a before filter which authorizes the resource using the instance variable.
|
# Sets up a before filter which authorizes the resource using the instance variable.
|
||||||
@@ -148,8 +159,105 @@ module CanCan
|
|||||||
# [:+instance_name+]
|
# [:+instance_name+]
|
||||||
# The name of the instance variable for this resource.
|
# The name of the instance variable for this resource.
|
||||||
#
|
#
|
||||||
|
# [:+through+]
|
||||||
|
# Authorize conditions on this parent resource when instance isn't available.
|
||||||
|
#
|
||||||
def authorize_resource(*args)
|
def authorize_resource(*args)
|
||||||
ControllerResource.add_before_filter(self, :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.
|
||||||
|
#
|
||||||
|
# class ApplicationController < ActionController::Base
|
||||||
|
# check_authorization
|
||||||
|
# end
|
||||||
|
#
|
||||||
|
# Any arguments are passed to the +after_filter+ it triggers.
|
||||||
|
#
|
||||||
|
# See skip_authorization_check to bypass this check on specific controller actions.
|
||||||
|
def check_authorization(*args)
|
||||||
|
self.after_filter(*args) do |controller|
|
||||||
|
unless controller.instance_variable_defined?(:@_authorized)
|
||||||
|
raise AuthorizationNotPerformed, "This action failed the check_authorization because it does not authorize_resource. Add skip_authorization_check to bypass this check."
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# Call this in the class of a controller to skip the check_authorization behavior on the actions.
|
||||||
|
#
|
||||||
|
# class HomeController < ApplicationController
|
||||||
|
# skip_authorization_check :only => :index
|
||||||
|
# end
|
||||||
|
#
|
||||||
|
# Any arguments are passed to the +before_filter+ it triggers.
|
||||||
|
def skip_authorization_check(*args)
|
||||||
|
self.before_filter(*args) do |controller|
|
||||||
|
controller.instance_variable_set(:@_authorized, true)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def skip_authorization(*args)
|
||||||
|
raise ImplementationRemoved, "The CanCan skip_authorization method has been renamed to skip_authorization_check. Please update your code."
|
||||||
|
end
|
||||||
|
|
||||||
|
def cancan_resource_class
|
||||||
|
if ancestors.map(&:to_s).include? "InheritedResources::Actions"
|
||||||
|
InheritedResource
|
||||||
|
else
|
||||||
|
ControllerResource
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def cancan_skipper
|
||||||
|
@_cancan_skipper ||= {:authorize => {}, :load => {}}
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -171,6 +279,16 @@ module CanCan
|
|||||||
#
|
#
|
||||||
# authorize! :read, @article, :message => "Not authorized to read #{@article.name}"
|
# authorize! :read, @article, :message => "Not authorized to read #{@article.name}"
|
||||||
#
|
#
|
||||||
|
# You can also use I18n to customize the message. Action aliases defined in Ability work here.
|
||||||
|
#
|
||||||
|
# en:
|
||||||
|
# unauthorized:
|
||||||
|
# manage:
|
||||||
|
# all: "Not authorized to %{action} %{subject}."
|
||||||
|
# user: "Not allowed to manage other user accounts."
|
||||||
|
# update:
|
||||||
|
# project: "Not allowed to update this project."
|
||||||
|
#
|
||||||
# You can rescue from the exception in the controller to customize how unauthorized
|
# You can rescue from the exception in the controller to customize how unauthorized
|
||||||
# access is displayed to the user.
|
# access is displayed to the user.
|
||||||
#
|
#
|
||||||
@@ -185,12 +303,9 @@ module CanCan
|
|||||||
#
|
#
|
||||||
# See the load_and_authorize_resource method to automatically add the authorize! behavior
|
# See the load_and_authorize_resource method to automatically add the authorize! behavior
|
||||||
# to the default RESTful actions.
|
# to the default RESTful actions.
|
||||||
def authorize!(action, subject, *args)
|
def authorize!(*args)
|
||||||
message = nil
|
@_authorized = true
|
||||||
if args.last.kind_of?(Hash) && args.last.has_key?(:message)
|
current_ability.authorize!(*args)
|
||||||
message = args.pop[:message]
|
|
||||||
end
|
|
||||||
raise AccessDenied.new(message, action, subject) if cannot?(action, subject, *args)
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def unauthorized!(message = nil)
|
def unauthorized!(message = nil)
|
||||||
@@ -223,6 +338,13 @@ module CanCan
|
|||||||
# <%= link_to "New Project", new_project_path %>
|
# <%= link_to "New Project", new_project_path %>
|
||||||
# <% end %>
|
# <% end %>
|
||||||
#
|
#
|
||||||
|
# If it's a nested resource, you can pass the parent instance in a hash. This way it will
|
||||||
|
# check conditions which reach through that association.
|
||||||
|
#
|
||||||
|
# <% if can? :create, @category => Project %>
|
||||||
|
# <%= link_to "New Project", new_project_path %>
|
||||||
|
# <% end %>
|
||||||
|
#
|
||||||
# This simply calls "can?" on the current_ability. See Ability#can?.
|
# This simply calls "can?" on the current_ability. See Ability#can?.
|
||||||
def can?(*args)
|
def can?(*args)
|
||||||
current_ability.can?(*args)
|
current_ability.can?(*args)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ module CanCan
|
|||||||
options = args.extract_options!
|
options = args.extract_options!
|
||||||
resource_name = args.first
|
resource_name = args.first
|
||||||
controller_class.before_filter(options.slice(:only, :except)) do |controller|
|
controller_class.before_filter(options.slice(:only, :except)) do |controller|
|
||||||
ControllerResource.new(controller, resource_name, options.except(:only, :except)).send(method)
|
controller.class.cancan_resource_class.new(controller, resource_name, options.except(:only, :except)).send(method)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -26,20 +26,39 @@ module CanCan
|
|||||||
end
|
end
|
||||||
|
|
||||||
def load_resource
|
def load_resource
|
||||||
if !resource_instance && (parent? || member_action?)
|
unless skip?(:load)
|
||||||
@controller.instance_variable_set("@#{instance_name}", load_resource_instance)
|
if load_instance?
|
||||||
|
self.resource_instance ||= load_resource_instance
|
||||||
|
elsif load_collection?
|
||||||
|
self.collection_instance ||= load_collection
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def authorize_resource
|
def authorize_resource
|
||||||
@controller.authorize!(authorization_action, resource_instance || resource_class)
|
unless skip?(:authorize)
|
||||||
|
@controller.authorize!(authorization_action, resource_instance || resource_class_with_parent)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def parent?
|
def parent?
|
||||||
@options.has_key?(:parent) ? @options[:parent] : @name && @name != name_from_controller.to_sym
|
@options.has_key?(:parent) ? @options[:parent] : @name && @name != name_from_controller.to_sym
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
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
|
def load_resource_instance
|
||||||
if !parent? && new_actions.include?(@params[:action].to_sym)
|
if !parent? && new_actions.include?(@params[:action].to_sym)
|
||||||
@@ -49,13 +68,35 @@ module CanCan
|
|||||||
end
|
end
|
||||||
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)
|
||||||
|
end
|
||||||
|
|
||||||
|
def load_collection
|
||||||
|
resource_base.accessible_by(current_ability)
|
||||||
|
end
|
||||||
|
|
||||||
def build_resource
|
def build_resource
|
||||||
method_name = @options[:singleton] ? "build_#{name}" : "new"
|
method_name = @options[:singleton] && resource_base.respond_to?("build_#{name}") ? "build_#{name}" : "new"
|
||||||
resource_base.send(*[method_name, @params[name]].compact)
|
resource = resource_base.send(method_name, @params[name] || {})
|
||||||
|
initial_attributes.each do |name, value|
|
||||||
|
resource.send("#{name}=", value)
|
||||||
|
end
|
||||||
|
resource
|
||||||
|
end
|
||||||
|
|
||||||
|
def initial_attributes
|
||||||
|
current_ability.attributes_for(@params[:action].to_sym, resource_class).delete_if do |key, value|
|
||||||
|
@params[name] && @params[name].include?(key)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def find_resource
|
def find_resource
|
||||||
if @options[:singleton]
|
if @options[:singleton] && resource_base.respond_to?(name)
|
||||||
resource_base.send(name)
|
resource_base.send(name)
|
||||||
else
|
else
|
||||||
@options[:find_by] ? resource_base.send("find_by_#{@options[:find_by]}!", id_param) : resource_base.find(id_param)
|
@options[:find_by] ? resource_base.send("find_by_#{@options[:find_by]}!", id_param) : resource_base.find(id_param)
|
||||||
@@ -86,24 +127,59 @@ module CanCan
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def resource_class_with_parent
|
||||||
|
parent_resource ? {parent_resource => resource_class} : resource_class
|
||||||
|
end
|
||||||
|
|
||||||
|
def resource_instance=(instance)
|
||||||
|
@controller.instance_variable_set("@#{instance_name}", instance)
|
||||||
|
end
|
||||||
|
|
||||||
def resource_instance
|
def resource_instance
|
||||||
@controller.instance_variable_get("@#{instance_name}")
|
@controller.instance_variable_get("@#{instance_name}") if load_instance?
|
||||||
|
end
|
||||||
|
|
||||||
|
def collection_instance=(instance)
|
||||||
|
@controller.instance_variable_set("@#{instance_name.to_s.pluralize}", instance)
|
||||||
|
end
|
||||||
|
|
||||||
|
def collection_instance
|
||||||
|
@controller.instance_variable_get("@#{instance_name.to_s.pluralize}")
|
||||||
end
|
end
|
||||||
|
|
||||||
# The object that methods (such as "find", "new" or "build") are called on.
|
# The object that methods (such as "find", "new" or "build") are called on.
|
||||||
# If the :through option is passed it will go through an association on that instance.
|
# If the :through option is passed it will go through an association on that instance.
|
||||||
|
# If the :shallow option is passed it will use the resource_class if there's no parent
|
||||||
# If the :singleton option is passed it won't use the association because it needs to be handled later.
|
# If the :singleton option is passed it won't use the association because it needs to be handled later.
|
||||||
def resource_base
|
def resource_base
|
||||||
if through_resource
|
if @options[:through]
|
||||||
@options[:singleton] ? through_resource : through_resource.send(name.to_s.pluralize)
|
if parent_resource
|
||||||
|
@options[:singleton] ? parent_resource : parent_resource.send(@options[:through_association] || name.to_s.pluralize)
|
||||||
|
elsif @options[:shallow]
|
||||||
|
resource_class
|
||||||
|
else
|
||||||
|
raise AccessDenied # maybe this should be a record not found error instead?
|
||||||
|
end
|
||||||
else
|
else
|
||||||
resource_class
|
resource_class
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
# The object to load this resource through.
|
# The object to load this resource through.
|
||||||
def through_resource
|
def parent_resource
|
||||||
@options[:through] && [@options[:through]].flatten.map { |i| @controller.instance_variable_get("@#{i}") }.compact.first
|
@options[:through] && [@options[:through]].flatten.map { |i| fetch_parent(i) }.compact.first
|
||||||
|
end
|
||||||
|
|
||||||
|
def fetch_parent(name)
|
||||||
|
if @controller.instance_variable_defined? "@#{name}"
|
||||||
|
@controller.instance_variable_get("@#{name}")
|
||||||
|
elsif @controller.respond_to? name
|
||||||
|
@controller.send(name)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def current_ability
|
||||||
|
@controller.send(:current_ability)
|
||||||
end
|
end
|
||||||
|
|
||||||
def name
|
def name
|
||||||
|
|||||||
@@ -2,9 +2,15 @@ module CanCan
|
|||||||
# A general CanCan exception
|
# A general CanCan exception
|
||||||
class Error < StandardError; end
|
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.
|
# Raised when removed code is called, an alternative solution is provided in message.
|
||||||
class ImplementationRemoved < Error; end
|
class ImplementationRemoved < Error; end
|
||||||
|
|
||||||
|
# Raised when using check_authorization without calling authorized!
|
||||||
|
class AuthorizationNotPerformed < Error; end
|
||||||
|
|
||||||
# This error is raised when a user isn't allowed to access a given controller action.
|
# This error is raised when a user isn't allowed to access a given controller action.
|
||||||
# This usually happens within a call to ControllerAdditions#authorize! but can be
|
# This usually happens within a call to ControllerAdditions#authorize! but can be
|
||||||
# raised manually.
|
# raised manually.
|
||||||
@@ -24,7 +30,8 @@ module CanCan
|
|||||||
# exception.default_message = "Default error message"
|
# exception.default_message = "Default error message"
|
||||||
# exception.message # => "Default error message"
|
# exception.message # => "Default error message"
|
||||||
#
|
#
|
||||||
# See ControllerAdditions#authorized! for more information on rescuing from this exception.
|
# See ControllerAdditions#authorized! for more information on rescuing from this exception
|
||||||
|
# and customizing the message using I18n.
|
||||||
class AccessDenied < Error
|
class AccessDenied < Error
|
||||||
attr_reader :action, :subject
|
attr_reader :action, :subject
|
||||||
attr_writer :default_message
|
attr_writer :default_message
|
||||||
|
|||||||
18
lib/cancan/inherited_resource.rb
Normal file
18
lib/cancan/inherited_resource.rb
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
module CanCan
|
||||||
|
# For use with Inherited Resources
|
||||||
|
class InheritedResource < ControllerResource # :nodoc:
|
||||||
|
def load_resource_instance
|
||||||
|
if parent?
|
||||||
|
@controller.send :parent
|
||||||
|
elsif new_actions.include? @params[:action].to_sym
|
||||||
|
@controller.send :build_resource
|
||||||
|
else
|
||||||
|
@controller.send :resource
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def resource_base
|
||||||
|
@controller.send :end_of_association_chain
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
40
lib/cancan/model_adapters/abstract_adapter.rb
Normal file
40
lib/cancan/model_adapters/abstract_adapter.rb
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
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
|
||||||
119
lib/cancan/model_adapters/active_record_adapter.rb
Normal file
119
lib/cancan/model_adapters/active_record_adapter.rb
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
module CanCan
|
||||||
|
module ModelAdapters
|
||||||
|
class ActiveRecordAdapter < AbstractAdapter
|
||||||
|
def self.for_class?(model_class)
|
||||||
|
model_class <= ActiveRecord::Base
|
||||||
|
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)
|
||||||
|
return conditions unless conditions.kind_of? Hash
|
||||||
|
conditions.inject({}) do |result_hash, (name, value)|
|
||||||
|
if value.kind_of? Hash
|
||||||
|
name = @model_class.reflect_on_association(name).table_name
|
||||||
|
value = tableized_conditions(value)
|
||||||
|
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 @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 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
|
||||||
41
lib/cancan/model_adapters/mongoid_adapter.rb
Normal file
41
lib/cancan/model_adapters/mongoid_adapter.rb
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
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
|
||||||
|
@model_class.where(conditions)
|
||||||
|
end
|
||||||
|
|
||||||
|
def conditions
|
||||||
|
if @rules.size == 0
|
||||||
|
false_query
|
||||||
|
else
|
||||||
|
@rules.first.conditions
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def false_query
|
||||||
|
# this query is sure to return no results
|
||||||
|
{:_id => {'$exists' => false, '$type' => 7}} # type 7 is an ObjectID (default for _id)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# simplest way to add `accessible_by` to all Mongoid Documents
|
||||||
|
module Mongoid::Document::ClassMethods
|
||||||
|
include CanCan::ModelAdditions::ClassMethods
|
||||||
|
end
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
module CanCan
|
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
|
module ClassMethods
|
||||||
# Returns a scope which fetches only the records that the passed ability
|
# 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 :read. This
|
||||||
@@ -17,15 +18,9 @@ module CanCan
|
|||||||
#
|
#
|
||||||
# @articles = Article.accessible_by(current_ability, :update)
|
# @articles = Article.accessible_by(current_ability, :update)
|
||||||
#
|
#
|
||||||
# Here only the articles which the user can update are returned. This
|
# Here only the articles which the user can update are returned.
|
||||||
# internally uses Ability#conditions method, see that for more information.
|
|
||||||
def accessible_by(ability, action = :read)
|
def accessible_by(ability, action = :read)
|
||||||
query = ability.query(action, self)
|
ability.model_adapter(self, action).database_records
|
||||||
if respond_to? :where
|
|
||||||
where(query.conditions).joins(query.joins)
|
|
||||||
else
|
|
||||||
scoped(:conditions => query.conditions, :joins => query.joins)
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -34,9 +29,3 @@ module CanCan
|
|||||||
end
|
end
|
||||||
end
|
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
|
|
||||||
137
lib/cancan/rule.rb
Normal file
137
lib/cancan/rule.rb
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
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 Rule # :nodoc:
|
||||||
|
attr_reader :base_behavior, :actions, :conditions
|
||||||
|
attr_writer :expanded_actions
|
||||||
|
|
||||||
|
# The first argument when initializing is the base_behavior which is a true/false
|
||||||
|
# value. True for "can" and false for "cannot". The next two arguments are the action
|
||||||
|
# and subject respectively (such as :read, @project). The third argument is a hash
|
||||||
|
# of conditions and the last one is the block passed to the "can" call.
|
||||||
|
def initialize(base_behavior, action, subject, conditions, block)
|
||||||
|
@match_all = action.nil? && subject.nil?
|
||||||
|
@base_behavior = base_behavior
|
||||||
|
@actions = [action].flatten
|
||||||
|
@subjects = [subject].flatten
|
||||||
|
@conditions = conditions || {}
|
||||||
|
@block = block
|
||||||
|
end
|
||||||
|
|
||||||
|
# Matches both the subject and action, not necessarily the conditions
|
||||||
|
def relevant?(action, subject)
|
||||||
|
subject = subject.values.first if subject.kind_of? Hash
|
||||||
|
@match_all || (matches_action?(action) && matches_subject?(subject))
|
||||||
|
end
|
||||||
|
|
||||||
|
# Matches the block or conditions hash
|
||||||
|
def matches_conditions?(action, subject, extra_args)
|
||||||
|
if @match_all
|
||||||
|
call_block_with_all(action, subject, extra_args)
|
||||||
|
elsif @block && !subject_class?(subject)
|
||||||
|
@block.call(subject, *extra_args)
|
||||||
|
elsif @conditions.kind_of?(Hash) && subject.kind_of?(Hash)
|
||||||
|
nested_subject_matches_conditions?(subject)
|
||||||
|
elsif @conditions.kind_of?(Hash) && !subject_class?(subject)
|
||||||
|
matches_conditions_hash?(subject)
|
||||||
|
else
|
||||||
|
# Don't stop at "cannot" definitions when there are conditions.
|
||||||
|
@conditions.empty? ? true : @base_behavior
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def only_block?
|
||||||
|
conditions_empty? && !@block.nil?
|
||||||
|
end
|
||||||
|
|
||||||
|
def only_raw_sql?
|
||||||
|
@block.nil? && !conditions_empty? && !@conditions.kind_of?(Hash)
|
||||||
|
end
|
||||||
|
|
||||||
|
def conditions_empty?
|
||||||
|
@conditions == {} || @conditions.nil?
|
||||||
|
end
|
||||||
|
|
||||||
|
def associations_hash(conditions = @conditions)
|
||||||
|
hash = {}
|
||||||
|
conditions.map do |name, value|
|
||||||
|
hash[name] = associations_hash(value) if value.kind_of? Hash
|
||||||
|
end if conditions.kind_of? Hash
|
||||||
|
hash
|
||||||
|
end
|
||||||
|
|
||||||
|
def attributes_from_conditions
|
||||||
|
attributes = {}
|
||||||
|
@conditions.each do |key, value|
|
||||||
|
attributes[key] = value unless [Array, Range, Hash].include? value.class
|
||||||
|
end if @conditions.kind_of? Hash
|
||||||
|
attributes
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def subject_class?(subject)
|
||||||
|
klass = (subject.kind_of?(Hash) ? subject.values.first : subject).class
|
||||||
|
klass == Class || klass == Module
|
||||||
|
end
|
||||||
|
|
||||||
|
def matches_action?(action)
|
||||||
|
@expanded_actions.include?(:manage) || @expanded_actions.include?(action)
|
||||||
|
end
|
||||||
|
|
||||||
|
def matches_subject?(subject)
|
||||||
|
@subjects.include?(:all) || @subjects.include?(subject) || matches_subject_class?(subject)
|
||||||
|
end
|
||||||
|
|
||||||
|
def matches_subject_class?(subject)
|
||||||
|
@subjects.any? { |sub| sub.kind_of?(Module) && (subject.kind_of?(sub) || subject.class.to_s == sub.to_s || subject.kind_of?(Module) && subject.ancestors.include?(sub)) }
|
||||||
|
end
|
||||||
|
|
||||||
|
# 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|
|
||||||
|
attribute = subject.send(name)
|
||||||
|
if value.kind_of?(Hash)
|
||||||
|
if attribute.kind_of? Array
|
||||||
|
attribute.any? { |element| matches_conditions_hash? element, value }
|
||||||
|
else
|
||||||
|
matches_conditions_hash? attribute, value
|
||||||
|
end
|
||||||
|
elsif value.kind_of?(Array) || value.kind_of?(Range)
|
||||||
|
value.include? attribute
|
||||||
|
else
|
||||||
|
attribute == value
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def nested_subject_matches_conditions?(subject_hash)
|
||||||
|
parent, child = subject_hash.shift
|
||||||
|
matches_conditions_hash?(parent, @conditions[parent.class.name.downcase.to_sym] || {})
|
||||||
|
end
|
||||||
|
|
||||||
|
def call_block_with_all(action, subject, extra_args)
|
||||||
|
if subject.class == Class
|
||||||
|
@block.call(action, subject, nil, *extra_args)
|
||||||
|
else
|
||||||
|
@block.call(action, subject.class, subject, *extra_args)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
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
|
||||||
@@ -24,7 +24,15 @@ describe CanCan::Ability do
|
|||||||
@ability.can?(:read, :some_symbol).should == true
|
@ability.can?(:read, :some_symbol).should == true
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should pass to previous can definition, if block returns false or nil" do
|
it "should pass nil to a block when no instance is passed" do
|
||||||
|
@ability.can :read, Symbol do |sym|
|
||||||
|
sym.should be_nil
|
||||||
|
true
|
||||||
|
end
|
||||||
|
@ability.can?(:read, Symbol).should be_true
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should pass to previous rule, if block returns false or nil" do
|
||||||
@ability.can :read, Symbol
|
@ability.can :read, Symbol
|
||||||
@ability.can :read, Integer do |i|
|
@ability.can :read, Integer do |i|
|
||||||
i < 5
|
i < 5
|
||||||
@@ -38,9 +46,8 @@ describe CanCan::Ability do
|
|||||||
@ability.can?(:read, 6).should be_false
|
@ability.can?(:read, 6).should be_false
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should pass class with object if :all objects are accepted" do
|
it "should not pass class with object if :all objects are accepted" do
|
||||||
@ability.can :preview, :all do |object_class, object|
|
@ability.can :preview, :all do |object|
|
||||||
object_class.should == Fixnum
|
|
||||||
object.should == 123
|
object.should == 123
|
||||||
@block_called = true
|
@block_called = true
|
||||||
end
|
end
|
||||||
@@ -48,23 +55,21 @@ describe CanCan::Ability do
|
|||||||
@block_called.should be_true
|
@block_called.should be_true
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should pass class with no object if :all objects are accepted and class is passed directly" do
|
it "should not call block when only class is passed, only return true" do
|
||||||
@ability.can :preview, :all do |object_class, object|
|
@block_called = false
|
||||||
object_class.should == Hash
|
@ability.can :preview, :all do |object|
|
||||||
object.should be_nil
|
|
||||||
@block_called = true
|
@block_called = true
|
||||||
end
|
end
|
||||||
@ability.can?(:preview, Hash)
|
@ability.can?(:preview, Hash).should be_true
|
||||||
@block_called.should be_true
|
@block_called.should be_false
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should pass action and object for global manage actions" do
|
it "should pass only object for global manage actions" do
|
||||||
@ability.can :manage, Array do |action, object|
|
@ability.can :manage, String do |object|
|
||||||
action.should == :stuff
|
object.should == "foo"
|
||||||
object.should == [1, 2]
|
|
||||||
@block_called = true
|
@block_called = true
|
||||||
end
|
end
|
||||||
@ability.can?(:stuff, [1, 2]).should
|
@ability.can?(:stuff, "foo").should
|
||||||
@block_called.should be_true
|
@block_called.should be_true
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -82,10 +87,10 @@ describe CanCan::Ability do
|
|||||||
@ability.can?(:increment, 123).should be_true
|
@ability.can?(:increment, 123).should be_true
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should return block result for action, object_class, and object for any action" do
|
it "should always call block with arguments when passing no arguments to can" do
|
||||||
@ability.can :manage, :all do |action, object_class, object|
|
@ability.can do |action, object_class, object|
|
||||||
action.should == :foo
|
action.should == :foo
|
||||||
object_class.should == Fixnum
|
object_class.should == 123.class
|
||||||
object.should == 123
|
object.should == 123
|
||||||
@block_called = true
|
@block_called = true
|
||||||
end
|
end
|
||||||
@@ -93,6 +98,17 @@ describe CanCan::Ability do
|
|||||||
@block_called.should be_true
|
@block_called.should be_true
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it "should pass nil to object when comparing class with can check" do
|
||||||
|
@ability.can do |action, object_class, object|
|
||||||
|
action.should == :foo
|
||||||
|
object_class.should == Hash
|
||||||
|
object.should be_nil
|
||||||
|
@block_called = true
|
||||||
|
end
|
||||||
|
@ability.can?(:foo, Hash)
|
||||||
|
@block_called.should be_true
|
||||||
|
end
|
||||||
|
|
||||||
it "should automatically alias index and show into read calls" do
|
it "should automatically alias index and show into read calls" do
|
||||||
@ability.can :read, :all
|
@ability.can :read, :all
|
||||||
@ability.can?(:index, 123).should be_true
|
@ability.can?(:index, 123).should be_true
|
||||||
@@ -122,13 +138,13 @@ describe CanCan::Ability do
|
|||||||
end
|
end
|
||||||
|
|
||||||
it "should be able to specify multiple classes and match any" do
|
it "should be able to specify multiple classes and match any" do
|
||||||
@ability.can :update, [String, Array]
|
@ability.can :update, [String, Range]
|
||||||
@ability.can?(:update, "foo").should be_true
|
@ability.can?(:update, "foo").should be_true
|
||||||
@ability.can?(:update, []).should be_true
|
@ability.can?(:update, 1..3).should be_true
|
||||||
@ability.can?(:update, 123).should be_false
|
@ability.can?(:update, 123).should be_false
|
||||||
end
|
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
|
||||||
@ability.can?(:read, :stats).should be_true
|
@ability.can?(:read, :stats).should be_true
|
||||||
@ability.can?(:update, :stats).should be_false
|
@ability.can?(:update, :stats).should be_false
|
||||||
@@ -149,18 +165,7 @@ describe CanCan::Ability do
|
|||||||
@ability.can?(:read, 123).should be_false
|
@ability.can?(:read, 123).should be_false
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should support block on 'cannot' method" 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 > 5
|
|
||||||
end
|
|
||||||
@ability.can?(:read, "foo").should be_true
|
|
||||||
@ability.can?(:read, 3).should be_true
|
|
||||||
@ability.can?(:read, 123).should be_false
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should pass to previous can definition, if block returns false or nil" do
|
|
||||||
#same as previous
|
|
||||||
@ability.can :read, :all
|
@ability.can :read, :all
|
||||||
@ability.cannot :read, Integer do |int|
|
@ability.cannot :read, Integer do |int|
|
||||||
int > 10 ? nil : ( int > 5 )
|
int > 10 ? nil : ( int > 5 )
|
||||||
@@ -169,7 +174,6 @@ describe CanCan::Ability do
|
|||||||
@ability.can?(:read, 3).should be_true
|
@ability.can?(:read, 3).should be_true
|
||||||
@ability.can?(:read, 8).should be_false
|
@ability.can?(:read, 8).should be_false
|
||||||
@ability.can?(:read, 123).should be_true
|
@ability.can?(:read, 123).should be_true
|
||||||
|
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should always return `false` for single cannot definition" do
|
it "should always return `false` for single cannot definition" do
|
||||||
@@ -214,41 +218,178 @@ describe CanCan::Ability do
|
|||||||
end
|
end
|
||||||
|
|
||||||
it "should use conditions as third parameter and determine abilities from it" do
|
it "should use conditions as third parameter and determine abilities from it" do
|
||||||
@ability.can :read, Array, :first => 1, :last => 3
|
@ability.can :read, Range, :begin => 1, :end => 3
|
||||||
@ability.can?(:read, [1, 2, 3]).should be_true
|
@ability.can?(:read, 1..3).should be_true
|
||||||
@ability.can?(:read, [1, 2, 3, 4]).should be_false
|
@ability.can?(:read, 1..4).should be_false
|
||||||
@ability.can?(:read, Array).should be_true
|
@ability.can?(:read, Range).should be_true
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should allow an array of options in conditions hash" do
|
it "should allow an array of options in conditions hash" do
|
||||||
@ability.can :read, Array, :first => [1, 3, 5]
|
@ability.can :read, Range, :begin => [1, 3, 5]
|
||||||
@ability.can?(:read, [1, 2, 3]).should be_true
|
@ability.can?(:read, 1..3).should be_true
|
||||||
@ability.can?(:read, [2, 3]).should be_false
|
@ability.can?(:read, 2..4).should be_false
|
||||||
@ability.can?(:read, [3, 4]).should be_true
|
@ability.can?(:read, 3..5).should be_true
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should allow a range of options in conditions hash" do
|
it "should allow a range of options in conditions hash" do
|
||||||
@ability.can :read, Array, :first => 1..3
|
@ability.can :read, Range, :begin => 1..3
|
||||||
@ability.can?(:read, [1, 2, 3]).should be_true
|
@ability.can?(:read, 1..10).should be_true
|
||||||
@ability.can?(:read, [3, 4]).should be_true
|
@ability.can?(:read, 3..30).should be_true
|
||||||
@ability.can?(:read, [4, 5]).should be_false
|
@ability.can?(:read, 4..40).should be_false
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should allow nested hashes in conditions hash" do
|
it "should allow nested hashes in conditions hash" do
|
||||||
@ability.can :read, Array, :first => { :length => 5 }
|
@ability.can :read, Range, :begin => { :to_i => 5 }
|
||||||
@ability.can?(:read, ["foo", "bar"]).should be_false
|
@ability.can?(:read, 5..7).should be_true
|
||||||
@ability.can?(:read, ["test1", "foo"]).should be_true
|
@ability.can?(:read, 6..8).should be_false
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should allow nested hash of arrays and match any element" do
|
it "should match any element passed in to nesting if it's an array (for has_many associations)" do
|
||||||
@ability.can :read, Array, :first => { :to_i => 3 }
|
@ability.can :read, Range, :to_a => { :to_i => 3 }
|
||||||
@ability.can?(:read, [[1, 2, 3]]).should be_true
|
@ability.can?(:read, 1..5).should be_true
|
||||||
@ability.can?(:read, [[4, 5, 6]]).should be_false
|
@ability.can?(:read, 4..6).should be_false
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should has eated cheezburger" do
|
it "should not stop at cannot definition when comparing class" do
|
||||||
lambda {
|
@ability.can :read, Range
|
||||||
@ability.can? :has, :cheezburger
|
@ability.cannot :read, Range, :begin => 1
|
||||||
}.should raise_error(CanCan::Error, "Nom nom nom. I eated it.")
|
@ability.can?(:read, 2..5).should be_true
|
||||||
|
@ability.can?(:read, 1..5).should be_false
|
||||||
|
@ability.can?(:read, Range).should be_true
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should stop at cannot definition when no hash is present" do
|
||||||
|
@ability.can :read, :all
|
||||||
|
@ability.cannot :read, Range
|
||||||
|
@ability.can?(:read, 1..5).should be_false
|
||||||
|
@ability.can?(:read, Range).should be_false
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should allow to check ability for Module" do
|
||||||
|
module B; end
|
||||||
|
class A; include B; end
|
||||||
|
@ability.can :read, B
|
||||||
|
@ability.can?(:read, A).should be_true
|
||||||
|
@ability.can?(:read, A.new).should be_true
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should pass nil to a block for ability on Module when no instance is passed" do
|
||||||
|
module B; end
|
||||||
|
class A; include B; end
|
||||||
|
@ability.can :read, B do |sym|
|
||||||
|
sym.should be_nil
|
||||||
|
true
|
||||||
|
end
|
||||||
|
@ability.can?(:read, B).should be_true
|
||||||
|
@ability.can?(:read, A).should be_true
|
||||||
|
end
|
||||||
|
|
||||||
|
it "passing a hash of subjects should check permissions through association" do
|
||||||
|
@ability.can :read, Range, :string => {:length => 3}
|
||||||
|
@ability.can?(:read, "foo" => Range).should be_true
|
||||||
|
@ability.can?(:read, "foobar" => Range).should be_false
|
||||||
|
@ability.can?(:read, 123 => Range).should be_true
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should have initial attributes based on hash conditions of 'new' action" do
|
||||||
|
@ability.can :manage, Range, :foo => "foo", :hash => {:skip => "hashes"}
|
||||||
|
@ability.can :create, Range, :bar => 123, :array => %w[skip arrays]
|
||||||
|
@ability.can :new, Range, :baz => "baz", :range => 1..3
|
||||||
|
@ability.cannot :new, Range, :ignore => "me"
|
||||||
|
@ability.attributes_for(:new, Range).should == {:foo => "foo", :bar => 123, :baz => "baz"}
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should raise access denied exception if ability us unauthorized to perform a certain action" do
|
||||||
|
begin
|
||||||
|
@ability.authorize! :read, :foo, 1, 2, 3, :message => "Access denied!"
|
||||||
|
rescue CanCan::AccessDenied => e
|
||||||
|
e.message.should == "Access denied!"
|
||||||
|
e.action.should == :read
|
||||||
|
e.subject.should == :foo
|
||||||
|
else
|
||||||
|
fail "Expected CanCan::AccessDenied exception to be raised"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should not raise access denied exception if ability is authorized to perform an action" do
|
||||||
|
@ability.can :read, :foo
|
||||||
|
lambda { @ability.authorize!(:read, :foo) }.should_not raise_error
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should know when block is used in conditions" do
|
||||||
|
@ability.can :read, :foo
|
||||||
|
@ability.should_not have_block(:read, :foo)
|
||||||
|
@ability.can :read, :foo do |foo|
|
||||||
|
false
|
||||||
|
end
|
||||||
|
@ability.should have_block(:read, :foo)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should know when raw sql is used in conditions" do
|
||||||
|
@ability.can :read, :foo
|
||||||
|
@ability.should_not have_raw_sql(:read, :foo)
|
||||||
|
@ability.can :read, :foo, 'false'
|
||||||
|
@ability.should have_raw_sql(:read, :foo)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should raise access denied exception with default message if not specified" do
|
||||||
|
begin
|
||||||
|
@ability.authorize! :read, :foo
|
||||||
|
rescue CanCan::AccessDenied => e
|
||||||
|
e.default_message = "Access denied!"
|
||||||
|
e.message.should == "Access denied!"
|
||||||
|
else
|
||||||
|
fail "Expected CanCan::AccessDenied exception to be raised"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
describe "unauthorized message" do
|
||||||
|
after(:each) do
|
||||||
|
I18n.backend = nil
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should use action/subject in i18n" do
|
||||||
|
I18n.backend.store_translations :en, :unauthorized => {:update => {:array => "foo"}}
|
||||||
|
@ability.unauthorized_message(:update, Array).should == "foo"
|
||||||
|
@ability.unauthorized_message(:update, [1, 2, 3]).should == "foo"
|
||||||
|
@ability.unauthorized_message(:update, :missing).should be_nil
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should use symbol as subject directly" do
|
||||||
|
I18n.backend.store_translations :en, :unauthorized => {:has => {:cheezburger => "Nom nom nom. I eated it."}}
|
||||||
|
@ability.unauthorized_message(:has, :cheezburger).should == "Nom nom nom. I eated it."
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should fall back to 'manage' and 'all'" do
|
||||||
|
I18n.backend.store_translations :en, :unauthorized => {
|
||||||
|
:manage => {:all => "manage all", :array => "manage array"},
|
||||||
|
:update => {:all => "update all", :array => "update array"}
|
||||||
|
}
|
||||||
|
@ability.unauthorized_message(:update, Array).should == "update array"
|
||||||
|
@ability.unauthorized_message(:update, Hash).should == "update all"
|
||||||
|
@ability.unauthorized_message(:foo, Array).should == "manage array"
|
||||||
|
@ability.unauthorized_message(:foo, Hash).should == "manage all"
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should follow aliased actions" do
|
||||||
|
I18n.backend.store_translations :en, :unauthorized => {:modify => {:array => "modify array"}}
|
||||||
|
@ability.alias_action :update, :to => :modify
|
||||||
|
@ability.unauthorized_message(:update, Array).should == "modify array"
|
||||||
|
@ability.unauthorized_message(:edit, Array).should == "modify array"
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should have variables for action and subject" do
|
||||||
|
I18n.backend.store_translations :en, :unauthorized => {:manage => {:all => "%{action} %{subject}"}} # old syntax for now in case testing with old I18n
|
||||||
|
@ability.unauthorized_message(:update, Array).should == "update array"
|
||||||
|
@ability.unauthorized_message(:edit, 1..3).should == "edit range"
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
require "spec_helper"
|
|
||||||
|
|
||||||
describe CanCan::ActiveRecordAdditions do
|
|
||||||
before(:each) do
|
|
||||||
@model_class = Class.new(Person)
|
|
||||||
stub(@model_class).scoped { :scoped_stub }
|
|
||||||
@model_class.send(:include, CanCan::ActiveRecordAdditions)
|
|
||||||
@ability = Object.new
|
|
||||||
@ability.extend(CanCan::Ability)
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should call where('true=false') when no ability is defined so no records are found" do
|
|
||||||
stub(@model_class).where('true=false').stub!.joins(nil) { :no_match }
|
|
||||||
@model_class.accessible_by(@ability, :read).should == :no_match
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should call where with matching ability conditions" do
|
|
||||||
@ability.can :read, @model_class, :foo => {:bar => 1}
|
|
||||||
stub(@model_class).where(:foos => { :bar => 1 }).stub!.joins([:foo]) { :found_records }
|
|
||||||
@model_class.accessible_by(@ability, :read).should == :found_records
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should default to :read ability and use scoped when where isn't available" do
|
|
||||||
@ability.can :read, @model_class, :foo => {:bar => 1}
|
|
||||||
stub(@model_class).scoped(:conditions => {:foos => {:bar => 1}}, :joins => [:foo]) { :found_records }
|
|
||||||
@model_class.accessible_by(@ability).should == :found_records
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should merge association joins and sanitize conditions" do
|
|
||||||
@ability.can :read, @model_class, :foo => {:bar => 1}
|
|
||||||
@ability.can :read, @model_class, :too => {:car => 1, :far => {:bar => 1}}
|
|
||||||
|
|
||||||
condition_variants = [
|
|
||||||
'(toos.fars.bar=1 AND toos.car=1) OR (foos.bar=1)', # faked sql sanitizer is stupid ;-)
|
|
||||||
'(toos.car=1 AND toos.fars.bar=1) OR (foos.bar=1)'
|
|
||||||
]
|
|
||||||
joins_variants = [
|
|
||||||
[:foo, {:too => [:far]}],
|
|
||||||
[{:too => [:far]}, :foo]
|
|
||||||
]
|
|
||||||
|
|
||||||
condition_variants.each do |condition|
|
|
||||||
joins_variants.each do |joins|
|
|
||||||
stub(@model_class).scoped( :conditions => condition, :joins => joins ) { :found_records }
|
|
||||||
end
|
|
||||||
end
|
|
||||||
# @ability.conditions(:read, @model_class).should == '(too.car=1 AND too.far.bar=1) OR (foo.bar=1)'
|
|
||||||
# @ability.associations_hash(:read, @model_class).should == [{:too => [:far]}, :foo]
|
|
||||||
@model_class.accessible_by(@ability).should == :found_records
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
require "spec_helper"
|
|
||||||
|
|
||||||
describe CanCan::CanDefinition do
|
|
||||||
before(:each) do
|
|
||||||
@conditions = {}
|
|
||||||
@can = CanCan::CanDefinition.new(true, :read, Integer, @conditions, nil)
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return no association joins if none exist" do
|
|
||||||
@can.associations_hash.should == {}
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return no association for joins if just attributes" do
|
|
||||||
@conditions[:foo] = :bar
|
|
||||||
@can.associations_hash.should == {}
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return single association for joins" do
|
|
||||||
@conditions[:foo] = {:bar => 1}
|
|
||||||
@can.associations_hash.should == {:foo => {}}
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return multiple associations for joins" do
|
|
||||||
@conditions[:foo] = {:bar => 1}
|
|
||||||
@conditions[:test] = {1 => 2}
|
|
||||||
@can.associations_hash.should == {:foo => {}, :test => {}}
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return nested associations for joins" do
|
|
||||||
@conditions[:foo] = {:bar => {1 => 2}}
|
|
||||||
@can.associations_hash.should == {:foo => {:bar => {}}}
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should tableize correctly for absurdly complex permissions" do
|
|
||||||
@conditions[:unit] = {:property=>{:landlord=>{:weasle_id=>560}}}
|
|
||||||
@conditions[:test] = 1
|
|
||||||
@can.tableized_conditions.should == {:units => {:properties => {:landlords=>{:weasle_id=>560}}}, :test => 1}
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should tableize correctly for complex permissions" do
|
|
||||||
@conditions[:unit] = {:property=>{:landlord_id=>560}}
|
|
||||||
@conditions[:test] = 1
|
|
||||||
@can.tableized_conditions.should == {:units => {:properties => {:landlord_id=>560}}, :test => 1}
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return table names in conditions for association joins" do
|
|
||||||
@conditions[:foo] = {:bar => 1}
|
|
||||||
@conditions[:test] = 1
|
|
||||||
@can.tableized_conditions.should == {:foos => {:bar => 1}, :test => 1}
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return no association joins if conditions is nil" do
|
|
||||||
can = CanCan::CanDefinition.new(true, :read, Integer, nil, nil)
|
|
||||||
can.associations_hash.should == {}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -14,32 +14,10 @@ describe CanCan::ControllerAdditions do
|
|||||||
lambda { @controller.unauthorized! }.should raise_error(CanCan::ImplementationRemoved)
|
lambda { @controller.unauthorized! }.should raise_error(CanCan::ImplementationRemoved)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should raise access denied exception if ability us unauthorized to perform a certain action" do
|
it "authorize! should assign @_authorized instance variable and pass args to current ability" do
|
||||||
begin
|
mock(@controller.current_ability).authorize!(:foo, :bar)
|
||||||
@controller.authorize! :read, :foo, 1, 2, 3, :message => "Access denied!"
|
@controller.authorize!(:foo, :bar)
|
||||||
rescue CanCan::AccessDenied => e
|
@controller.instance_variable_get(:@_authorized).should be_true
|
||||||
e.message.should == "Access denied!"
|
|
||||||
e.action.should == :read
|
|
||||||
e.subject.should == :foo
|
|
||||||
else
|
|
||||||
fail "Expected CanCan::AccessDenied exception to be raised"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should not raise access denied exception if ability is authorized to perform an action" do
|
|
||||||
@controller.current_ability.can :read, :foo
|
|
||||||
lambda { @controller.authorize!(:read, :foo) }.should_not raise_error
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should raise access denied exception with default message if not specified" do
|
|
||||||
begin
|
|
||||||
@controller.authorize! :read, :foo
|
|
||||||
rescue CanCan::AccessDenied => e
|
|
||||||
e.default_message = "Access denied!"
|
|
||||||
e.message.should == "Access denied!"
|
|
||||||
else
|
|
||||||
fail "Expected CanCan::AccessDenied exception to be raised"
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should have a current_ability method which generates an ability for the current user" do
|
it "should have a current_ability method which generates an ability for the current user" do
|
||||||
@@ -75,4 +53,64 @@ describe CanCan::ControllerAdditions do
|
|||||||
mock(@controller_class).before_filter(:only => [:show, :index]) { |options, block| block.call(@controller) }
|
mock(@controller_class).before_filter(:only => [:show, :index]) { |options, block| block.call(@controller) }
|
||||||
@controller_class.load_resource :foo => :bar, :only => [:show, :index]
|
@controller_class.load_resource :foo => :bar, :only => [:show, :index]
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it "skip_authorization_check should set up a before filter which sets @_authorized to true" do
|
||||||
|
mock(@controller_class).before_filter(:filter_options) { |options, block| block.call(@controller) }
|
||||||
|
@controller_class.skip_authorization_check(:filter_options)
|
||||||
|
@controller.instance_variable_get(:@_authorized).should be_true
|
||||||
|
end
|
||||||
|
|
||||||
|
it "check_authorization should trigger AuthorizationNotPerformed in after filter" do
|
||||||
|
mock(@controller_class).after_filter(:some_options) { |options, block| block.call(@controller) }
|
||||||
|
lambda {
|
||||||
|
@controller_class.check_authorization(:some_options)
|
||||||
|
}.should raise_error(CanCan::AuthorizationNotPerformed)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "check_authorization should not raise error when @_authorized is set" do
|
||||||
|
@controller.instance_variable_set(:@_authorized, true)
|
||||||
|
mock(@controller_class).after_filter(:some_options) { |options, block| block.call(@controller) }
|
||||||
|
lambda {
|
||||||
|
@controller_class.check_authorization(:some_options)
|
||||||
|
}.should_not raise_error(CanCan::AuthorizationNotPerformed)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "cancan_resource_class should be ControllerResource by default" do
|
||||||
|
@controller.class.cancan_resource_class.should == CanCan::ControllerResource
|
||||||
|
end
|
||||||
|
|
||||||
|
it "cancan_resource_class should be InheritedResource when class includes InheritedResources::Actions" do
|
||||||
|
stub(@controller.class).ancestors { ["InheritedResources::Actions"] }
|
||||||
|
@controller.class.cancan_resource_class.should == CanCan::InheritedResource
|
||||||
|
end
|
||||||
|
|
||||||
|
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
|
end
|
||||||
|
|||||||
@@ -2,77 +2,124 @@ require "spec_helper"
|
|||||||
|
|
||||||
describe CanCan::ControllerResource do
|
describe CanCan::ControllerResource do
|
||||||
before(:each) do
|
before(:each) do
|
||||||
@params = HashWithIndifferentAccess.new(:controller => "abilities")
|
@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).params { @params }
|
||||||
|
stub(@controller).current_ability { @ability }
|
||||||
|
stub(@controller_class).cancan_skipper { {:authorize => {}, :load => {}} }
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should load the resource into an instance variable if params[:id] is specified" do
|
it "should load the resource into an instance variable if params[:id] is specified" do
|
||||||
@params.merge!(:action => "show", :id => 123)
|
project = Project.create!
|
||||||
stub(Ability).find(123) { :some_resource }
|
@params.merge!(:action => "show", :id => project.id)
|
||||||
resource = CanCan::ControllerResource.new(@controller)
|
resource = CanCan::ControllerResource.new(@controller)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
@controller.instance_variable_get(:@project).should == project
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should not load resource into an instance variable if already set" do
|
it "should not load resource into an instance variable if already set" do
|
||||||
@params.merge!(:action => "show", :id => 123)
|
@params.merge!(:action => "show", :id => 123)
|
||||||
@controller.instance_variable_set(:@ability, :some_ability)
|
@controller.instance_variable_set(:@project, :some_project)
|
||||||
resource = CanCan::ControllerResource.new(@controller)
|
resource = CanCan::ControllerResource.new(@controller)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
@controller.instance_variable_get(:@project).should == :some_project
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should properly load resource for namespaced controller" do
|
it "should properly load resource for namespaced controller" do
|
||||||
@params.merge!(:controller => "admin/abilities", :action => "show", :id => 123)
|
project = Project.create!
|
||||||
stub(Ability).find(123) { :some_resource }
|
@params.merge!(:controller => "admin/projects", :action => "show", :id => project.id)
|
||||||
resource = CanCan::ControllerResource.new(@controller)
|
resource = CanCan::ControllerResource.new(@controller)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
@controller.instance_variable_get(:@project).should == project
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should properly load resource for namespaced controller when using '::' for namespace" do
|
it "should properly load resource for namespaced controller when using '::' for namespace" do
|
||||||
@params.merge!(:controller => "Admin::AbilitiesController", :action => "show", :id => 123)
|
project = Project.create!
|
||||||
stub(Ability).find(123) { :some_resource }
|
@params.merge!(:controller => "Admin::ProjectsController", :action => "show", :id => project.id)
|
||||||
resource = CanCan::ControllerResource.new(@controller)
|
resource = CanCan::ControllerResource.new(@controller)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
@controller.instance_variable_get(:@project).should == project
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should build a new resource with hash if params[:id] is not specified" do
|
it "should build a new resource with hash if params[:id] is not specified" do
|
||||||
@params.merge!(:action => "create", :ability => {:foo => "bar"})
|
@params.merge!(:action => "create", :project => {:name => "foobar"})
|
||||||
stub(Ability).new("foo" => "bar") { :some_resource }
|
|
||||||
resource = CanCan::ControllerResource.new(@controller)
|
resource = CanCan::ControllerResource.new(@controller)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should build a new resource with no arguments if attribute hash isn't specified" do
|
it "should build a new resource with attributes from current ability" do
|
||||||
@params[:action] = "new"
|
@params.merge!(:action => "new")
|
||||||
mock(Ability).new { :some_resource }
|
@ability.can(:create, Project, :name => "from conditions")
|
||||||
resource = CanCan::ControllerResource.new(@controller)
|
resource = CanCan::ControllerResource.new(@controller)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
@controller.instance_variable_get(:@project).name.should == "from conditions"
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should not build a resource when on index action" do
|
it "should override initial attributes with params" do
|
||||||
|
@params.merge!(:action => "new", :project => {:name => "from params"})
|
||||||
|
@ability.can(:create, Project, :name => "from conditions")
|
||||||
|
resource = CanCan::ControllerResource.new(@controller)
|
||||||
|
resource.load_resource
|
||||||
|
@controller.instance_variable_get(:@project).name.should == "from params"
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should build a collection when on index action when class responds to accessible_by" do
|
||||||
|
stub(Project).accessible_by(@ability) { :found_projects }
|
||||||
|
@params[:action] = "index"
|
||||||
|
resource = CanCan::ControllerResource.new(@controller, :project)
|
||||||
|
resource.load_resource
|
||||||
|
@controller.instance_variable_get(:@project).should be_nil
|
||||||
|
@controller.instance_variable_get(:@projects).should == :found_projects
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should not build a collection when on index action when class does not respond to accessible_by" do
|
||||||
@params[:action] = "index"
|
@params[:action] = "index"
|
||||||
resource = CanCan::ControllerResource.new(@controller)
|
resource = CanCan::ControllerResource.new(@controller)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should be_nil
|
@controller.instance_variable_get(:@project).should be_nil
|
||||||
|
@controller.instance_variable_defined?(:@projects).should be_false
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should not use accessible_by when defining abilities through a block" do
|
||||||
|
stub(Project).accessible_by(@ability) { :found_projects }
|
||||||
|
@params[:action] = "index"
|
||||||
|
@ability.can(:read, Project) { |p| false }
|
||||||
|
resource = CanCan::ControllerResource.new(@controller)
|
||||||
|
resource.load_resource
|
||||||
|
@controller.instance_variable_get(:@project).should be_nil
|
||||||
|
@controller.instance_variable_defined?(:@projects).should be_false
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should 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!(:read, :some_category) { raise CanCan::AccessDenied }
|
||||||
|
resource = CanCan::ControllerResource.new(@controller, :category, :parent => true)
|
||||||
|
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should perform authorization using controller action and loaded model" do
|
it "should perform authorization using controller action and loaded model" do
|
||||||
@params[:action] = "show"
|
@params[:action] = "show"
|
||||||
@controller.instance_variable_set(:@ability, :some_resource)
|
@controller.instance_variable_set(:@project, :some_project)
|
||||||
stub(@controller).authorize!(:show, :some_resource) { raise CanCan::AccessDenied }
|
stub(@controller).authorize!(:show, :some_project) { raise CanCan::AccessDenied }
|
||||||
resource = CanCan::ControllerResource.new(@controller)
|
resource = CanCan::ControllerResource.new(@controller)
|
||||||
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should perform authorization using controller action and non loaded model" do
|
it "should perform authorization using controller action and non loaded model" do
|
||||||
@params[:action] = "show"
|
@params[:action] = "show"
|
||||||
stub(@controller).authorize!(:show, Ability) { raise CanCan::AccessDenied }
|
stub(@controller).authorize!(:show, Project) { raise CanCan::AccessDenied }
|
||||||
resource = CanCan::ControllerResource.new(@controller)
|
resource = CanCan::ControllerResource.new(@controller)
|
||||||
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||||
end
|
end
|
||||||
@@ -89,146 +136,192 @@ describe CanCan::ControllerResource do
|
|||||||
@params[:action] = "sort"
|
@params[:action] = "sort"
|
||||||
resource = CanCan::ControllerResource.new(@controller, :collection => [:sort, :list])
|
resource = CanCan::ControllerResource.new(@controller, :collection => [:sort, :list])
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should be_nil
|
@controller.instance_variable_get(:@project).should be_nil
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should build a resource when on custom new action even when params[:id] exists" do
|
it "should build a resource when on custom new action even when params[:id] exists" do
|
||||||
@params.merge!(:action => "build", :id => 123)
|
@params.merge!(:action => "build", :id => 123)
|
||||||
stub(Ability).new { :some_resource }
|
stub(Project).new { :some_project }
|
||||||
resource = CanCan::ControllerResource.new(@controller, :new => :build)
|
resource = CanCan::ControllerResource.new(@controller, :new => :build)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
@controller.instance_variable_get(:@project).should == :some_project
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should not try to load resource for other action if params[:id] is undefined" do
|
it "should not try to load resource for other action if params[:id] is undefined" do
|
||||||
@params[:action] = "list"
|
@params[:action] = "list"
|
||||||
resource = CanCan::ControllerResource.new(@controller)
|
resource = CanCan::ControllerResource.new(@controller)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should be_nil
|
@controller.instance_variable_get(:@project).should be_nil
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should be a parent resource when name is provided which doesn't match controller" do
|
it "should be a parent resource when name is provided which doesn't match controller" do
|
||||||
resource = CanCan::ControllerResource.new(@controller, :person)
|
resource = CanCan::ControllerResource.new(@controller, :category)
|
||||||
resource.should be_parent
|
resource.should be_parent
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should not be a parent resource when name is provided which matches controller" do
|
it "should not be a parent resource when name is provided which matches controller" do
|
||||||
resource = CanCan::ControllerResource.new(@controller, :ability)
|
resource = CanCan::ControllerResource.new(@controller, :project)
|
||||||
resource.should_not be_parent
|
resource.should_not be_parent
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should be parent if specified in options" do
|
it "should be parent if specified in options" do
|
||||||
resource = CanCan::ControllerResource.new(@controller, :ability, {:parent => true})
|
resource = CanCan::ControllerResource.new(@controller, :project, {:parent => true})
|
||||||
resource.should be_parent
|
resource.should be_parent
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should not be parent if specified in options" do
|
it "should not be parent if specified in options" do
|
||||||
resource = CanCan::ControllerResource.new(@controller, :person, {:parent => false})
|
resource = CanCan::ControllerResource.new(@controller, :category, {:parent => false})
|
||||||
resource.should_not be_parent
|
resource.should_not be_parent
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should load parent resource through proper id parameter when supplying a resource with a different name" do
|
it "should load parent resource through proper id parameter" do
|
||||||
@params.merge!(:action => "index", :person_id => 123)
|
project = Project.create!
|
||||||
stub(Person).find(123) { :some_person }
|
@params.merge!(:action => "index", :project_id => project.id)
|
||||||
resource = CanCan::ControllerResource.new(@controller, :person)
|
resource = CanCan::ControllerResource.new(@controller, :project, :parent => true)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@person).should == :some_person
|
@controller.instance_variable_get(:@project).should == project
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should load parent resource for collection action" do
|
it "should load resource through the association of another parent resource using instance variable" do
|
||||||
@params.merge!(:action => "index", :person_id => 456)
|
|
||||||
stub(Person).find(456) { :some_person }
|
|
||||||
resource = CanCan::ControllerResource.new(@controller, :person)
|
|
||||||
resource.load_resource
|
|
||||||
@controller.instance_variable_get(:@person).should == :some_person
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should load resource through the association of another parent resource" do
|
|
||||||
@params.merge!(:action => "show", :id => 123)
|
@params.merge!(:action => "show", :id => 123)
|
||||||
person = Object.new
|
category = Object.new
|
||||||
@controller.instance_variable_set(:@person, person)
|
@controller.instance_variable_set(:@category, category)
|
||||||
stub(person).abilities.stub!.find(123) { :some_ability }
|
stub(category).projects.stub!.find(123) { :some_project }
|
||||||
resource = CanCan::ControllerResource.new(@controller, :through => :person)
|
resource = CanCan::ControllerResource.new(@controller, :through => :category)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
@controller.instance_variable_get(:@project).should == :some_project
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should not load through parent resource if instance isn't loaded" do
|
it "should load resource through the custom association name" do
|
||||||
@params.merge!(:action => "show", :id => 123)
|
@params.merge!(:action => "show", :id => 123)
|
||||||
stub(Ability).find(123) { :some_ability }
|
category = Object.new
|
||||||
resource = CanCan::ControllerResource.new(@controller, :through => :person)
|
@controller.instance_variable_set(:@category, category)
|
||||||
|
stub(category).custom_projects.stub!.find(123) { :some_project }
|
||||||
|
resource = CanCan::ControllerResource.new(@controller, :through => :category, :through_association => :custom_projects)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
@controller.instance_variable_get(:@project).should == :some_project
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should load resource through the association of another parent resource using method" do
|
||||||
|
@params.merge!(:action => "show", :id => 123)
|
||||||
|
category = Object.new
|
||||||
|
stub(@controller).category { category }
|
||||||
|
stub(category).projects.stub!.find(123) { :some_project }
|
||||||
|
resource = CanCan::ControllerResource.new(@controller, :through => :category)
|
||||||
|
resource.load_resource
|
||||||
|
@controller.instance_variable_get(:@project).should == :some_project
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should not load through parent resource if instance isn't loaded when shallow" do
|
||||||
|
project = Project.create!
|
||||||
|
@params.merge!(:action => "show", :id => project.id)
|
||||||
|
resource = CanCan::ControllerResource.new(@controller, :through => :category, :shallow => true)
|
||||||
|
resource.load_resource
|
||||||
|
@controller.instance_variable_get(:@project).should == project
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should raise AccessDenied when attempting to load resource through nil" do
|
||||||
|
project = Project.create!
|
||||||
|
@params.merge!(:action => "show", :id => project.id)
|
||||||
|
resource = CanCan::ControllerResource.new(@controller, :through => :category)
|
||||||
|
lambda {
|
||||||
|
resource.load_resource
|
||||||
|
}.should raise_error(CanCan::AccessDenied)
|
||||||
|
@controller.instance_variable_get(:@project).should be_nil
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should authorize nested resource through parent association on index action" do
|
||||||
|
@params.merge!(:action => "index")
|
||||||
|
category = Object.new
|
||||||
|
@controller.instance_variable_set(:@category, category)
|
||||||
|
stub(@controller).authorize!(:index, category => Project) { raise CanCan::AccessDenied }
|
||||||
|
resource = CanCan::ControllerResource.new(@controller, :through => :category)
|
||||||
|
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should load through first matching if multiple are given" do
|
it "should load through first matching if multiple are given" do
|
||||||
@params.merge!(:action => "show", :id => 123)
|
@params.merge!(:action => "show", :id => 123)
|
||||||
person = Object.new
|
category = Object.new
|
||||||
@controller.instance_variable_set(:@person, person)
|
@controller.instance_variable_set(:@category, category)
|
||||||
stub(person).abilities.stub!.find(123) { :some_ability }
|
stub(category).projects.stub!.find(123) { :some_project }
|
||||||
resource = CanCan::ControllerResource.new(@controller, :through => [:thing, :person])
|
resource = CanCan::ControllerResource.new(@controller, :through => [:category, :user])
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
@controller.instance_variable_get(:@project).should == :some_project
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should find record through has_one association with :singleton option" do
|
it "should find record through has_one association with :singleton option" do
|
||||||
@params.merge!(:action => "show")
|
@params.merge!(:action => "show")
|
||||||
person = Object.new
|
category = Object.new
|
||||||
@controller.instance_variable_set(:@person, person)
|
@controller.instance_variable_set(:@category, category)
|
||||||
stub(person).ability { :some_ability }
|
stub(category).project { :some_project }
|
||||||
resource = CanCan::ControllerResource.new(@controller, :through => :person, :singleton => true)
|
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
@controller.instance_variable_get(:@project).should == :some_project
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should build record through has_one association with :singleton option" do
|
it "should build record through has_one association with :singleton option" do
|
||||||
@params.merge!(:action => "create", :ability => :ability_attributes)
|
@params.merge!(:action => "create", :project => {:name => "foobar"})
|
||||||
person = Object.new
|
category = Object.new
|
||||||
@controller.instance_variable_set(:@person, person)
|
@controller.instance_variable_set(:@category, category)
|
||||||
stub(person).build_ability(:ability_attributes) { :new_ability }
|
stub(category).build_project { |attributes| Project.new(attributes) }
|
||||||
resource = CanCan::ControllerResource.new(@controller, :through => :person, :singleton => true)
|
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :new_ability
|
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should find record through has_one association with :singleton and :shallow options" do
|
||||||
|
project = Project.create!
|
||||||
|
@params.merge!(:action => "show", :id => project.id)
|
||||||
|
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true, :shallow => true)
|
||||||
|
resource.load_resource
|
||||||
|
@controller.instance_variable_get(:@project).should == project
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should build record through has_one association with :singleton and :shallow options" do
|
||||||
|
@params.merge!(:action => "create", :project => {:name => "foobar"})
|
||||||
|
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true, :shallow => true)
|
||||||
|
resource.load_resource
|
||||||
|
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should only authorize :read action on parent resource" do
|
it "should only authorize :read action on parent resource" do
|
||||||
@params.merge!(:action => "new", :person_id => 123)
|
project = Project.create!
|
||||||
stub(Person).find(123) { :some_person }
|
@params.merge!(:action => "new", :project_id => project.id)
|
||||||
stub(@controller).authorize!(:read, :some_person) { raise CanCan::AccessDenied }
|
stub(@controller).authorize!(:read, project) { raise CanCan::AccessDenied }
|
||||||
resource = CanCan::ControllerResource.new(@controller, :person)
|
resource = CanCan::ControllerResource.new(@controller, :project, :parent => true)
|
||||||
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
|
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should load the model using a custom class" do
|
it "should load the model using a custom class" do
|
||||||
@params.merge!(:action => "show", :id => 123)
|
project = Project.create!
|
||||||
stub(Person).find(123) { :some_resource }
|
@params.merge!(:action => "show", :id => project.id)
|
||||||
resource = CanCan::ControllerResource.new(@controller, :class => Person)
|
resource = CanCan::ControllerResource.new(@controller, :class => Project)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
@controller.instance_variable_get(:@project).should == project
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should authorize based on resource name if class is false" do
|
it "should authorize based on resource name if class is false" do
|
||||||
@params.merge!(:action => "show", :id => 123)
|
@params.merge!(:action => "show", :id => 123)
|
||||||
stub(@controller).authorize!(:show, :ability) { raise CanCan::AccessDenied }
|
stub(@controller).authorize!(:show, :project) { raise CanCan::AccessDenied }
|
||||||
resource = CanCan::ControllerResource.new(@controller, :class => false)
|
resource = CanCan::ControllerResource.new(@controller, :class => false)
|
||||||
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should load and authorize using custom instance name" do
|
it "should load and authorize using custom instance name" do
|
||||||
@params.merge!(:action => "show", :id => 123)
|
project = Project.create!
|
||||||
stub(Ability).find(123) { :some_ability }
|
@params.merge!(:action => "show", :id => project.id)
|
||||||
stub(@controller).authorize!(:show, :some_ability) { raise CanCan::AccessDenied }
|
stub(@controller).authorize!(:show, project) { raise CanCan::AccessDenied }
|
||||||
resource = CanCan::ControllerResource.new(@controller, :instance_name => :custom_ability)
|
resource = CanCan::ControllerResource.new(@controller, :instance_name => :custom_project)
|
||||||
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
|
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||||
@controller.instance_variable_get(:@custom_ability).should == :some_ability
|
@controller.instance_variable_get(:@custom_project).should == project
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should load resource using custom find_by attribute" do
|
it "should load resource using custom find_by attribute" do
|
||||||
@params.merge!(:action => "show", :id => 123)
|
project = Project.create!(:name => "foo")
|
||||||
stub(Ability).find_by_name!(123) { :some_resource }
|
@params.merge!(:action => "show", :id => "foo")
|
||||||
resource = CanCan::ControllerResource.new(@controller, :find_by => :name)
|
resource = CanCan::ControllerResource.new(@controller, :find_by => :name)
|
||||||
resource.load_resource
|
resource.load_resource
|
||||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
@controller.instance_variable_get(:@project).should == project
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should raise ImplementationRemoved when adding :name option" do
|
it "should raise ImplementationRemoved when adding :name option" do
|
||||||
@@ -239,13 +332,61 @@ describe CanCan::ControllerResource do
|
|||||||
|
|
||||||
it "should raise ImplementationRemoved exception when specifying :resource option since it is no longer used" do
|
it "should raise ImplementationRemoved exception when specifying :resource option since it is no longer used" do
|
||||||
lambda {
|
lambda {
|
||||||
CanCan::ControllerResource.new(@controller, :resource => Person)
|
CanCan::ControllerResource.new(@controller, :resource => Project)
|
||||||
}.should raise_error(CanCan::ImplementationRemoved)
|
}.should raise_error(CanCan::ImplementationRemoved)
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should raise ImplementationRemoved exception when passing :nested option" do
|
it "should raise ImplementationRemoved exception when passing :nested option" do
|
||||||
lambda {
|
lambda {
|
||||||
CanCan::ControllerResource.new(@controller, :nested => :person)
|
CanCan::ControllerResource.new(@controller, :nested => :project)
|
||||||
}.should raise_error(CanCan::ImplementationRemoved)
|
}.should raise_error(CanCan::ImplementationRemoved)
|
||||||
end
|
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
|
end
|
||||||
|
|||||||
42
spec/cancan/inherited_resource_spec.rb
Normal file
42
spec/cancan/inherited_resource_spec.rb
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
require "spec_helper"
|
||||||
|
|
||||||
|
describe CanCan::InheritedResource do
|
||||||
|
before(:each) do
|
||||||
|
@params = HashWithIndifferentAccess.new(:controller => "projects")
|
||||||
|
@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"
|
||||||
|
stub(@controller).resource { :project_resource }
|
||||||
|
CanCan::InheritedResource.new(@controller).load_resource
|
||||||
|
@controller.instance_variable_get(:@project).should == :project_resource
|
||||||
|
end
|
||||||
|
|
||||||
|
it "new should load through @controller.build_resource" do
|
||||||
|
@params[:action] = "new"
|
||||||
|
stub(@controller).build_resource { :project_resource }
|
||||||
|
CanCan::InheritedResource.new(@controller).load_resource
|
||||||
|
@controller.instance_variable_get(:@project).should == :project_resource
|
||||||
|
end
|
||||||
|
|
||||||
|
it "index should load through @controller.parent when parent" do
|
||||||
|
@params[:action] = "index"
|
||||||
|
stub(@controller).parent { :project_resource }
|
||||||
|
CanCan::InheritedResource.new(@controller, :parent => true).load_resource
|
||||||
|
@controller.instance_variable_get(:@project).should == :project_resource
|
||||||
|
end
|
||||||
|
|
||||||
|
it "index should load through @controller.end_of_association_chain" do
|
||||||
|
@params[:action] = "index"
|
||||||
|
stub(Project).accessible_by(@ability) { :projects }
|
||||||
|
stub(@controller).end_of_association_chain { Project }
|
||||||
|
CanCan::InheritedResource.new(@controller).load_resource
|
||||||
|
@controller.instance_variable_get(:@projects).should == :projects
|
||||||
|
end
|
||||||
|
end
|
||||||
185
spec/cancan/model_adapters/active_record_adapter_spec.rb
Normal file
185
spec/cancan/model_adapters/active_record_adapter_spec.rb
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
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 :article do
|
||||||
|
table do |t|
|
||||||
|
t.boolean "published"
|
||||||
|
t.boolean "secret"
|
||||||
|
end
|
||||||
|
model do
|
||||||
|
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 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 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
|
||||||
|
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
|
||||||
168
spec/cancan/model_adapters/mongoid_adapter_spec.rb
Normal file
168
spec/cancan/model_adapters/mongoid_adapter_spec.rb
Normal file
@@ -0,0 +1,168 @@
|
|||||||
|
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).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 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, Person).conditions.should == "true=false"
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return hash for single `can` definition" do
|
|
||||||
@ability.can :read, Person, :blocked => false, :user_id => 1
|
|
||||||
@ability.query(:read, Person).conditions.should == { :blocked => false, :user_id => 1 }
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should merge multiple can definitions into single SQL string joining with OR" do
|
|
||||||
@ability.can :read, Person, :blocked => false
|
|
||||||
@ability.can :read, Person, :admin => true
|
|
||||||
@ability.query(:read, Person).conditions.should == "(admin=true) OR (blocked=false)"
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should merge multiple can definitions into single SQL string joining with OR and AND" do
|
|
||||||
@ability.can :read, Person, :blocked => false, :active => true
|
|
||||||
@ability.can :read, Person, :admin => true
|
|
||||||
@ability.query(:read, Person).conditions.should orderlessly_match("(blocked=false AND active=true) OR (admin=true)")
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should merge multiple can definitions into single SQL string joining with OR and AND" do
|
|
||||||
@ability.can :read, Person, :blocked => false, :active => true
|
|
||||||
@ability.can :read, Person, :admin => true
|
|
||||||
@ability.query(:read, Person).conditions.should orderlessly_match("(blocked=false AND active=true) OR (admin=true)")
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return false conditions for cannot clause" do
|
|
||||||
@ability.cannot :read, Person
|
|
||||||
@ability.query(:read, Person).conditions.should == "true=false"
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return SQL for single `can` definition in front of default `cannot` condition" do
|
|
||||||
@ability.cannot :read, Person
|
|
||||||
@ability.can :read, Person, :blocked => false, :user_id => 1
|
|
||||||
@ability.query(:read, Person).conditions.should orderlessly_match("blocked=false AND user_id=1")
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return true condition for single `can` definition in front of default `can` condition" do
|
|
||||||
@ability.can :read, Person
|
|
||||||
@ability.can :read, Person, :blocked => false, :user_id => 1
|
|
||||||
@ability.query(:read, Person).conditions.should == 'true=true'
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return false condition for single `cannot` definition" do
|
|
||||||
@ability.cannot :read, Person, :blocked => true, :user_id => 1
|
|
||||||
@ability.query(:read, Person).conditions.should == 'true=false'
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return `false condition` for single `cannot` definition in front of default `cannot` condition" do
|
|
||||||
@ability.cannot :read, Person
|
|
||||||
@ability.cannot :read, Person, :blocked => true, :user_id => 1
|
|
||||||
@ability.query(:read, Person).conditions.should == 'true=false'
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return `not (sql)` for single `cannot` definition in front of default `can` condition" do
|
|
||||||
@ability.can :read, Person
|
|
||||||
@ability.cannot :read, Person, :blocked => true, :user_id => 1
|
|
||||||
@ability.query(:read, Person).conditions.should orderlessly_match("not (blocked=true AND user_id=1)")
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should return appropriate sql conditions in complex case" do
|
|
||||||
@ability.can :read, Person
|
|
||||||
@ability.can :manage, Person, :id => 1
|
|
||||||
@ability.can :update, Person, :manager_id => 1
|
|
||||||
@ability.cannot :update, Person, :self_managed => true
|
|
||||||
@ability.query(:update, Person).conditions.should == 'not (self_managed=true) AND ((manager_id=1) OR (id=1))'
|
|
||||||
@ability.query(:manage, Person).conditions.should == {:id=>1}
|
|
||||||
@ability.query(:read, Person).conditions.should == 'true=true'
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should have nil joins if no can definitions" do
|
|
||||||
@ability.query(:read, Person).joins.should be_nil
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should have nil joins if no nested hashes specified in conditions" do
|
|
||||||
@ability.can :read, Person, :blocked => false
|
|
||||||
@ability.can :read, Person, :admin => true
|
|
||||||
@ability.query(:read, Person).joins.should be_nil
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should merge separate joins into a single array" do
|
|
||||||
@ability.can :read, Person, :project => { :blocked => false }
|
|
||||||
@ability.can :read, Person, :company => { :admin => true }
|
|
||||||
@ability.query(:read, Person).joins.inspect.should orderlessly_match([:company, :project].inspect)
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should merge same joins into a single array" do
|
|
||||||
@ability.can :read, Person, :project => { :blocked => false }
|
|
||||||
@ability.can :read, Person, :project => { :admin => true }
|
|
||||||
@ability.query(:read, Person).joins.should == [:project]
|
|
||||||
end
|
|
||||||
|
|
||||||
it "should merge complex, nested joins" do
|
|
||||||
@ability.can :read, Person, :project => { :bar => {:test => true} }, :company => { :bar => {:test => true} }
|
|
||||||
@ability.can :read, Person, :project => { :foo => {:bar => true}, :bar => {:zip => :zap} }
|
|
||||||
@ability.query(:read, Person).joins.inspect.should orderlessly_match([{:project => [:bar, :foo]}, {:company => [:bar]}].inspect)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
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,4 +1,4 @@
|
|||||||
Spec::Matchers.define :orderlessly_match do |original_string|
|
RSpec::Matchers.define :orderlessly_match do |original_string|
|
||||||
match do |given_string|
|
match do |given_string|
|
||||||
original_string.split('').sort == given_string.split('').sort
|
original_string.split('').sort == given_string.split('').sort
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
--color
|
--color
|
||||||
|
--backtrace
|
||||||
|
|||||||
@@ -1,15 +1,19 @@
|
|||||||
require 'rubygems'
|
require 'rubygems'
|
||||||
require 'spec'
|
require 'bundler/setup'
|
||||||
require 'active_support'
|
|
||||||
require 'active_record'
|
Bundler.require(:default)
|
||||||
require 'action_controller'
|
|
||||||
require 'action_view'
|
require 'supermodel' # shouldn't Bundler do this already?
|
||||||
|
require 'active_support/all'
|
||||||
require 'matchers'
|
require 'matchers'
|
||||||
require 'cancan'
|
|
||||||
require 'cancan/matchers'
|
require 'cancan/matchers'
|
||||||
|
|
||||||
Spec::Runner.configure do |config|
|
RSpec.configure do |config|
|
||||||
config.mock_with :rr
|
config.mock_with :rr
|
||||||
|
config.before(:each) do
|
||||||
|
Project.delete_all
|
||||||
|
Category.delete_all
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
class Ability
|
class Ability
|
||||||
@@ -19,29 +23,10 @@ class Ability
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
# this class helps out in testing SQL conditions
|
class Category < SuperModel::Base
|
||||||
class Person
|
has_many :projects
|
||||||
class << self
|
end
|
||||||
protected
|
|
||||||
|
class Project < SuperModel::Base
|
||||||
def sanitize_sql(hash_cond)
|
belongs_to :category
|
||||||
case hash_cond
|
|
||||||
when Hash
|
|
||||||
sanitize_hash(hash_cond).join(' AND ')
|
|
||||||
when Array
|
|
||||||
hash_cond.shift.gsub('?'){"#{hash_cond.shift.inspect}"}
|
|
||||||
when String then hash_cond
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def sanitize_hash(hash)
|
|
||||||
hash.map do |name, value|
|
|
||||||
if Hash === value
|
|
||||||
sanitize_hash(value).map{|cond| "#{name}.#{cond}"}
|
|
||||||
else
|
|
||||||
"#{name}=#{value}"
|
|
||||||
end
|
|
||||||
end.flatten
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user