Compare commits

..

No commits in common. "master" and "0.2.1" have entirely different histories.

46 changed files with 553 additions and 4008 deletions

4
.gitignore vendored
View File

@ -1,5 +1 @@
*.swp
**/*.swp
*.gem
Gemfile.lock
.bundle

View File

@ -1 +0,0 @@
1.8.7-p357

1
.rspec
View File

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

1
.rvmrc
View File

@ -1 +0,0 @@
rvm use 1.8.7@cancan --create

View File

@ -1,7 +0,0 @@
rvm:
- 1.8.7
- ree
notifications:
recipients:
- graf.otodrakula@gmail.com
- ryan@railscasts.com

View File

@ -1,380 +1,3 @@
1.6.10 (May 7, 2013)
* fix matches_conditons_hash for string values on 1.8 (thanks rrosen)
* work around SQL injection vulnerability in older Rails versions (thanks steerio) - issue #800
* add support for nested join conditions (thanks yuszuv) - issue #806
* fix load_resource "find_by" in mongoid resources (thanks albertobajo) - issue #705
* fix namespace split behavior (thanks xinuc) - issue #668
1.6.9 (February 4, 2013)
* fix inserting AND (NULL) to end of SQL queries (thanks jonsgreen) - issue #687
* fix merge_joins for nested association hashes (thanks DavidMikeSimon) - issues #655, #560
* raise error on recursive alias_action (thanks fl00r) - issue #660
* fix namespace controllers not loading params (thanks andhapp) - issues #670, #664
1.6.8 (June 25, 2012)
* improved support for namespaced controllers and models
* pass :if and :unless options for load and authorize resource (thanks mauriciozaffari)
* Travis CI badge (thanks plentz)
* adding Ability#merge for combining multiple abilities (thanks rogercampos)
* support for multiple MetaWhere rules (thanks andhapp)
* various fixes for DataMapper, Mongoid, and Inherited Resource integration
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.6.7...1.6.8]
1.6.7 (October 4, 2011)
* fixing nested resource problem caused by namespace addition - issue #482
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.6.6...1.6.7]
1.6.6 (September 28, 2011)
* correct "return cant jump across threads" error when using check_authorization (thanks codeprimate) - issues #463, #469
* fixing tests in development by specifying with_model version (thanks kirkconnell) - issue #476
* added travis.yml file for TravisCI support (thanks bai) - issue #427
* better support for namespaced models (thanks whilefalse) - issues #424
* adding :id_param option to load_and_authorize_resource (thanks skhisma) - issue #425
* make default unauthorized message translatable text (thanks nhocki) - issue #409
* improving DataMapper behavior (thanks psanford, maxsum-corin) - issue #410, #373
* allow :find_by option to be full find method name - issue #335
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.6.5...1.6.6]
1.6.5 (May 18, 2011)
* pass action and subject through AccessDenied exception when :through isn't found - issue #366
* many Mongoid adapter improvements (thanks rahearn, cardagin) - issues #363, #352, #343
* allow :through option to work with private controller methods - issue #360
* ensure Mongoid::Document is defined before loading Mongoid adapter - issue #359
* many DataMapper adapter improvements (thanks emmanuel) - issue #355
* handle checking nil attributes through associations (thanks thatothermitch) - issue #330
* improve scope merging - issue #328
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.6.4...1.6.5]
1.6.4 (March 29, 2011)
* Fixed mongoid 'or' error - see issue #322
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.6.3...1.6.4]
1.6.3 (March 25, 2011)
* Make sure ActiveRecord::Relation is defined before checking conditions against it so Rails 2 is supported again - see issue #312
* Return subject passed to authorize! - see issue #314
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.6.2...1.6.3]
1.6.2 (March 18, 2011)
* Fixed instance loading when :singleton option is used - see issue #310
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.6.1...1.6.2]
1.6.1 (March 15, 2011)
* Use Item.new instead of build_item for singleton resource so it doesn't effect database - see issue #304
* Made accessible_by action default to :index and parent action default to :show instead of :read - see issue #302
* Reverted Inherited Resources "collection" override since it doesn't seem to be working - see issue #305
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.6.0...1.6.1]
1.6.0 (March 11, 2011)
* Added MetaWhere support - see issue #194 and #261
* Allow Active Record scopes in Ability conditions - see issue #257
* Added :if and :unless options to check_authorization - see issue #284
* Several Inherited Resources fixes (thanks aq1018, tanordheim and stefanoverna)
* Pass action name to accessible_by call when loading a collection (thanks amw)
* Added :prepend option to load_and_authorize_resource to load before other filters - see issue #290
* Fixed spacing issue in I18n message for multi-word model names - see issue #292
* Load resource collection for any action which doesn't have an "id" parameter - see issue #296
* Raise an exception when trying to make a Ability condition with both a hash of conditions and a block - see issue #269
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.5.1...1.6.0]
1.5.1 (January 20, 2011)
* Fixing deeply nested conditions in Active Record adapter - see issue #246
* Improving Mongoid support for multiple can and cannot definitions (thanks stellard) - see issue #239
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.5.0...1.5.1]
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
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.4.1...1.5.0]
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
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.4.0...1.4.1]
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
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.3.4...1.4.0]
1.3.4 (August 31, 2010)
* Don't stop at +cannot+ with hash conditions when checking class (thanks tamoya) - see issue #131
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.3.3...1.3.4]
1.3.3 (August 20, 2010)
* Switching to Rspec namespace to remove deprecation warning in Rspec 2 - see issue #119
* Pluralize nested associations for conditions in accessible_by (thanks mlooney) - see issue #123
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.3.2...1.3.3]
1.3.2 (August 7, 2010)
* Fixing slice error when passing in custom resource name - see issue #112
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.3.1...1.3.2]
1.3.1 (August 6, 2010)
* Fixing protected sanitize_sql error - see issue #111
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.3.0...1.3.1]
1.3.0 (August 6, 2010)
* Adding :find_by option to load_resource - see issue #19
* Adding :singleton option to load_resource - see issue #93
* Supporting multiple resources in :through option for polymorphic associations - see issue #73
* Supporting Single Table Inheritance for "can" comparisons - see issue #55
* Adding :instance_name option to load/authorize_resource - see issue #44
* Don't pass nil to "new" to keep MongoMapper happy - see issue #63
* Parent resources are now authorized with :read action.
* Changing :resource option in load/authorize_resource back to :class with ability to pass false
* Removing :nested option in favor of :through option with separate load/authorize call
* Moving internal logic from ResourceAuthorization to ControllerResource class
* Supporting multiple "can" and "cannot" calls with accessible_by (thanks funny-falcon) - see issue #71
* Supporting deeply nested aliases - see issue #98
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.2.0...1.3.0]
1.2.0 (July 16, 2010)
* Load nested parent resources on collection actions such as "index" (thanks dohzya)
* Adding :name option to load_and_authorize_resource if it does not match controller - see issue #65
* Fixing issue when using accessible_by with nil can conditions (thanks jrallison) - see issue #66
* Pluralize table name for belongs_to associations in can conditions hash (thanks logandk) - see issue #62
* Support has_many association or arrays in can conditions hash
* Adding joins clause to accessible_by when conditions are across associations
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.1.1...1.2.0]
1.1.1 (April 17, 2010)
* Fixing behavior in Rails 3 by properly initializing ResourceAuthorization
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.1...1.1.1]
1.1.0 (April 17, 2010)
* Supporting arrays, ranges, and nested hashes in ability conditions
* Removing "unauthorized!" method in favor of "authorize!" in controllers
* Adding action, subject and default_message abilities to AccessDenied exception - see issue #40
* Adding caching to current_ability controller method, if you're overriding this be sure to add caching too.
* Adding "accessible_by" method to Active Record for fetching records matching a specific ability
* Adding conditions behavior to Ability#can and fetch with Ability#conditions - see issue #53
* Renaming :class option to :resource for load_and_authorize_resource which now supports a symbol for non models - see issue #45
* Properly handle Admin::AbilitiesController in params[:controller] - see issue #46
* Adding be_able_to RSpec matcher (thanks dchelimsky), requires Ruby 1.8.7 or higher - see issue #54
* Support additional arguments to can? which get passed to the block - see issue #48
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.0.2...1.1]
1.0.2 (Dec 30, 2009)
* Adding clear_aliased_actions to Ability which removes previously defined actions including defaults - see issue #20
* Append aliased actions (don't overwrite them) - see issue #20
* Adding custom message argument to unauthorized! method (thanks tjwallace) - see issue #18
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.0.1...1.0.2]
1.0.1 (Dec 14, 2009)
* Adding :class option to load_resource so one can customize which class to use for the model - see issue #17
* Don't fetch parent of nested resource if *_id parameter is missing so it works with shallow nested routes - see issue #14
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/1.0.0...1.0.1]
1.0.0 (Dec 13, 2009)
* Don't set resource instance variable if it has been set already - see issue #13
* Allowing :nested option to accept an array for deep nesting
* Adding :nested option to load resource method - see issue #10
* Pass :only and :except options to before filters for load/authorize resource methods.
* Adding :collection and :new options to load_resource method so we can specify behavior of additional actions if needed.
* BACKWARDS INCOMPATIBLE: turning load and authorize resource methods into class methods which set up the before filter so they can accept additional arguments.
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/0.2.1...1.0.0]
0.2.1 (Nov 26, 2009)
* many internal refactorings - see issues #11 and #12
@ -383,9 +6,6 @@
* support custom objects (usually symbols) in can definition - see issue #8
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/0.2.0...0.2.1]
0.2.0 (Nov 17, 2009)
* fix behavior of load_and_authorize_resource for namespaced controllers - see issue #3
@ -396,8 +16,6 @@
* BACKWARDS INCOMPATIBLE: use Ability#initialize instead of 'prepare' to set up abilities - see issue #4
* {see the full list of changes}[https://github.com/ryanb/cancan/compare/0.1.0...0.2.0]
0.1.0 (Nov 16, 2009)

View File

@ -1,11 +0,0 @@
### Please read before contributing
1) If you have any questions about CanCan, search the [Wiki](https://github.com/ryanb/cancan/wiki) or use [Stack Overflow](http://stackoverflow.com/questions/tagged/cancan). Do not post questions here.
2) If you find a security bug, **DO NOT** submit an issue here. Please send an e-mail to [ryan@railscasts.com](mailto:ryan@railscasts.com) instead.
3) Do a small search on the issues tracker before submitting your issue to see if it was already reported / fixed. In case it was not, create your report including Rails and CanCan versions. If you are getting exceptions, please include the full backtrace.
That's it! The more information you give, the more easy it becomes for us to track it down and fix it. Ideal scenario would be adding the issue to CanCan test suite or to a sample application.
Thanks!

20
Gemfile
View File

@ -1,20 +0,0 @@
source "http://rubygems.org"
case ENV["MODEL_ADAPTER"]
when nil, "active_record"
gem "sqlite3"
gem "activerecord", '~> 3.0.9', :require => "active_record"
gem "with_model", "~> 0.2.5"
gem "meta_where"
when "data_mapper"
gem "dm-core", "~> 1.0.2"
gem "dm-sqlite-adapter", "~> 1.0.2"
gem "dm-migrations", "~> 1.0.2"
when "mongoid"
gem "bson_ext", "~> 1.1"
gem "mongoid", "~> 2.0.0.beta.20"
else
raise "Unknown model adapter: #{ENV["MODEL_ADAPTER"]}"
end
gemspec

View File

@ -1,4 +1,4 @@
Copyright (c) 2011 Ryan Bates
Copyright (c) 2009 Ryan Bates
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

View File

@ -1,120 +1,183 @@
= CanCan {<img src="https://fury-badge.herokuapp.com/rb/cancan.png" alt="Gem Version" />}[http://badge.fury.io/rb/cancan] {<img src="https://secure.travis-ci.org/ryanb/cancan.png?branch=master" />}[http://travis-ci.org/ryanb/cancan] {<img src="https://codeclimate.com/badge.png" />}[https://codeclimate.com/github/ryanb/cancan]
= CanCan
Wiki[https://github.com/ryanb/cancan/wiki] | RDocs[http://rdoc.info/projects/ryanb/cancan] | Screencast[http://railscasts.com/episodes/192-authorization-with-cancan]
This is a simple authorization solution for Ruby on Rails to restrict what a given user is allowed to access in the application. This is completely decoupled from any role based implementation allowing you to define user roles the way you want. All permissions are stored in a single location for convenience.
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.
This assumes you already have authentication (such as Authlogic[http://github.com/binarylogic/authlogic]) which provides a current_user model.
See the RDocs[http://rdoc.info/projects/ryanb/cancan] and Wiki[http://wiki.github.com/ryanb/cancan] for additional documentation.
== Installation
In <b>Rails 3</b>, add this to your Gemfile and run the +bundle+ command.
You can set it up as a gem in your environment.rb file.
config.gem "cancan", :source => "http://gemcutter.org"
And then install the gem.
gem "cancan"
sudo rake gems:install
In <b>Rails 2</b>, add this to your environment.rb file.
Alternatively you can install it as a Rails plugin.
config.gem "cancan"
Alternatively, you can install it as a plugin.
rails plugin install git://github.com/ryanb/cancan.git
script/plugin install git://github.com/ryanb/cancan.git
== Getting Started
== Setup
CanCan expects a +current_user+ method to exist in the controller. First, set up some authentication (such as Authlogic[https://github.com/binarylogic/authlogic] or Devise[https://github.com/plataformatec/devise]). See {Changing Defaults}[https://github.com/ryanb/cancan/wiki/changing-defaults] if you need different behavior.
=== 1. Define Abilities
User permissions are defined in an +Ability+ class. CanCan 1.5 includes a Rails 3 generator for creating this class.
rails g cancan:ability
In Rails 2.3, just add a new class in `app/models/ability.rb` with the folowing contents:
First, define a class called Ability in "models/ability.rb".
class Ability
include CanCan::Ability
def initialize(user)
if user.admin?
can :manage, :all
else
can :read, :all
end
end
end
See {Defining Abilities}[https://github.com/ryanb/cancan/wiki/defining-abilities] for details.
This is where all permissions will go. See the "Defining Abilities" section below for more information.
=== 2. Check Abilities & Authorization
The current user's permissions can then be checked using the <tt>can?</tt> and <tt>cannot?</tt> methods in the view and controller.
You can access the current permissions at any point using the "can?" and "cannot?" methods in the view.
<% if can? :update, @article %>
<%= link_to "Edit", edit_article_path(@article) %>
<% end %>
See {Checking Abilities}[https://github.com/ryanb/cancan/wiki/checking-abilities] for more information
The <tt>authorize!</tt> method in the controller will raise an exception if the user is not able to perform the given action.
You can also use these methods in a controller along with the "unauthorized!" method to restrict access.
def show
@article = Article.find(params[:id])
authorize! :read, @article
unauthorized! if cannot? :read, @article
end
Setting this for every action can be tedious, therefore the +load_and_authorize_resource+ method is provided to automatically authorize all actions in a RESTful style resource controller. It will use a before filter to load the resource into an instance variable and authorize it for every action.
Setting this for every action can be tedious, therefore a before filter is also provided to automatically authorize all actions in a RESTful style resource controller.
class ArticlesController < ApplicationController
load_and_authorize_resource
before_filter :load_and_authorize_resource
def show
# @article is already loaded and authorized
# @article is already loaded
end
end
See {Authorizing Controller Actions}[https://github.com/ryanb/cancan/wiki/authorizing-controller-actions] for more information.
=== 3. Handle Unauthorized Access
If the user authorization fails, a <tt>CanCan::AccessDenied</tt> exception will be raised. You can catch this and modify its behavior in the +ApplicationController+.
If the user authorization fails, a CanCan::AccessDenied exception will be raised. You can catch this and modify its behavior in the ApplicationController.
class ApplicationController < ActionController::Base
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url, :alert => exception.message
rescue_from CanCan::AccessDenied, :with => :access_denied
protected
def access_denied
flash[:error] = "Sorry, you are not allowed to access that page."
redirect_to root_url
end
end
See {Exception Handling}[https://github.com/ryanb/cancan/wiki/exception-handling] for more information.
== Defining Abilities
=== 4. Lock It Down
As shown above, the Ability class is where all user permissions are defined. The user model is passed into the initialize method so you are free to modify the permissions based on the user's attributes. This way CanCan is completely decoupled with how you choose to handle roles.
If you want to ensure authorization happens on every action in your application, add +check_authorization+ to your ApplicationController.
The "can" method accepts two arguments, the first one is the action you're setting the permission for, the second one is the class of object you're setting it on.
class ApplicationController < ActionController::Base
check_authorization
can :update, Article
You can pass an array for either of these parameters to match any one.
can [:update, :destroy], [Article, Comment]
In this case the user has the ability to update or destroy both articles and comments.
You can pass a block to provide logic based on the article's attributes.
can :update, Article do |article|
article && article.user == user
end
This will raise an exception if authorization is not performed in an action. If you want to skip this add +skip_authorization_check+ to a controller subclass. See {Ensure Authorization}[https://github.com/ryanb/cancan/wiki/Ensure-Authorization] for more information.
If the block returns true then the user has that :update ability for that article, otherwise he will be denied access. It's possible for the passed in model to be nil if one isn't specified, so be sure to take that into consideration.
You can pass :all to reference every type of object. In this case the object type will be passed into the block as well (just in case object is nil).
can :read, :all do |object_class, object|
object_class != Order
end
Here the user has permission to read all objects except orders.
You can also pass :manage as the action which will match any action. In this case the action is passed to the block.
can :manage, Comment do |action, comment|
action != :destroy
end
Finally, the "cannot" method works similar to "can" but defines which abilities cannot be done.
can :read, :all
cannot :read, Product
== Wiki Docs
== Checking Abilities
* {Upgrading to 1.6}[https://github.com/ryanb/cancan/wiki/Upgrading-to-1.6]
* {Defining Abilities}[https://github.com/ryanb/cancan/wiki/Defining-Abilities]
* {Checking Abilities}[https://github.com/ryanb/cancan/wiki/Checking-Abilities]
* {Authorizing Controller Actions}[https://github.com/ryanb/cancan/wiki/Authorizing-Controller-Actions]
* {Exception Handling}[https://github.com/ryanb/cancan/wiki/Exception-Handling]
* {Changing Defaults}[https://github.com/ryanb/cancan/wiki/Changing-Defaults]
* {See more}[https://github.com/ryanb/cancan/wiki]
Use the "can?" method in the controller or view to check the user's permission for a given action and object.
can? :destroy, @project
You can also pass the class instead of an instance (if you don't have one handy).
<% if can? :create, Project %>
<%= link_to "New Project", new_project_path %>
<% end %>
The "cannot?" method is for convenience and performs the opposite check of "can?"
cannot? :destroy, @project
== Questions or Problems?
== Aliasing Actions
If you have any issues with CanCan which you cannot find the solution to in the documentation[https://github.com/ryanb/cancan/wiki], please add an {issue on GitHub}[https://github.com/ryanb/cancan/issues] or fork the project and send a pull request.
You can use the "alias_action" method to alias one or more actions into one.
To get the specs running you should call +bundle+ and then +rake+. See the {spec/README}[https://github.com/ryanb/cancan/blob/master/spec/README.rdoc] for more information.
alias_action :update, :destroy, :to => :modify
can :modify, Comment
can? :update, Comment # => true
The following aliases are added by default for conveniently mapping common controller actions.
alias_action :index, :show, :to => :read
alias_action :new, :to => :create
alias_action :edit, :to => :update
== Assumptions & Configuring
CanCan makes two assumptions about your application.
* You have an Ability class which defines the permissions.
* You have a current_user method in the controller which returns the current user model.
You can override these by overriding the "current_ability" method in your ApplicationController.
def current_ability
UserAbility.new(current_account) # instead of Ability.new(current_user)
end
That's it!
== Testing Abilities
It is very easy to test the Ability model since you can call "can?" directly on it as you would in the view or controller.
def test "user can only destroy projects which he owns"
user = User.new
ability = Ability.new(user)
assert ability.can?(:destroy, Project.new(:user => user))
assert ability.cannot?(:destroy, Project.new)
end
== Special Thanks
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.
CanCan was inspired by declarative_authorization[http://github.com/stffn/declarative_authorization/] and aegis[http://github.com/makandra/aegis]. Many thanks to the authors and contributors.

View File

@ -1,18 +1,11 @@
require 'rubygems'
require 'rake'
require 'rspec/core/rake_task'
desc "Run RSpec"
RSpec::Core::RakeTask.new do |t|
t.verbose = false
end
desc "Run specs for all adapters"
task :spec_all do
%w[active_record data_mapper mongoid].each do |model_adapter|
puts "MODEL_ADAPTER = #{model_adapter}"
system "rake spec MODEL_ADAPTER=#{model_adapter}"
end
end
task :default => :spec
require 'rubygems'
require 'rake'
require 'spec/rake/spectask'
spec_files = Rake::FileList["spec/**/*_spec.rb"]
desc "Run specs"
Spec::Rake::SpecTask.new do |t|
t.spec_files = spec_files
t.spec_opts = ["-c"]
end

View File

@ -1,20 +1,22 @@
Gem::Specification.new do |s|
s.name = "cancan"
s.version = "1.6.10"
s.author = "Ryan Bates"
s.email = "ryan@railscasts.com"
s.homepage = "http://github.com/ryanb/cancan"
s.summary = "Simple authorization solution for Rails."
s.description = "Simple authorization solution for Rails which is decoupled from user roles. All permissions are stored in a single location."
s.files = Dir["{lib,spec}/**/*", "[A-Z]*", "init.rb"] - ["Gemfile.lock"]
s.require_path = "lib"
s.add_development_dependency 'rspec', '~> 2.6.0'
s.add_development_dependency 'rails', '~> 3.0.9'
s.add_development_dependency 'rr', '~> 0.10.11' # 1.0.0 has respond_to? issues: http://github.com/btakita/rr/issues/issue/43
s.add_development_dependency 'supermodel', '~> 0.1.4'
s.rubyforge_project = s.name
s.required_rubygems_version = ">= 1.3.4"
s.name = "cancan"
s.summary = "Simple authorization solution for Rails."
s.description = "Simple authorization solution for Rails which is completely decoupled from the user's roles. All permissions are stored in a single location for convenience."
s.homepage = "http://github.com/ryanb/cancan"
s.version = "0.2.1"
s.date = "2009-11-26"
s.authors = ["Ryan Bates"]
s.email = "ryan@railscasts.com"
s.require_paths = ["lib"]
s.files = Dir["lib/**/*"] + Dir["spec/**/*"] + ["LICENSE", "README.rdoc", "Rakefile", "CHANGELOG.rdoc", "init.rb"]
s.extra_rdoc_files = ["README.rdoc", "CHANGELOG.rdoc", "LICENSE"]
s.has_rdoc = true
s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "CanCan", "--main", "README.rdoc"]
s.rubygems_version = "1.3.4"
s.required_rubygems_version = Gem::Requirement.new(">= 1.2")
end

View File

@ -1,13 +1,9 @@
require 'cancan/ability'
require 'cancan/rule'
require 'cancan/controller_resource'
require 'cancan/controller_additions'
require 'cancan/model_additions'
require 'cancan/exceptions'
require 'cancan/inherited_resource'
module CanCan
# This error is raised when a user isn't allowed to access a given
# controller action. See ControllerAdditions#unauthorized! for details.
class AccessDenied < StandardError; end
end
require '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) && defined?(Mongoid::Document)
require File.dirname(__FILE__) + '/cancan/ability'
require File.dirname(__FILE__) + '/cancan/resource_authorization'
require File.dirname(__FILE__) + '/cancan/controller_additions'

View File

@ -1,8 +1,8 @@
module CanCan
# This module is designed to be included into an Ability class. This will
# provide the "can" methods for defining and checking abilities.
#
#
# class Ability
# include CanCan::Ability
#
@ -14,292 +14,157 @@ module CanCan
# end
# end
# end
#
#
module Ability
# Check if the user has permission to perform a given action on an object.
#
attr_accessor :user
# Use to check the user's permission for a given action and object.
#
# can? :destroy, @project
#
#
# You can also pass the class instead of an instance (if you don't have one handy).
#
#
# can? :create, Project
#
# Nested resources can be passed through a hash, this way conditions which are
# dependent upon the association will work when using a class.
#
# can? :create, @category => Project
#
# Any additional arguments will be passed into the "can" block definition. This
# can be used to pass more information about the user's request for example.
#
# can? :create, Project, request.remote_ip
#
# can :create Project do |project, remote_ip|
# # ...
# end
#
# Not only can you use the can? method in the controller and view (see ControllerAdditions),
#
# Not only can you use the can? method in the controller and view (see ControllerAdditions),
# but you can also call it directly on an ability instance.
#
#
# ability.can? :destroy, @project
#
#
# This makes testing a user's abilities very easy.
#
#
# def test "user can only destroy projects which he owns"
# user = User.new
# ability = Ability.new(user)
# assert ability.can?(:destroy, Project.new(:user => user))
# assert ability.cannot?(:destroy, Project.new)
# end
#
# Also see the RSpec Matchers to aid in testing.
def can?(action, subject, *extra_args)
match = relevant_rules_for_match(action, subject).detect do |rule|
rule.matches_conditions?(action, subject, extra_args)
#
def can?(action, noun)
(@can_definitions || []).reverse.each do |base_behavior, defined_action, defined_noun, defined_block|
defined_actions = expand_actions(defined_action)
defined_nouns = [defined_noun].flatten
if includes_action?(defined_actions, action) && includes_noun?(defined_nouns, noun)
result = can_perform_action?(action, noun, defined_actions, defined_nouns, defined_block)
return base_behavior ? result : !result
end
end
match ? match.base_behavior : false
false
end
# Convenience method which works the same as "can?" but returns the opposite value.
#
#
# cannot? :destroy, @project
#
#
def cannot?(*args)
!can?(*args)
end
# Defines which abilities are allowed using two arguments. The first one is the action
# you're setting the permission for, the second one is the class of object you're setting it on.
#
#
# can :update, Article
#
#
# You can pass an array for either of these parameters to match any one.
# Here the user has the ability to update or destroy both articles and comments.
#
# can [:update, :destroy], [Article, Comment]
#
# You can pass :all to match any object and :manage to match any action. Here are some examples.
# In this case the user has the ability to update or destroy both articles and comments.
#
# can :manage, :all
# can :update, :all
# can :manage, Project
# You can pass a block to provide logic based on the article's attributes.
#
# You can pass a hash of conditions as the third argument. Here the user can only see active projects which he owns.
#
# can :read, Project, :active => true, :user_id => user.id
#
# See ActiveRecordAdditions#accessible_by for how to use this in database queries. These conditions
# are also used for initial attributes when building a record in ControllerAdditions#load_resource.
#
# If the conditions hash does not give you enough control over defining abilities, you can use a block
# along with any Ruby code you want.
#
# can :update, Project do |project|
# project.groups.include?(user.group)
# can :update, Article do |article|
# article && article.user == user
# end
#
# If the block returns true then the user has that :update ability for that project, otherwise he
# will be denied access. 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
#
# If the block returns true then the user has that :update ability for that article, otherwise he
# will be denied access. It's possible for the passed in model to be nil if one isn't specified,
# so be sure to take that into consideration.
#
# You can pass :all to reference every type of object. In this case the object type will be passed
# into the block as well (just in case object is nil).
#
# can :read, :all do |object_class, object|
# object_class != Order
# end
#
# Here the user has permission to read all objects except orders.
#
# You can also pass :manage as the action which will match any action. In this case the action is
# passed to the block.
#
# can :manage, Comment do |action, comment|
# action != :destroy
# end
#
# You can pass custom objects into this "can" method, this is usually done through a symbol
# and is useful if a class isn't available to define permissions on.
#
#
# can :read, :stats
# can? :read, :stats # => true
#
# IMPORTANT: Neither a hash of conditions or a block will be used when checking permission on a class.
#
# can :update, Project, :priority => 3
# can? :update, Project # => true
#
# If you pass no arguments to +can+, the action, class, and object will be passed to the block and the
# block will always be executed. This allows you to override the full behavior if the permissions are
# defined in an external source such as the database.
#
# can do |action, object_class, object|
# # check the database and return true/false
# end
#
def can(action = nil, subject = nil, conditions = nil, &block)
rules << Rule.new(true, action, subject, conditions, block)
#
def can(action, noun, &block)
@can_definitions ||= []
@can_definitions << [true, action, noun, block]
end
# Defines an ability which cannot be done. Accepts the same arguments as "can".
#
# Define an ability which cannot be done. Accepts the same arguments as "can".
#
# can :read, :all
# cannot :read, Comment
#
#
# A block can be passed just like "can", however if the logic is complex it is recommended
# to use the "can" method.
#
#
# cannot :read, Product do |product|
# product.invisible?
# end
#
def cannot(action = nil, subject = nil, conditions = nil, &block)
rules << Rule.new(false, action, subject, conditions, block)
#
def cannot(action, noun, &block)
@can_definitions ||= []
@can_definitions << [false, action, noun, block]
end
# Alias one or more actions into another one.
#
#
# alias_action :update, :destroy, :to => :modify
# can :modify, Comment
#
#
# Then :modify permission will apply to both :update and :destroy requests.
#
#
# can? :update, Comment # => true
# can? :destroy, Comment # => true
#
#
# This only works in one direction. Passing the aliased action into the "can?" call
# will not work because aliases are meant to generate more generic actions.
#
#
# alias_action :update, :destroy, :to => :modify
# can :update, Comment
# can? :modify, Comment # => false
#
#
# Unless that exact alias is used.
#
#
# can :modify, Comment
# can? :modify, Comment # => true
#
#
# The following aliases are added by default for conveniently mapping common controller actions.
#
#
# alias_action :index, :show, :to => :read
# alias_action :new, :to => :create
# alias_action :edit, :to => :update
#
#
# This way one can use params[:action] in the controller to determine the permission.
def alias_action(*args)
target = args.pop[:to]
validate_target(target)
aliased_actions[target] ||= []
aliased_actions[target] += args
aliased_actions[target] = args
end
# User shouldn't specify targets with names of real actions or it will cause Seg fault
def validate_target(target)
raise Error, "You can't specify target (#{target}) as alias because it is real action name" if aliased_actions.values.flatten.include? target
end
# Returns a hash of aliased actions. The key is the target and the value is an array of actions aliasing the key.
private
def aliased_actions
@aliased_actions ||= default_alias_actions
end
# Removes previously aliased actions including the defaults.
def clear_aliased_actions
@aliased_actions = {}
end
def model_adapter(model_class, action)
adapter_class = ModelAdapters::AbstractAdapter.adapter_class(model_class)
adapter_class.new(model_class, relevant_rules_for_query(action, model_class))
end
# See ControllerAdditions#authorize! for documentation.
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
subject
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.underscore.humanize.downcase
message = I18n.translate(nil, variables.merge(:scope => :unauthorized, :default => keys + [""]))
message.blank? ? nil : message
end
def attributes_for(action, subject)
attributes = {}
relevant_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
def merge(ability)
ability.send(:rules).each do |rule|
rules << rule.dup
end
self
end
private
def unauthorized_message_keys(action, subject)
subject = (subject.class == Class ? subject : subject.class).name.underscore unless subject.kind_of? Symbol
[subject, :all].map do |try_subject|
[aliases_for_action(action), :manage].flatten.map do |try_action|
:"#{try_action}.#{try_subject}"
end
end.flatten
end
# Accepts an array of actions and returns an array of actions which match.
# This should be called before "matches?" and other checking methods since they
# rely on the actions to be expanded.
def expand_actions(actions)
actions.map do |action|
aliased_actions[action] ? [action, *expand_actions(aliased_actions[action])] : action
end.flatten
end
# Given an action, it will try to find all of the actions which are aliased to it.
# This does the opposite kind of lookup as expand_actions.
def aliases_for_action(action)
results = [action]
aliased_actions.each do |aliased_action, actions|
results += aliases_for_action(aliased_action) if actions.include? action
end
results
end
def 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
def relevant_rules(action, subject)
rules.reverse.select do |rule|
rule.expanded_actions = expand_actions(rule.actions)
rule.relevant? action, subject
end
end
def relevant_rules_for_match(action, subject)
relevant_rules(action, subject).each do |rule|
if rule.only_raw_sql?
raise Error, "The can? and cannot? call cannot be used with a raw sql 'can' definition. The checking code cannot be determined for #{action.inspect} #{subject.inspect}"
end
end
end
def relevant_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
def default_alias_actions
{
:read => [:index, :show],
@ -307,5 +172,35 @@ module CanCan
:update => [:edit],
}
end
def expand_actions(actions)
[actions].flatten.map do |action|
if aliased_actions[action]
[action, *aliased_actions[action]]
else
action
end
end.flatten
end
def can_perform_action?(action, noun, defined_actions, defined_nouns, defined_block)
if defined_block.nil?
true
else
block_args = []
block_args << action if defined_actions.include?(:manage)
block_args << (noun.class == Class ? noun : noun.class) if defined_nouns.include?(:all)
block_args << (noun.class == Class ? nil : noun)
return defined_block.call(*block_args)
end
end
def includes_action?(actions, action)
actions.include?(:manage) || actions.include?(action)
end
def includes_noun?(nouns, noun)
nouns.include?(:all) || nouns.include?(noun) || nouns.any? { |c| c.kind_of?(Class) && noun.kind_of?(c) }
end
end
end

View File

@ -1,396 +1,121 @@
module CanCan
# This module is automatically included into all controllers.
# It also makes the "can?" and "cannot?" methods available to all views.
module ControllerAdditions
module ClassMethods
# Sets up a before filter which loads and authorizes the current resource. This performs both
# load_resource and authorize_resource and accepts the same arguments. See those methods for details.
#
# class BooksController < ApplicationController
# load_and_authorize_resource
# end
#
def load_and_authorize_resource(*args)
cancan_resource_class.add_before_filter(self, :load_and_authorize_resource, *args)
end
# Sets up a before filter which loads the model resource into an instance variable.
# For example, given an ArticlesController it will load the current article into the @article
# instance variable. It does this by either calling Article.find(params[:id]) or
# Article.new(params[:article]) depending upon the action. The index action will
# automatically set @articles to Article.accessible_by(current_ability).
#
# If a conditions hash is used in the Ability, the +new+ and +create+ actions will set
# the initial attributes based on these conditions. This way these actions will satisfy
# the ability restrictions.
#
# Call this method directly on the controller class.
#
# class BooksController < ApplicationController
# load_resource
# end
#
# A resource is not loaded if the instance variable is already set. This makes it easy to override
# the behavior through a before_filter on certain actions.
#
# class BooksController < ApplicationController
# before_filter :find_book_by_permalink, :only => :show
# load_resource
#
# private
#
# def find_book_by_permalink
# @book = Book.find_by_permalink!(params[:id)
# end
# end
#
# If a name is provided which does not match the controller it assumes it is a parent resource. Child
# resources can then be loaded through it.
#
# class BooksController < ApplicationController
# load_resource :author
# load_resource :book, :through => :author
# end
#
# Here the author resource will be loaded before each action using params[:author_id]. The book resource
# will then be loaded through the @author instance variable.
#
# That first argument is optional and will default to the singular name of the controller.
# A hash of options (see below) can also be passed to this method to further customize it.
#
# See load_and_authorize_resource to automatically authorize the resource too.
#
# Options:
# [:+only+]
# Only applies before filter to given actions.
#
# [:+except+]
# Does not apply before filter to given actions.
#
# [:+through+]
# 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+]
# Pass +true+ if this is a singleton resource through a +has_one+ association.
#
# [:+parent+]
# True or false depending on if the resource is considered a parent resource. This defaults to +true+ if a resource
# name is given which does not match the controller.
#
# [:+class+]
# The class to use for the model (string or constant).
#
# [:+instance_name+]
# The name of the instance variable to load the resource into.
#
# [:+find_by+]
# Find using a different attribute other than id. For example.
#
# load_resource :find_by => :permalink # will use find_by_permalink!(params[:id])
#
# [:+id_param+]
# Find using a param key other than :id. For example:
#
# load_resource :id_key => :url # will use find(params[:url])
#
# [:+collection+]
# Specify which actions are resource collection actions in addition to :+index+. This
# is usually not necessary because it will try to guess depending on if the id param is present.
#
# load_resource :collection => [:sort, :list]
#
# [:+new+]
# Specify which actions are new resource actions in addition to :+new+ and :+create+.
# Pass an action name into here if you would like to build a new resource instead of
# fetch one.
#
# load_resource :new => :build
#
# [:+prepend+]
# Passing +true+ will use prepend_before_filter instead of a normal before_filter.
#
def load_resource(*args)
cancan_resource_class.add_before_filter(self, :load_resource, *args)
end
# Sets up a before filter which authorizes the resource using the instance variable.
# For example, if you have an ArticlesController it will check the @article instance variable
# and ensure the user can perform the current action on it. Under the hood it is doing
# something like the following.
#
# authorize!(params[:action].to_sym, @article || Article)
#
# Call this method directly on the controller class.
#
# class BooksController < ApplicationController
# authorize_resource
# end
#
# If you pass in the name of a resource which does not match the controller it will assume
# it is a parent resource.
#
# class BooksController < ApplicationController
# authorize_resource :author
# authorize_resource :book
# end
#
# Here it will authorize :+show+, @+author+ on every action before authorizing the book.
#
# That first argument is optional and will default to the singular name of the controller.
# A hash of options (see below) can also be passed to this method to further customize it.
#
# See load_and_authorize_resource to automatically load the resource too.
#
# Options:
# [:+only+]
# Only applies before filter to given actions.
#
# [:+except+]
# Does not apply before filter to given actions.
#
# [:+singleton+]
# Pass +true+ if this is a singleton resource through a +has_one+ association.
#
# [:+parent+]
# True or false depending on if the resource is considered a parent resource. This defaults to +true+ if a resource
# name is given which does not match the controller.
#
# [:+class+]
# The class to use for the model (string or constant). This passed in when the instance variable is not set.
# Pass +false+ if there is no associated class for this resource and it will use a symbol of the resource name.
#
# [:+instance_name+]
# The name of the instance variable for this resource.
#
# [:+through+]
# Authorize conditions on this parent resource when instance isn't available.
#
# [:+prepend+]
# Passing +true+ will use prepend_before_filter instead of a normal before_filter.
#
def authorize_resource(*args)
cancan_resource_class.add_before_filter(self, :authorize_resource, *args)
end
# Skip both the loading and authorization behavior of CanCan for this given controller. This is primarily
# useful to skip the behavior of a superclass. You can pass :only and :except options to specify which actions
# to skip the effects on. It will apply to all actions by default.
#
# class ProjectsController < SomeOtherController
# skip_load_and_authorize_resource :only => :index
# end
#
# You can also pass the resource name as the first argument to skip that resource.
def skip_load_and_authorize_resource(*args)
skip_load_resource(*args)
skip_authorize_resource(*args)
end
# Skip 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 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
#
# See skip_authorization_check to bypass this check on specific controller actions.
#
# Options:
# [:+only+]
# Only applies to given actions.
#
# [:+except+]
# Does not apply to given actions.
#
# [:+if+]
# Supply the name of a controller method to be called. The authorization check only takes place if this returns true.
#
# check_authorization :if => :admin_controller?
#
# [:+unless+]
# Supply the name of a controller method to be called. The authorization check only takes place if this returns false.
#
# check_authorization :unless => :devise_controller?
#
def check_authorization(options = {})
self.after_filter(options.slice(:only, :except)) do |controller|
next if controller.instance_variable_defined?(:@_authorized)
next if options[:if] && !controller.send(options[:if])
next if options[:unless] && controller.send(options[:unless])
raise AuthorizationNotPerformed, "This action failed the check_authorization because it does not authorize_resource. Add skip_authorization_check to bypass this check."
end
end
# 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
def self.included(base)
base.extend ClassMethods
base.helper_method :can?, :cannot?, :current_ability
base.helper_method :can?, :cannot?
end
# Raises a CanCan::AccessDenied exception if the current_ability cannot
# perform the given action. This is usually called in a controller action or
# before filter to perform the authorization.
#
# Raises the CanCan::AccessDenied exception. This is often used in a
# controller action to mark a request as unauthorized.
#
# def show
# @article = Article.find(params[:id])
# authorize! :read, @article
# unauthorized! if cannot? :read, @article
# end
#
# A :message option can be passed to specify a different message.
#
# authorize! :read, @article, :message => "Not authorized to read #{@article.name}"
#
# You can also use I18n to customize the message. Action aliases defined in Ability work here.
#
# en:
# unauthorized:
# manage:
# all: "Not authorized to %{action} %{subject}."
# user: "Not allowed to manage other user accounts."
# update:
# project: "Not allowed to update this project."
#
# You can rescue from the exception in the controller to customize how unauthorized
# access is displayed to the user.
#
#
# You can rescue from the exception in the controller to specify
# the user experience.
#
# class ApplicationController < ActionController::Base
# rescue_from CanCan::AccessDenied do |exception|
# redirect_to root_url, :alert => exception.message
# rescue_from CanCan::AccessDenied, :with => :access_denied
#
# protected
#
# def access_denied
# flash[:error] = "Sorry, you are not allowed to access that page."
# redirect_to root_url
# end
# end
#
# See the CanCan::AccessDenied exception for more details on working with the exception.
#
# See the load_and_authorize_resource method to automatically add the authorize! behavior
# to the default RESTful actions.
def authorize!(*args)
@_authorized = true
current_ability.authorize!(*args)
#
# See the load_and_authorize_resource method to automatically add
# the "unauthorized!" behavior to a RESTful controller's actions.
def unauthorized!
raise AccessDenied, "You are unable to access this page."
end
def unauthorized!(message = nil)
raise ImplementationRemoved, "The unauthorized! method has been removed from CanCan, use authorize! instead."
end
# Creates and returns the current user's ability and caches it. If you
# want to override how the Ability is defined then this is the place.
# Just define the method in the controller to change behavior.
#
# Creates and returns the current user's ability. You generally do not invoke
# this method directly, instead you can override this method to change its
# behavior if the Ability class or current_user method are different.
#
# def current_ability
# # instead of Ability.new(current_user)
# @current_ability ||= UserAbility.new(current_account)
# UserAbility.new(current_account) # instead of Ability.new(current_user)
# end
#
# Notice it is important to cache the ability object so it is not
# recreated every time.
#
def current_ability
@current_ability ||= ::Ability.new(current_user)
::Ability.new(current_user)
end
# Use in the controller or view to check the user's permission for a given action
# and object.
#
#
# can? :destroy, @project
#
#
# You can also pass the class instead of an instance (if you don't have one handy).
#
#
# <% if can? :create, Project %>
# <%= link_to "New Project", new_project_path %>
# <% end %>
#
# If it's a nested resource, you can pass the parent instance in a hash. This way it will
# check conditions which reach through that association.
#
# <% if can? :create, @category => Project %>
# <%= link_to "New Project", new_project_path %>
# <% end %>
#
#
# This simply calls "can?" on the current_ability. See Ability#can?.
def can?(*args)
current_ability.can?(*args)
(@current_ability ||= current_ability).can?(*args)
end
# Convenience method which works the same as "can?" but returns the opposite value.
#
#
# cannot? :destroy, @project
#
#
def cannot?(*args)
current_ability.cannot?(*args)
(@current_ability ||= current_ability).cannot?(*args)
end
# This method loads the appropriate model resource into an instance variable. For example,
# given an ArticlesController it will load the current article into the @article instance
# variable. It does this by either calling Article.find(params[:id]) or
# Article.new(params[:article]) depending upon the action. It does nothing for the "index"
# action.
#
# You would often use this as a before filter in the controller. See
# load_and_authorize_resource to handle authorization too.
#
# before_filter :load_resource
#
def load_resource
ResourceAuthorization.new(self, params).load_resource
end
# Authorizes the resource in the current instance variable. For example,
# if you have an ArticlesController it will check the @article instance variable
# and ensure the user can perform the current action on it.
# Under the hood it is doing something like the following.
#
# unauthorized! if cannot?(params[:action].to_sym, @article || Article)
#
# You would often use this as a before filter in the controller.
#
# before_filter :authorize_resource
#
# See load_and_authorize_resource to automatically load the resource too.
def authorize_resource
ResourceAuthorization.new(self, params).authorize_resource
end
# Calls load_resource to load the current resource model into an instance variable.
# Then calls authorize_resource to ensure the current user is authorized to access the page.
# You would often use this as a before filter in the controller.
#
# before_filter :load_and_authorize_resource
#
def load_and_authorize_resource
load_resource
authorize_resource
end
end
end
if defined? ActionController::Base
if defined? ActionController
ActionController::Base.class_eval do
include CanCan::ControllerAdditions
end

View File

@ -1,273 +0,0 @@
module CanCan
# Handle the load and authorization controller logic so we don't clutter up all controllers with non-interface methods.
# This class is used internally, so you do not need to call methods directly on it.
class ControllerResource # :nodoc:
def self.add_before_filter(controller_class, method, *args)
options = args.extract_options!
resource_name = args.first
before_filter_method = options.delete(:prepend) ? :prepend_before_filter : :before_filter
controller_class.send(before_filter_method, options.slice(:only, :except, :if, :unless)) do |controller|
controller.class.cancan_resource_class.new(controller, resource_name, options.except(:only, :except, :if, :unless)).send(method)
end
end
def initialize(controller, *args)
@controller = controller
@params = controller.params
@options = args.extract_options!
@name = args.first
raise CanCan::ImplementationRemoved, "The :nested option is no longer supported, instead use :through with separate load/authorize call." if @options[:nested]
raise CanCan::ImplementationRemoved, "The :name option is no longer supported, instead pass the name as the first argument." if @options[:name]
raise CanCan::ImplementationRemoved, "The :resource option has been renamed back to :class, use false if no class." if @options[:resource]
end
def load_and_authorize_resource
load_resource
authorize_resource
if update_actions.include?(@params[:action].to_sym)
update_resource
authorize_resource # Reauthorize the now-updated resource
end
end
def load_resource
unless skip?(:load)
if load_instance?
self.resource_instance ||= load_resource_instance
elsif load_collection?
self.collection_instance ||= load_collection
end
end
end
def authorize_resource
unless skip?(:authorize)
@controller.authorize!(authorization_action, resource_instance || resource_class_with_parent)
end
end
def parent?
@options.has_key?(:parent) ? @options[:parent] : @name && @name != name_from_controller.to_sym
end
def skip?(behavior) # This could probably use some refactoring
options = @controller.class.cancan_skipper[behavior][@name]
if options.nil?
false
elsif options == {}
true
elsif options[:except] && ![options[:except]].flatten.include?(@params[:action].to_sym)
true
elsif [options[:only]].flatten.include?(@params[:action].to_sym)
true
end
end
protected
def load_resource_instance
if !parent? && new_actions.include?(@params[:action].to_sym)
build_resource
elsif id_param || @options[:singleton]
find_resource
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, authorization_action)
end
def build_resource
resource = resource_base.new(resource_params || {})
assign_attributes(resource)
end
def update_resource
resource.assign_attributes(resource_params || {})
end
def assign_attributes(resource)
resource.send("#{parent_name}=", parent_resource) if @options[:singleton] && parent_resource
initial_attributes.each do |attr_name, value|
resource.send("#{attr_name}=", value)
end
resource
end
def initial_attributes
current_ability.attributes_for(@params[:action].to_sym, resource_class).delete_if do |key, value|
resource_params && resource_params.include?(key)
end
end
def find_resource
if @options[:singleton] && parent_resource.respond_to?(name)
parent_resource.send(name)
else
if @options[:find_by]
if resource_base.respond_to? "find_by_#{@options[:find_by]}!"
resource_base.send("find_by_#{@options[:find_by]}!", id_param)
elsif resource_base.respond_to? "find_by"
resource_base.send("find_by", { @options[:find_by].to_sym => id_param })
else
resource_base.send(@options[:find_by], id_param)
end
else
adapter.find(resource_base, id_param)
end
end
end
def adapter
ModelAdapters::AbstractAdapter.adapter_class(resource_class)
end
def authorization_action
parent? ? :show : @params[:action].to_sym
end
def id_param
if @options[:id_param]
@params[@options[:id_param]]
else
@params[parent? ? :"#{name}_id" : :id]
end.to_s
end
def member_action?
new_actions.include?(@params[:action].to_sym) || @options[:singleton] || ( (@params[:id] || @params[@options[:id_param]]) && !collection_actions.include?(@params[:action].to_sym))
end
# Returns the class used for this resource. This can be overriden by the :class option.
# If +false+ is passed in it will use the resource name as a symbol in which case it should
# only be used for authorization, not loading since there's no class to load through.
def resource_class
case @options[:class]
when false then name.to_sym
when nil then namespaced_name.to_s.camelize.constantize
when String then @options[:class].constantize
else @options[:class]
end
end
def resource_class_with_parent
parent_resource ? {parent_resource => resource_class} : resource_class
end
def resource_instance=(instance)
@controller.instance_variable_set("@#{instance_name}", instance)
end
def resource_instance
@controller.instance_variable_get("@#{instance_name}") 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
# 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 :shallow option is passed it will use the resource_class if there's no parent
# If the :singleton option is passed it won't use the association because it needs to be handled later.
def resource_base
if @options[:through]
if parent_resource
@options[:singleton] ? resource_class : parent_resource.send(@options[:through_association] || name.to_s.pluralize)
elsif @options[:shallow]
resource_class
else
raise AccessDenied.new(nil, authorization_action, resource_class) # maybe this should be a record not found error instead?
end
else
resource_class
end
end
def parent_name
@options[:through] && [@options[:through]].flatten.detect { |i| fetch_parent(i) }
end
# The object to load this resource through.
def parent_resource
parent_name && fetch_parent(parent_name)
end
def fetch_parent(name)
if @controller.instance_variable_defined? "@#{name}"
@controller.instance_variable_get("@#{name}")
elsif @controller.respond_to?(name, true)
@controller.send(name)
end
end
def current_ability
@controller.send(:current_ability)
end
def name
@name || name_from_controller
end
def resource_params
if @options[:class]
params_key = extract_key(@options[:class])
return @params[params_key] if @params[params_key]
end
resource_params_by_namespaced_name
end
def resource_params_by_namespaced_name
@params[extract_key(namespaced_name)]
end
def namespace
@params[:controller].split(/::|\//)[0..-2]
end
def namespaced_name
[namespace, name.camelize].join('::').singularize.camelize.constantize
rescue NameError
name
end
def name_from_controller
@params[:controller].sub("Controller", "").underscore.split('/').last.singularize
end
def instance_name
@options[:instance_name] || name
end
def collection_actions
[:index] + [@options[:collection]].flatten
end
def new_actions
[:new, :create] + [@options[:new]].flatten
end
def update_actions
[:update] #TODO: check what @options is for
end
private
def extract_key(value)
value.to_s.underscore.gsub('/', '_')
end
end
end

View File

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

View File

@ -1,20 +0,0 @@
module CanCan
# For use with Inherited Resources
class InheritedResource < ControllerResource # :nodoc:
def load_resource_instance
if parent?
@controller.send :association_chain
@controller.instance_variable_get("@#{instance_name}")
elsif new_actions.include? @params[:action].to_sym
resource = @controller.send :build_resource
assign_attributes(resource)
else
@controller.send :resource
end
end
def resource_base
@controller.send :end_of_association_chain
end
end
end

View File

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

View File

@ -1,56 +0,0 @@
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
# Override if you need custom find behavior
def self.find(model_class, id)
model_class.find(id)
end
# Used to determine if this model adapter will override the matching behavior for a hash of conditions.
# If this returns true then matches_conditions_hash? will be called. See Rule#matches_conditions_hash
def self.override_conditions_hash_matching?(subject, conditions)
false
end
# Override if override_conditions_hash_matching? returns true
def self.matches_conditions_hash?(subject, conditions)
raise NotImplemented, "This model adapter does not support matching on a conditions hash."
end
# Used to determine if this model adapter will override the matching behavior for a specific condition.
# If this returns true then matches_condition? will be called. See Rule#matches_conditions_hash
def self.override_condition_matching?(subject, name, value)
false
end
# Override if override_condition_matching? returns true
def self.matches_condition?(subject, name, value)
raise NotImplemented, "This model adapter does not support matching on a specific condition."
end
def initialize(model_class, rules)
@model_class = model_class
@rules = rules
end
def database_records
# This should be overridden in a subclass to return records which match @rules
raise NotImplemented, "This model adapter does not support fetching records from the database."
end
end
end
end

View File

@ -1,181 +0,0 @@
module CanCan
module ModelAdapters
class ActiveRecordAdapter < AbstractAdapter
def self.for_class?(model_class)
model_class <= ActiveRecord::Base
end
def self.override_condition_matching?(subject, name, value)
name.kind_of?(MetaWhere::Column) if defined? MetaWhere
end
def self.matches_condition?(subject, name, value)
subject_value = subject.send(name.column)
if name.method.to_s.ends_with? "_any"
value.any? { |v| meta_where_match? subject_value, name.method.to_s.sub("_any", ""), v }
elsif name.method.to_s.ends_with? "_all"
value.all? { |v| meta_where_match? subject_value, name.method.to_s.sub("_all", ""), v }
else
meta_where_match? subject_value, name.method, value
end
end
def self.meta_where_match?(subject_value, method, value)
case method.to_sym
when :eq then subject_value == value
when :not_eq then subject_value != value
when :in then value.include?(subject_value)
when :not_in then !value.include?(subject_value)
when :lt then subject_value < value
when :lteq then subject_value <= value
when :gt then subject_value > value
when :gteq then subject_value >= value
when :matches then subject_value =~ Regexp.new("^" + Regexp.escape(value).gsub("%", ".*") + "$", true)
when :does_not_match then !meta_where_match?(subject_value, :matches, value)
else raise NotImplemented, "The #{method} MetaWhere condition is not supported."
end
end
# Returns conditions intended to be used inside a database query. Normally you will not call this
# method directly, but instead go through ModelAdditions#accessible_by.
#
# If there is only one "can" definition, a hash of conditions will be returned matching the one defined.
#
# can :manage, User, :id => 1
# query(:manage, User).conditions # => { :id => 1 }
#
# If there are multiple "can" definitions, a SQL string will be returned to handle complex cases.
#
# can :manage, User, :id => 1
# can :manage, User, :manager_id => 1
# cannot :manage, User, :self_managed => true
# query(:manage, User).conditions # => "not (self_managed = 't') AND ((manager_id = 1) OR (id = 1))"
#
def conditions
if @rules.size == 1 && @rules.first.base_behavior
# Return the conditions directly if there's just one definition
tableized_conditions(@rules.first.conditions).dup
else
@rules.reverse.inject(false_sql) do |sql, rule|
merge_conditions(sql, tableized_conditions(rule.conditions).dup, rule.base_behavior)
end
end
end
def tableized_conditions(conditions, model_class = @model_class)
return conditions unless conditions.kind_of? Hash
conditions.inject({}) do |result_hash, (name, value)|
if value.kind_of? Hash
value = value.dup
association_class = model_class.reflect_on_association(name).class_name.constantize
nested = value.inject({}) do |nested,(k,v)|
if v.kind_of? Hash
value.delete(k)
nested[k] = v
else
name = model_class.reflect_on_association(name).table_name.to_sym
result_hash[name] = value
end
nested
end
result_hash.merge!(tableized_conditions(nested,association_class))
else
result_hash[name] = value
end
result_hash
end
end
# Returns the associations used in conditions for the :joins option of a search.
# See ModelAdditions#accessible_by
def joins
joins_hash = {}
@rules.each do |rule|
merge_joins(joins_hash, rule.associations_hash)
end
clean_joins(joins_hash) unless joins_hash.empty?
end
def database_records
if override_scope
@model_class.scoped.merge(override_scope)
elsif @model_class.respond_to?(:where) && @model_class.respond_to?(:joins)
mergeable_conditions = @rules.select {|rule| rule.unmergeable? }.blank?
if mergeable_conditions
@model_class.where(conditions).joins(joins)
else
@model_class.where(*(@rules.map(&:conditions))).joins(joins)
end
else
@model_class.scoped(:conditions => conditions, :joins => joins)
end
end
private
def override_scope
conditions = @rules.map(&:conditions).compact
if defined?(ActiveRecord::Relation) && conditions.any? { |c| c.kind_of?(ActiveRecord::Relation) }
if conditions.size == 1
conditions.first
else
rule = @rules.detect { |rule| rule.conditions.kind_of?(ActiveRecord::Relation) }
raise Error, "Unable to merge an Active Record scope with other conditions. Instead use a hash or SQL for #{rule.actions.first} #{rule.subjects.first} ability."
end
end
end
def merge_conditions(sql, conditions_hash, behavior)
if conditions_hash.blank?
behavior ? true_sql : false_sql
else
conditions = sanitize_sql(conditions_hash)
case sql
when true_sql
behavior ? true_sql : "not (#{conditions})"
when false_sql
behavior ? conditions : false_sql
else
behavior ? "(#{conditions}) OR (#{sql})" : "not (#{conditions}) AND (#{sql})"
end
end
end
def false_sql
sanitize_sql(['?=?', true, false])
end
def true_sql
sanitize_sql(['?=?', true, true])
end
def sanitize_sql(conditions)
@model_class.send(:sanitize_sql, conditions)
end
# Takes two hashes and does a deep merge.
def merge_joins(base, add)
add.each do |name, nested|
if base[name].is_a?(Hash)
merge_joins(base[name], nested) unless nested.empty?
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

View File

@ -1,34 +0,0 @@
module CanCan
module ModelAdapters
class DataMapperAdapter < AbstractAdapter
def self.for_class?(model_class)
model_class <= DataMapper::Resource
end
def self.find(model_class, id)
model_class.get(id)
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)
collection = DataMapper::Collection.new(subject.query, [ subject ])
!!collection.first(conditions)
end
def database_records
scope = @model_class.all(:conditions => ["0 = 1"])
cans, cannots = @rules.partition { |r| r.base_behavior }
return scope if cans.empty?
# apply unions first, then differences. this mean cannot overrides can
cans.each { |r| scope += @model_class.all(:conditions => r.conditions) }
cannots.each { |r| scope -= @model_class.all(:conditions => r.conditions) }
scope
end
end # class DataMapper
end # module ModelAdapters
end # module CanCan
DataMapper::Model.append_extensions(CanCan::ModelAdditions::ClassMethods)

View File

@ -1,7 +0,0 @@
module CanCan
module ModelAdapters
class DefaultAdapter < AbstractAdapter
# This adapter is used when no matching adapter is found
end
end
end

View File

@ -1,54 +0,0 @@
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? do |k,v|
key_is_not_symbol = lambda { !k.kind_of?(Symbol) }
subject_value_is_array = lambda do
subject.respond_to?(k) && subject.send(k).is_a?(Array)
end
key_is_not_symbol.call || subject_value_is_array.call
end
end
def self.matches_conditions_hash?(subject, conditions)
# To avoid hitting the db, retrieve the raw Mongo selector from
# the Mongoid Criteria and use Mongoid::Matchers#matches?
subject.matches?( subject.class.where(conditions).selector )
end
def database_records
if @rules.size == 0
@model_class.where(:_id => {'$exists' => false, '$type' => 7}) # return no records in Mongoid
elsif @rules.size == 1 && @rules[0].conditions.is_a?(Mongoid::Criteria)
@rules[0].conditions
else
# we only need to process can rules if
# there are no rules with empty conditions
rules = @rules.reject { |rule| rule.conditions.empty? && rule.base_behavior }
process_can_rules = @rules.count == rules.count
rules.inject(@model_class.all) do |records, rule|
if process_can_rules && rule.base_behavior
records.or rule.conditions
elsif !rule.base_behavior
records.excludes rule.conditions
else
records
end
end
end
end
end
end
end
# simplest way to add `accessible_by` to all Mongoid Documents
module Mongoid::Document::ClassMethods
include CanCan::ModelAdditions::ClassMethods
end

View File

@ -1,31 +0,0 @@
module CanCan
# This module adds the accessible_by class method to a model. It is included in the model adapters.
module ModelAdditions
module ClassMethods
# Returns a scope which fetches only the records that the passed ability
# can perform a given action on. The action defaults to :index. This
# is usually called from a controller and passed the +current_ability+.
#
# @articles = Article.accessible_by(current_ability)
#
# Here only the articles which the user is able to read will be returned.
# If the user does not have permission to read any articles then an empty
# result is returned. Since this is a scope it can be combined with any
# other scopes or pagination.
#
# An alternative action can optionally be passed as a second argument.
#
# @articles = Article.accessible_by(current_ability, :update)
#
# Here only the articles which the user can update are returned.
def accessible_by(ability, action = :index)
ability.model_adapter(self, action).database_records
end
end
def self.included(base)
base.extend ClassMethods
end
end
end

View File

@ -0,0 +1,41 @@
module CanCan
class ResourceAuthorization # :nodoc:
attr_reader :params
def initialize(controller, params)
@controller = controller
@params = params
end
def load_and_authorize_resource
load_resource
authorize_resource
end
def load_resource
self.model_instance = params[:id] ? model_class.find(params[:id]) : model_class.new(params[model_name.to_sym]) unless params[:action] == "index"
end
def authorize_resource
@controller.unauthorized! if @controller.cannot?(params[:action].to_sym, model_instance || model_class)
end
private
def model_name
params[:controller].split('/').last.singularize
end
def model_class
model_name.camelcase.constantize
end
def model_instance
@controller.instance_variable_get("@#{model_name}")
end
def model_instance=(instance)
@controller.instance_variable_set("@#{model_name}", instance)
end
end
end

View File

@ -1,147 +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 Rule # :nodoc:
attr_reader :base_behavior, :subjects, :actions, :conditions
attr_writer :expanded_actions
# The first argument when initializing is the base_behavior which is a true/false
# 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)
raise Error, "You are not able to supply a block with a hash of conditions in #{action} #{subject} ability. Use either one." if conditions.kind_of?(Hash) && !block.nil?
@match_all = action.nil? && subject.nil?
@base_behavior = base_behavior
@actions = [action].flatten
@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.class == 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.class == 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 unmergeable?
@conditions.respond_to?(:keys) && @conditions.present? &&
(!@conditions.keys.first.kind_of? Symbol)
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|
if model_adapter(subject).override_condition_matching? subject, name, value
model_adapter(subject).matches_condition? subject, name, value
else
attribute = subject.send(name)
if value.kind_of?(Hash)
if attribute.kind_of? Array
attribute.any? { |element| matches_conditions_hash? element, value }
else
!attribute.nil? && matches_conditions_hash?(attribute, value)
end
elsif !value.is_a?(String) && value.kind_of?(Enumerable)
value.include? attribute
else
attribute == value
end
end
end
end
end
end
def nested_subject_matches_conditions?(subject_hash)
parent, child = subject_hash.first
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)
CanCan::ModelAdapters::AbstractAdapter.adapter_class(subject_class?(subject) ? subject : subject.class)
end
end
end

View File

@ -1,4 +0,0 @@
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.

View File

@ -1,11 +0,0 @@
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

View File

@ -1,32 +0,0 @@
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

View File

@ -1,28 +0,0 @@
= 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

View File

@ -1,458 +1,126 @@
require "spec_helper"
require File.dirname(__FILE__) + '/../spec_helper'
describe CanCan::Ability do
before(:each) do
@ability = Object.new
@ability.extend(CanCan::Ability)
@ability_class = Class.new
@ability_class.send(:include, CanCan::Ability)
@ability = @ability_class.new
end
it "should be able to :read anything" do
@ability.can :read, :all
@ability.can?(:read, String).should be_true
@ability.can?(:read, 123).should be_true
end
it "should not have permission to do something it doesn't know about" do
@ability.can?(:foodfight, String).should be_false
end
it "should pass true to `can?` when non false/nil is returned in block" do
it "should return what block returns on a can call" do
@ability.can :read, :all
@ability.can :read, Symbol do |sym|
"foo" # TODO test that sym is nil when no instance is passed
sym
end
@ability.can?(:read, :some_symbol).should == true
@ability.can?(:read, Symbol).should be_nil
@ability.can?(:read, :some_symbol).should == :some_symbol
end
it "should pass nil to a block when no instance is passed" do
@ability.can :read, Symbol do |sym|
sym.should be_nil
true
it "should pass class with object if :all objects are accepted" do
@ability.can :preview, :all do |object_class, object|
[object_class, object]
end
@ability.can?(:read, Symbol).should be_true
@ability.can?(:preview, 123).should == [Fixnum, 123]
end
it "should pass to previous rule, if block returns false or nil" do
@ability.can :read, Symbol
@ability.can :read, Integer do |i|
i < 5
it "should pass class with no object if :all objects are accepted and class is passed directly" do
@ability.can :preview, :all do |object_class, object|
[object_class, object]
end
@ability.can :read, Integer do |i|
i > 10
end
@ability.can?(:read, Symbol).should be_true
@ability.can?(:read, 11).should be_true
@ability.can?(:read, 1).should be_true
@ability.can?(:read, 6).should be_false
@ability.can?(:preview, Hash).should == [Hash, nil]
end
it "should not pass class with object if :all objects are accepted" do
@ability.can :preview, :all do |object|
object.should == 123
@block_called = true
it "should pass action and object for global manage actions" do
@ability.can :manage, Array do |action, object|
[action, object]
end
@ability.can?(:preview, 123)
@block_called.should be_true
@ability.can?(:stuff, [1, 2]).should == [:stuff, [1, 2]]
@ability.can?(:stuff, Array).should == [:stuff, nil]
end
it "should not call block when only class is passed, only return true" do
@block_called = false
@ability.can :preview, :all do |object|
@block_called = true
end
@ability.can?(:preview, Hash).should be_true
@block_called.should be_false
end
it "should pass only object for global manage actions" do
@ability.can :manage, String do |object|
object.should == "foo"
@block_called = true
end
@ability.can?(:stuff, "foo").should
@block_called.should be_true
end
it "should alias update or destroy actions to modify action" do
@ability.alias_action :update, :destroy, :to => :modify
@ability.can :modify, :all
@ability.can?(:update, 123).should be_true
@ability.can?(:destroy, 123).should be_true
end
it "should allow deeply nested aliased actions" do
@ability.alias_action :increment, :to => :sort
@ability.alias_action :sort, :to => :modify
@ability.can :modify, :all
@ability.can?(:increment, 123).should be_true
end
it "should raise an Error if alias target is an exist action" do
lambda{ @ability.alias_action :show, :to => :show }.should raise_error(CanCan::Error, "You can't specify target (show) as alias because it is real action name")
end
it "should always call block with arguments when passing no arguments to can" do
@ability.can do |action, object_class, object|
action.should == :foo
object_class.should == 123.class
object.should == 123
@block_called = true
@ability.can :modify, :all do |object_class, object|
:modify_called
end
@ability.can?(:foo, 123)
@block_called.should be_true
@ability.can?(:update, 123).should == :modify_called
@ability.can?(:destroy, 123).should == :modify_called
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
it "should return block result for action, object_class, and object for any action" do
@ability.can :manage, :all do |action, object_class, object|
[action, object_class, object]
end
@ability.can?(:foo, Hash)
@block_called.should be_true
@ability.can?(:foo, 123).should == [:foo, Fixnum, 123]
@ability.can?(:bar, Fixnum).should == [:bar, Fixnum, nil]
end
it "should automatically alias index and show into read calls" do
@ability.can :read, :all
@ability.can?(:index, 123).should be_true
@ability.can?(:show, 123).should be_true
end
it "should automatically alias new and edit into create and update respectively" do
@ability.can :create, :all
@ability.can :update, :all
@ability.can?(:new, 123).should be_true
@ability.can?(:edit, 123).should be_true
@ability.can(:create, :all) { :create_called }
@ability.can(:update, :all) { :update_called }
@ability.can?(:new, 123).should == :create_called
@ability.can?(:edit, 123).should == :update_called
end
it "should not respond to prepare (now using initialize)" do
@ability.should_not respond_to(:prepare)
end
it "should offer cannot? method which is simply invert of can?" do
@ability.cannot?(:tie, String).should be_true
end
it "should be able to specify multiple actions and match any" do
@ability.can [:read, :update], :all
@ability.can?(:read, 123).should be_true
@ability.can?(:update, 123).should be_true
@ability.can?(:count, 123).should be_false
end
it "should be able to specify multiple classes and match any" do
@ability.can :update, [String, Range]
@ability.can :update, [String, Array]
@ability.can?(:update, "foo").should be_true
@ability.can?(:update, 1..3).should be_true
@ability.can?(:update, []).should be_true
@ability.can?(:update, 123).should be_false
end
it "should support custom objects in the rule" do
it "should support custom objects in the can definition" do
@ability.can :read, :stats
@ability.can?(:read, :stats).should be_true
@ability.can?(:update, :stats).should be_false
@ability.can?(:read, :nonstats).should be_false
end
it "should check ancestors of class" do
@ability.can :read, Numeric
@ability.can?(:read, Integer).should be_true
@ability.can?(:read, 1.23).should be_true
@ability.can?(:read, "foo").should be_false
end
it "should support 'cannot' method to define what user cannot do" do
@ability.can :read, :all
@ability.cannot :read, Integer
@ability.can?(:read, "foo").should be_true
@ability.can?(:read, 123).should be_false
end
it "should pass to previous rule, if block returns false or nil" do
it "should support block on 'cannot' method" do
@ability.can :read, :all
@ability.cannot :read, Integer do |int|
int > 10 ? nil : ( int > 5 )
int > 5
end
@ability.can?(:read, "foo").should be_true
@ability.can?(:read, 3).should be_true
@ability.can?(:read, 8).should be_false
@ability.can?(:read, 123).should be_true
end
it "should always return `false` for single cannot definition" do
@ability.cannot :read, Integer do |int|
int > 10 ? nil : ( int > 5 )
end
@ability.can?(:read, "foo").should be_false
@ability.can?(:read, 3).should be_false
@ability.can?(:read, 8).should be_false
@ability.can?(:read, 123).should be_false
end
it "should pass to previous cannot definition, if block returns false or nil" do
@ability.cannot :read, :all
@ability.can :read, Integer do |int|
int > 10 ? nil : ( int > 5 )
end
@ability.can?(:read, "foo").should be_false
@ability.can?(:read, 3).should be_false
@ability.can?(:read, 10).should be_true
@ability.can?(:read, 123).should be_false
end
it "should append aliased actions" do
@ability.alias_action :update, :to => :modify
@ability.alias_action :destroy, :to => :modify
@ability.aliased_actions[:modify].should == [:update, :destroy]
end
it "should clear aliased actions" do
@ability.alias_action :update, :to => :modify
@ability.clear_aliased_actions
@ability.aliased_actions[:modify].should be_nil
end
it "should pass additional arguments to block from can?" do
@ability.can :read, Integer do |int, x|
int > x
end
@ability.can?(:read, 2, 1).should be_true
@ability.can?(:read, 2, 3).should be_false
end
it "should use conditions as third parameter and determine abilities from it" do
@ability.can :read, Range, :begin => 1, :end => 3
@ability.can?(:read, 1..3).should be_true
@ability.can?(:read, 1..4).should be_false
@ability.can?(:read, Range).should be_true
end
it "should allow an array of options in conditions hash" do
@ability.can :read, Range, :begin => [1, 3, 5]
@ability.can?(:read, 1..3).should be_true
@ability.can?(:read, 2..4).should be_false
@ability.can?(:read, 3..5).should be_true
end
it "should allow a range of options in conditions hash" do
@ability.can :read, Range, :begin => 1..3
@ability.can?(:read, 1..10).should be_true
@ability.can?(:read, 3..30).should be_true
@ability.can?(:read, 4..40).should be_false
end
it "should allow nested hashes in conditions hash" do
@ability.can :read, Range, :begin => { :to_i => 5 }
@ability.can?(:read, 5..7).should be_true
@ability.can?(:read, 6..8).should be_false
end
it "should match any element passed in to nesting if it's an array (for has_many associations)" do
@ability.can :read, Range, :to_a => { :to_i => 3 }
@ability.can?(:read, 1..5).should be_true
@ability.can?(:read, 4..6).should be_false
end
it "should accept a set as a condition value" do
mock(object_with_foo_2 = Object.new).foo { 2 }
mock(object_with_foo_3 = Object.new).foo { 3 }
@ability.can :read, Object, :foo => [1, 2, 5].to_set
@ability.can?(:read, object_with_foo_2).should be_true
@ability.can?(:read, object_with_foo_3).should be_false
end
it "should not match subjects return nil for methods that must match nested a nested conditions hash" do
mock(object_with_foo = Object.new).foo { :bar }
@ability.can :read, Array, :first => { :foo => :bar }
@ability.can?(:read, [object_with_foo]).should be_true
@ability.can?(:read, []).should be_false
end
it "should match strings but not substrings specified in a conditions hash" do
@ability.can :read, String, :presence => "declassified"
@ability.can?(:read, "declassified").should be_true
@ability.can?(:read, "classified").should be_false
end
it "should not stop at cannot definition when comparing class" do
@ability.can :read, Range
@ability.cannot :read, Range, :begin => 1
@ability.can?(:read, 2..5).should be_true
@ability.can?(:read, 1..5).should be_false
@ability.can?(:read, Range).should be_true
end
it "should 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 "passing a hash of subjects with multiple definitions should check permissions correctly" do
@ability.can :read, Range, :string => {:length => 4}
@ability.can [:create, :read], Range, :string => {:upcase => 'FOO'}
@ability.can?(:read, "foo" => Range).should be_true
@ability.can?(:read, "foobar" => Range).should be_false
@ability.can?(:read, 1234 => Range).should be_true
end
it "should allow to check ability on Hash-like object" do
class Container < Hash; end
@ability.can :read, Container
@ability.can?(:read, Container.new).should be_true
end
it "should have initial attributes based on hash conditions of 'new' action" do
@ability.can :manage, Range, :foo => "foo", :hash => {:skip => "hashes"}
@ability.can :create, Range, :bar => 123, :array => %w[skip arrays]
@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 and return subject" do
@ability.can :read, :foo
lambda {
@ability.authorize!(:read, :foo).should == :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
it "should raise an error when attempting to use a block with a hash condition since it's not likely what they want" do
lambda {
@ability.can :read, Array, :published => true do
false
end
}.should raise_error(CanCan::Error, "You are not able to supply a block with a hash of conditions in read Array ability. Use either one.")
end
describe "unauthorized message" do
after(:each) do
I18n.backend = nil
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(:update, ArgumentError).should == "update argument error"
@ability.unauthorized_message(:edit, 1..3).should == "edit range"
end
end
describe "#merge" do
it "should add the rules from the given ability" do
@ability.can :use, :tools
another_ability = Object.new
another_ability.extend(CanCan::Ability)
another_ability.can :use, :search
@ability.merge(another_ability)
@ability.can?(:use, :search).should be_true
@ability.send(:rules).size.should == 2
end
end
end

View File

@ -1,137 +1,45 @@
require "spec_helper"
require File.dirname(__FILE__) + '/../spec_helper'
describe CanCan::ControllerAdditions do
before(:each) do
@controller_class = Class.new
@controller = @controller_class.new
stub(@controller).params { {} }
stub(@controller).current_user { :current_user }
mock(@controller_class).helper_method(:can?, :cannot?, :current_ability)
mock(@controller_class).helper_method(:can?, :cannot?)
@controller_class.send(:include, CanCan::ControllerAdditions)
end
it "should raise ImplementationRemoved when attempting to call 'unauthorized!' on a controller" do
lambda { @controller.unauthorized! }.should raise_error(CanCan::ImplementationRemoved)
it "should read from the cache with request uri as key and render that text" do
lambda {
@controller.unauthorized!
}.should raise_error(CanCan::AccessDenied)
end
it "authorize! should assign @_authorized instance variable and pass args to current ability" do
mock(@controller.current_ability).authorize!(:foo, :bar)
@controller.authorize!(:foo, :bar)
@controller.instance_variable_get(:@_authorized).should be_true
end
it "should have a current_ability method which generates an ability for the current user" do
stub(@controller).current_user { :current_user }
@controller.current_ability.should be_kind_of(Ability)
end
it "should provide a can? and cannot? methods which go through the current ability" do
stub(@controller).current_user { :current_user }
@controller.current_ability.should be_kind_of(Ability)
@controller.can?(:foo, :bar).should be_false
@controller.cannot?(:foo, :bar).should be_true
end
it "load_and_authorize_resource should setup a before filter which passes call to ControllerResource" do
stub(CanCan::ControllerResource).new(@controller, nil, :foo => :bar).mock!.load_and_authorize_resource
mock(@controller_class).before_filter({}) { |options, block| block.call(@controller) }
@controller_class.load_and_authorize_resource :foo => :bar
it "should load resource" do
mock.instance_of(CanCan::ResourceAuthorization).load_resource
@controller.load_resource
end
it "load_and_authorize_resource should properly pass first argument as the resource name" do
stub(CanCan::ControllerResource).new(@controller, :project, :foo => :bar).mock!.load_and_authorize_resource
mock(@controller_class).before_filter({}) { |options, block| block.call(@controller) }
@controller_class.load_and_authorize_resource :project, :foo => :bar
it "should authorize resource" do
mock.instance_of(CanCan::ResourceAuthorization).authorize_resource
@controller.authorize_resource
end
it "load_and_authorize_resource with :prepend should prepend the before filter" do
mock(@controller_class).prepend_before_filter({})
@controller_class.load_and_authorize_resource :foo => :bar, :prepend => true
end
it "authorize_resource should setup a before filter which passes call to ControllerResource" do
stub(CanCan::ControllerResource).new(@controller, nil, :foo => :bar).mock!.authorize_resource
mock(@controller_class).before_filter(:except => :show, :if => true) { |options, block| block.call(@controller) }
@controller_class.authorize_resource :foo => :bar, :except => :show, :if => true
end
it "load_resource should setup a before filter which passes call to ControllerResource" do
stub(CanCan::ControllerResource).new(@controller, nil, :foo => :bar).mock!.load_resource
mock(@controller_class).before_filter(:only => [:show, :index], :unless => false) { |options, block| block.call(@controller) }
@controller_class.load_resource :foo => :bar, :only => [:show, :index], :unless => false
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(:only => [:test]) { |options, block| block.call(@controller) }
lambda {
@controller_class.check_authorization(:only => [:test])
}.should raise_error(CanCan::AuthorizationNotPerformed)
end
it "check_authorization should not trigger AuthorizationNotPerformed when :if is false" do
stub(@controller).check_auth? { false }
mock(@controller_class).after_filter({}) { |options, block| block.call(@controller) }
lambda {
@controller_class.check_authorization(:if => :check_auth?)
}.should_not raise_error(CanCan::AuthorizationNotPerformed)
end
it "check_authorization should not trigger AuthorizationNotPerformed when :unless is true" do
stub(@controller).engine_controller? { true }
mock(@controller_class).after_filter({}) { |options, block| block.call(@controller) }
lambda {
@controller_class.check_authorization(:unless => :engine_controller?)
}.should_not raise_error(CanCan::AuthorizationNotPerformed)
end
it "check_authorization should not raise error when @_authorized is set" do
@controller.instance_variable_set(:@_authorized, true)
mock(@controller_class).after_filter(:only => [:test]) { |options, block| block.call(@controller) }
lambda {
@controller_class.check_authorization(:only => [:test])
}.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]}
it "should load and authorize resource in one call through controller" do
mock(@controller).load_resource
mock(@controller).authorize_resource
@controller.load_and_authorize_resource
end
end

View File

@ -1,491 +0,0 @@
require "spec_helper"
describe CanCan::ControllerResource 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 "should load the resource into an instance variable if params[:id] is specified" do
project = Project.create!
@params.merge!(:action => "show", :id => project.id)
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).should == project
end
it "should not load resource into an instance variable if already set" do
@params.merge!(:action => "show", :id => "123")
@controller.instance_variable_set(:@project, :some_project)
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).should == :some_project
end
it "should properly load resource for namespaced controller" do
project = Project.create!
@params.merge!(:controller => "admin/projects", :action => "show", :id => project.id)
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).should == project
end
it "should attempt to load a resource with the same namespace as the controller when using :: for namespace" do
module MyEngine
class Project < ::Project; end
end
project = MyEngine::Project.create!
@params.merge!(:controller => "MyEngine::ProjectsController", :action => "show", :id => project.id)
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).should == project
end
# Rails includes namespace in params, see issue #349
it "should create through the namespaced params" do
module MyEngine
class Project < ::Project; end
end
@params.merge!(:controller => "MyEngine::ProjectsController", :action => "create", :my_engine_project => {:name => "foobar"})
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).name.should == "foobar"
end
it "should properly load resource for namespaced controller when using '::' for namespace" do
project = Project.create!
@params.merge!(:controller => "Admin::ProjectsController", :action => "show", :id => project.id)
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).should == project
end
it "has the specified nested resource_class when using / for namespace" do
module Admin
class Dashboard; end
end
@ability.can(:index, "admin/dashboard")
@params.merge!(:controller => "admin/dashboard", :action => "index")
resource = CanCan::ControllerResource.new(@controller, :authorize => true)
resource.send(:resource_class).should == Admin::Dashboard
end
it "should build a new resource with hash if params[:id] is not specified" do
@params.merge!(:action => "create", :project => {:name => "foobar"})
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).name.should == "foobar"
end
it "should build a new resource for namespaced model with hash if params[:id] is not specified" do
@params.merge!(:action => "create", 'sub_project' => {:name => "foobar"})
resource = CanCan::ControllerResource.new(@controller, :class => ::Sub::Project)
resource.load_resource
@controller.instance_variable_get(:@project).name.should == "foobar"
end
it "should build a new resource for namespaced controller and namespaced model with hash if params[:id] is not specified" do
@params.merge!(:controller => "Admin::SubProjectsController", :action => "create", 'sub_project' => {:name => "foobar"})
resource = CanCan::ControllerResource.new(@controller, :class => Project)
resource.load_resource
@controller.instance_variable_get(:@sub_project).name.should == "foobar"
end
it "should build a new resource with attributes from current ability" do
@params.merge!(:action => "new")
@ability.can(:create, Project, :name => "from conditions")
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).name.should == "from conditions"
end
it "should 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, :index) { :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"
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).should be_nil
@controller.instance_variable_defined?(:@projects).should be_false
end
it "should not use accessible_by when defining abilities through a block" do
stub(Project).accessible_by(@ability) { :found_projects }
@params[:action] = "index"
@ability.can(:read, Project) { |p| false }
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).should be_nil
@controller.instance_variable_defined?(:@projects).should be_false
end
it "should not authorize single resource in collection action" do
@params[:action] = "index"
@controller.instance_variable_set(:@project, :some_project)
stub(@controller).authorize!(:index, Project) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller)
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
end
it "should authorize parent resource in collection action" do
@params[:action] = "index"
@controller.instance_variable_set(:@category, :some_category)
stub(@controller).authorize!(:show, :some_category) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller, :category, :parent => true)
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
end
it "should perform authorization using controller action and loaded model" do
@params.merge!(:action => "show", :id => "123")
@controller.instance_variable_set(:@project, :some_project)
stub(@controller).authorize!(:show, :some_project) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller)
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
end
it "should perform authorization using controller action and non loaded model" do
@params.merge!(:action => "show", :id => "123")
stub(@controller).authorize!(:show, Project) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller)
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
end
it "should call load_resource and authorize_resource for load_and_authorize_resource" do
@params.merge!(:action => "show", :id => "123")
resource = CanCan::ControllerResource.new(@controller)
mock(resource).load_resource
mock(resource).authorize_resource
resource.load_and_authorize_resource
end
it "should not build a single resource when on custom collection action even with id" do
@params.merge!(:action => "sort", :id => "123")
resource = CanCan::ControllerResource.new(@controller, :collection => [:sort, :list])
resource.load_resource
@controller.instance_variable_get(:@project).should be_nil
end
it "should load a collection resource when on custom action with no id param" do
stub(Project).accessible_by(@ability, :sort) { :found_projects }
@params[:action] = "sort"
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).should be_nil
@controller.instance_variable_get(:@projects).should == :found_projects
end
it "should build a resource when on custom new action even when params[:id] exists" do
@params.merge!(:action => "build", :id => "123")
stub(Project).new { :some_project }
resource = CanCan::ControllerResource.new(@controller, :new => :build)
resource.load_resource
@controller.instance_variable_get(:@project).should == :some_project
end
it "should not try to load resource for other action if params[:id] is undefined" do
@params[:action] = "list"
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).should be_nil
end
it "should be a parent resource when name is provided which doesn't match controller" do
resource = CanCan::ControllerResource.new(@controller, :category)
resource.should be_parent
end
it "should not be a parent resource when name is provided which matches controller" do
resource = CanCan::ControllerResource.new(@controller, :project)
resource.should_not be_parent
end
it "should be parent if specified in options" do
resource = CanCan::ControllerResource.new(@controller, :project, {:parent => true})
resource.should be_parent
end
it "should not be parent if specified in options" do
resource = CanCan::ControllerResource.new(@controller, :category, {:parent => false})
resource.should_not be_parent
end
it "should have the specified resource_class if 'name' is passed to load_resource" do
class Section
end
resource = CanCan::ControllerResource.new(@controller, :section)
resource.send(:resource_class).should == Section
end
it "should load parent resource through proper id parameter" do
project = Project.create!
@params.merge!(:controller => "categories", :action => "index", :project_id => project.id)
resource = CanCan::ControllerResource.new(@controller, :project)
resource.load_resource
@controller.instance_variable_get(:@project).should == project
end
it "should load resource through the association of another parent resource using instance variable" do
@params.merge!(:action => "show", :id => "123")
category = Object.new
@controller.instance_variable_set(:@category, category)
stub(category).projects.stub!.find("123") { :some_project }
resource = CanCan::ControllerResource.new(@controller, :through => :category)
resource.load_resource
@controller.instance_variable_get(:@project).should == :some_project
end
it "should load resource through the custom association name" do
@params.merge!(:action => "show", :id => "123")
category = Object.new
@controller.instance_variable_set(:@category, category)
stub(category).custom_projects.stub!.find("123") { :some_project }
resource = CanCan::ControllerResource.new(@controller, :through => :category, :through_association => :custom_projects)
resource.load_resource
@controller.instance_variable_get(:@project).should == :some_project
end
it "should load resource through the association of another parent resource using method" do
@params.merge!(:action => "show", :id => "123")
category = Object.new
stub(@controller).category { category }
stub(category).projects.stub!.find("123") { :some_project }
resource = CanCan::ControllerResource.new(@controller, :through => :category)
resource.load_resource
@controller.instance_variable_get(:@project).should == :some_project
end
it "should not load through parent resource if instance isn't loaded when shallow" do
project = Project.create!
@params.merge!(:action => "show", :id => project.id)
resource = CanCan::ControllerResource.new(@controller, :through => :category, :shallow => true)
resource.load_resource
@controller.instance_variable_get(:@project).should == project
end
it "should raise AccessDenied when attempting to load resource through nil" do
project = Project.create!
@params.merge!(:action => "show", :id => project.id)
resource = CanCan::ControllerResource.new(@controller, :through => :category)
lambda {
resource.load_resource
}.should raise_error(CanCan::AccessDenied) { |exception|
exception.action.should == :show
exception.subject.should == Project
}
@controller.instance_variable_get(:@project).should be_nil
end
it "should authorize nested resource through parent association on index action" do
@params.merge!(:action => "index")
category = Object.new
@controller.instance_variable_set(:@category, category)
stub(@controller).authorize!(:index, category => Project) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller, :through => :category)
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
end
it "should load through first matching if multiple are given" do
@params.merge!(:action => "show", :id => "123")
category = Object.new
@controller.instance_variable_set(:@category, category)
stub(category).projects.stub!.find("123") { :some_project }
resource = CanCan::ControllerResource.new(@controller, :through => [:category, :user])
resource.load_resource
@controller.instance_variable_get(:@project).should == :some_project
end
it "should find record through has_one association with :singleton option without id param" do
@params.merge!(:action => "show", :id => nil)
category = Object.new
@controller.instance_variable_set(:@category, category)
stub(category).project { :some_project }
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true)
resource.load_resource
@controller.instance_variable_get(:@project).should == :some_project
end
it "should not build record through has_one association with :singleton option because it can cause it to delete it in the database" do
@params.merge!(:action => "create", :project => {:name => "foobar"})
category = Category.new
@controller.instance_variable_set(:@category, category)
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true)
resource.load_resource
@controller.instance_variable_get(:@project).name.should == "foobar"
@controller.instance_variable_get(:@project).category.should == category
end
it "should find record through has_one association with :singleton and :shallow options" do
project = Project.create!
@params.merge!(:action => "show", :id => project.id)
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true, :shallow => true)
resource.load_resource
@controller.instance_variable_get(:@project).should == project
end
it "should build record through has_one association with :singleton and :shallow options" do
@params.merge!(:action => "create", :project => {:name => "foobar"})
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true, :shallow => true)
resource.load_resource
@controller.instance_variable_get(:@project).name.should == "foobar"
end
it "should only authorize :show action on parent resource" do
project = Project.create!
@params.merge!(:action => "new", :project_id => project.id)
stub(@controller).authorize!(:show, project) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller, :project, :parent => true)
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
end
it "should load the model using a custom class" do
project = Project.create!
@params.merge!(:action => "show", :id => project.id)
resource = CanCan::ControllerResource.new(@controller, :class => Project)
resource.load_resource
@controller.instance_variable_get(:@project).should == project
end
it "should load the model using a custom namespaced class" do
project = Sub::Project.create!
@params.merge!(:action => "show", :id => project.id)
resource = CanCan::ControllerResource.new(@controller, :class => ::Sub::Project)
resource.load_resource
@controller.instance_variable_get(:@project).should == project
end
it "should authorize based on resource name if class is false" do
@params.merge!(:action => "show", :id => "123")
stub(@controller).authorize!(:show, :project) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller, :class => false)
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
end
it "should load and authorize using custom instance name" do
project = Project.create!
@params.merge!(:action => "show", :id => project.id)
stub(@controller).authorize!(:show, project) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller, :instance_name => :custom_project)
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
@controller.instance_variable_get(:@custom_project).should == project
end
it "should load resource using custom ID param" do
project = Project.create!
@params.merge!(:action => "show", :the_project => project.id)
resource = CanCan::ControllerResource.new(@controller, :id_param => :the_project)
resource.load_resource
@controller.instance_variable_get(:@project).should == project
end
# CVE-2012-5664
it "should always convert id param to string" do
@params.merge!(:action => "show", :the_project => { :malicious => "I am" })
resource = CanCan::ControllerResource.new(@controller, :id_param => :the_project)
resource.send(:id_param).class.should == String
end
it "should load resource using custom find_by attribute" do
project = Project.create!(:name => "foo")
@params.merge!(:action => "show", :id => "foo")
resource = CanCan::ControllerResource.new(@controller, :find_by => :name)
resource.load_resource
@controller.instance_variable_get(:@project).should == project
end
it "should allow full find method to be passed into find_by option" do
project = Project.create!(:name => "foo")
@params.merge!(:action => "show", :id => "foo")
resource = CanCan::ControllerResource.new(@controller, :find_by => :find_by_name)
resource.load_resource
@controller.instance_variable_get(:@project).should == project
end
it "should raise ImplementationRemoved when adding :name option" do
lambda {
CanCan::ControllerResource.new(@controller, :name => :foo)
}.should raise_error(CanCan::ImplementationRemoved)
end
it "should raise ImplementationRemoved exception when specifying :resource option since it is no longer used" do
lambda {
CanCan::ControllerResource.new(@controller, :resource => Project)
}.should raise_error(CanCan::ImplementationRemoved)
end
it "should raise ImplementationRemoved exception when passing :nested option" do
lambda {
CanCan::ControllerResource.new(@controller, :nested => :project)
}.should raise_error(CanCan::ImplementationRemoved)
end
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

View File

@ -1,58 +0,0 @@
require "spec_helper"
describe CanCan::AccessDenied do
describe "with action and subject" do
before(:each) do
@exception = CanCan::AccessDenied.new(nil, :some_action, :some_subject)
end
it "should have action and subject accessors" do
@exception.action.should == :some_action
@exception.subject.should == :some_subject
end
it "should have a changable default message" do
@exception.message.should == "You are not authorized to access this page."
@exception.default_message = "Unauthorized!"
@exception.message.should == "Unauthorized!"
end
end
describe "with only a message" do
before(:each) do
@exception = CanCan::AccessDenied.new("Access denied!")
end
it "should have nil action and subject" do
@exception.action.should be_nil
@exception.subject.should be_nil
end
it "should have passed message" do
@exception.message.should == "Access denied!"
end
end
describe "i18n in the default message" do
after(:each) do
I18n.backend = nil
end
it "uses i18n for the default message" do
I18n.backend.store_translations :en, :unauthorized => {:default => "This is a different message"}
@exception = CanCan::AccessDenied.new
@exception.message.should == "This is a different message"
end
it "defaults to a nice message" do
@exception = CanCan::AccessDenied.new
@exception.message.should == "You are not authorized to access this page."
end
it "does not use translation if a message is given" do
@exception = CanCan::AccessDenied.new("Hey! You're not welcome here")
@exception.message.should == "Hey! You're not welcome here"
@exception.message.should_not == "You are not authorized to access this page."
end
end
end

View File

@ -1,60 +0,0 @@
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.merge!(:action => "show", :id => 123)
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.association_chain when parent" do
@params[:action] = "index"
stub(@controller).association_chain { @controller.instance_variable_set(:@project, :project_resource) }
CanCan::InheritedResource.new(@controller, :parent => true).load_resource
@controller.instance_variable_get(:@project).should == :project_resource
end
it "index should load through @controller.end_of_association_chain" do
@params[:action] = "index"
stub(Project).accessible_by(@ability, :index) { :projects }
stub(@controller).end_of_association_chain { Project }
CanCan::InheritedResource.new(@controller).load_resource
@controller.instance_variable_get(:@projects).should == :projects
end
it "should build a new resource with attributes from current ability" do
@params[:action] = "new"
@ability.can(:create, Project, :name => "from conditions")
stub(@controller).build_resource { Struct.new(:name).new }
resource = CanCan::InheritedResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).name.should == "from conditions"
end
it "should override initial attributes with params" do
@params.merge!(:action => "new", :project => {:name => "from params"})
@ability.can(:create, Project, :name => "from conditions")
stub(@controller).build_resource { Struct.new(:name).new }
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).name.should == "from params"
end
end

View File

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

View File

@ -1,320 +0,0 @@
if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
require "spec_helper"
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
describe CanCan::ModelAdapters::ActiveRecordAdapter do
with_model :category do
table do |t|
t.boolean "visible"
end
model do
has_many :articles
end
end
with_model :article do
table do |t|
t.string "name"
t.boolean "published"
t.boolean "secret"
t.integer "priority"
t.integer "category_id"
t.integer "user_id"
end
model do
belongs_to :category
has_many :comments
belongs_to :user
end
end
with_model :comment do
table do |t|
t.boolean "spam"
t.integer "article_id"
end
model do
belongs_to :article
end
end
with_model :user do
table do |t|
end
model do
has_many :articles
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 find record" do
article = Article.create!
CanCan::ModelAdapters::ActiveRecordAdapter.find(Article, article.id).should == article
end
it "should not fetch any records when no abilities are defined" do
Article.create!
Article.accessible_by(@ability).should be_empty
end
it "should fetch all articles when one can read all" do
@ability.can :read, Article
article = Article.create!
Article.accessible_by(@ability).should == [article]
end
it "should fetch only the articles that are published" do
@ability.can :read, Article, :published => true
article1 = Article.create!(:published => true)
article2 = Article.create!(:published => false)
Article.accessible_by(@ability).should == [article1]
end
it "should fetch any articles which are published or secret" do
@ability.can :read, Article, :published => true
@ability.can :read, Article, :secret => true
article1 = Article.create!(:published => true, :secret => false)
article2 = Article.create!(:published => true, :secret => true)
article3 = Article.create!(:published => false, :secret => true)
article4 = Article.create!(:published => false, :secret => false)
Article.accessible_by(@ability).should == [article1, article2, article3]
end
it "should fetch only the articles that are published and not secret" do
@ability.can :read, Article, :published => true
@ability.cannot :read, Article, :secret => true
article1 = Article.create!(:published => true, :secret => false)
article2 = Article.create!(:published => true, :secret => true)
article3 = Article.create!(:published => false, :secret => true)
article4 = Article.create!(:published => false, :secret => false)
Article.accessible_by(@ability).should == [article1]
end
it "should only read comments for articles which are published" do
@ability.can :read, Comment, :article => { :published => true }
comment1 = Comment.create!(:article => Article.create!(:published => true))
comment2 = Comment.create!(:article => Article.create!(:published => false))
Comment.accessible_by(@ability).should == [comment1]
end
it "should only read comments for visible categories through articles" do
@ability.can :read, Comment, :article => { :category => { :visible => true } }
comment1 = Comment.create!(:article => Article.create!(:category => Category.create!(:visible => true)))
comment2 = Comment.create!(:article => Article.create!(:category => Category.create!(:visible => false)))
Comment.accessible_by(@ability).should == [comment1]
end
it "should allow conditions in SQL and merge with hash conditions" do
@ability.can :read, Article, :published => true
@ability.can :read, Article, ["secret=?", true]
article1 = Article.create!(:published => true, :secret => false)
article2 = Article.create!(:published => true, :secret => true)
article3 = Article.create!(:published => false, :secret => true)
article4 = Article.create!(:published => false, :secret => false)
Article.accessible_by(@ability).should == [article1, article2, article3]
end
it "should allow a scope for conditions" do
@ability.can :read, Article, Article.where(:secret => true)
article1 = Article.create!(:secret => true)
article2 = Article.create!(:secret => false)
Article.accessible_by(@ability).should == [article1]
end
it "should fetch only associated records when using with a scope for conditions" do
@ability.can :read, Article, Article.where(:secret => true)
category1 = Category.create!(:visible => false)
category2 = Category.create!(:visible => true)
article1 = Article.create!(:secret => true, :category => category1)
article2 = Article.create!(:secret => true, :category => category2)
category1.articles.accessible_by(@ability).should == [article1]
end
it "should raise an exception when trying to merge scope with other conditions" do
@ability.can :read, Article, :published => true
@ability.can :read, Article, Article.where(:secret => true)
lambda { Article.accessible_by(@ability) }.should raise_error(CanCan::Error, "Unable to merge an Active Record scope with other conditions. Instead use a hash or SQL for read Article ability.")
end
it "should not allow to fetch records when ability with just block present" do
@ability.can :read, Article do
false
end
lambda { Article.accessible_by(@ability) }.should raise_error(CanCan::Error)
end
it "should not allow to check ability on object against SQL conditions without block" do
@ability.can :read, Article, ["secret=?", true]
lambda { @ability.can? :read, Article.new }.should raise_error(CanCan::Error)
end
it "should have false conditions if no abilities match" do
@ability.model_adapter(Article, :read).conditions.should == "'t'='f'"
end
it "should return false conditions for cannot clause" do
@ability.cannot :read, Article
@ability.model_adapter(Article, :read).conditions.should == "'t'='f'"
end
it "should return SQL for single `can` definition in front of default `cannot` condition" do
@ability.cannot :read, Article
@ability.can :read, Article, :published => false, :secret => true
@ability.model_adapter(Article, :read).conditions.should orderlessly_match(%Q["#{@article_table}"."published" = 'f' AND "#{@article_table}"."secret" = 't'])
end
it "should return true condition for single `can` definition in front of default `can` condition" do
@ability.can :read, Article
@ability.can :read, Article, :published => false, :secret => true
@ability.model_adapter(Article, :read).conditions.should == "'t'='t'"
end
it "should return `false condition` for single `cannot` definition in front of default `cannot` condition" do
@ability.cannot :read, Article
@ability.cannot :read, Article, :published => false, :secret => true
@ability.model_adapter(Article, :read).conditions.should == "'t'='f'"
end
it "should return `not (sql)` for single `cannot` definition in front of default `can` condition" do
@ability.can :read, Article
@ability.cannot :read, Article, :published => false, :secret => true
@ability.model_adapter(Article, :read).conditions.should orderlessly_match(%Q["not (#{@article_table}"."published" = 'f' AND "#{@article_table}"."secret" = 't')])
end
it "should return appropriate sql conditions in complex case" do
@ability.can :read, Article
@ability.can :manage, Article, :id => 1
@ability.can :update, Article, :published => true
@ability.cannot :update, Article, :secret => true
@ability.model_adapter(Article, :update).conditions.should == %Q[not ("#{@article_table}"."secret" = 't') AND (("#{@article_table}"."published" = 't') OR ("#{@article_table}"."id" = 1))]
@ability.model_adapter(Article, :manage).conditions.should == {:id => 1}
@ability.model_adapter(Article, :read).conditions.should == "'t'='t'"
end
it "should return appropriate sql conditions in complex case with nested joins" do
@ability.can :read, Comment, :article => { :category => { :visible => true } }
@ability.model_adapter(Comment, :read).conditions.should == { Category.table_name.to_sym => { :visible => true } }
end
it "should return appropriate sql conditions in complex case with nested joins of different depth" do
@ability.can :read, Comment, :article => { :published => true, :category => { :visible => true } }
@ability.model_adapter(Comment, :read).conditions.should == { Article.table_name.to_sym => { :published => true }, Category.table_name.to_sym => { :visible => true } }
end
it "should not forget conditions when calling with SQL string" do
@ability.can :read, Article, :published => true
@ability.can :read, Article, ['secret=?', false]
adapter = @ability.model_adapter(Article, :read)
2.times do
adapter.conditions.should == %Q[(secret='f') OR ("#{@article_table}"."published" = 't')]
end
end
it "should have nil joins if no rules" do
@ability.model_adapter(Article, :read).joins.should be_nil
end
it "should have nil joins if no nested hashes specified in conditions" do
@ability.can :read, Article, :published => false
@ability.can :read, Article, :secret => true
@ability.model_adapter(Article, :read).joins.should be_nil
end
it "should merge separate joins into a single array" do
@ability.can :read, Article, :project => { :blocked => false }
@ability.can :read, Article, :company => { :admin => true }
@ability.model_adapter(Article, :read).joins.inspect.should orderlessly_match([:company, :project].inspect)
end
it "should merge same joins into a single array" do
@ability.can :read, Article, :project => { :blocked => false }
@ability.can :read, Article, :project => { :admin => true }
@ability.model_adapter(Article, :read).joins.should == [:project]
end
it "should merge nested and non-nested joins" do
@ability.can :read, Article, :project => { :blocked => false }
@ability.can :read, Article, :project => { :comments => { :spam => true } }
@ability.model_adapter(Article, :read).joins.should == [{:project=>[:comments]}]
end
it "should merge :all conditions with other conditions" do
user = User.create!
article = Article.create!(:user => user)
ability = Ability.new(user)
ability.can :manage, :all
ability.can :manage, Article, :user_id => user.id
Article.accessible_by(ability).should == [article]
end
it "should restrict articles given a MetaWhere condition" do
@ability.can :read, Article, :priority.lt => 2
article1 = Article.create!(:priority => 1)
article2 = Article.create!(:priority => 3)
Article.accessible_by(@ability).should == [article1]
@ability.should be_able_to(:read, article1)
@ability.should_not be_able_to(:read, article2)
end
it "should merge MetaWhere and non-MetaWhere conditions" do
@ability.can :read, Article, :priority.lt => 2
@ability.can :read, Article, :priority => 1
article1 = Article.create!(:priority => 1)
article2 = Article.create!(:priority => 3)
Article.accessible_by(@ability).should == [article1]
@ability.should be_able_to(:read, article1)
@ability.should_not be_able_to(:read, article2)
end
it "should match any MetaWhere condition" do
adapter = CanCan::ModelAdapters::ActiveRecordAdapter
article1 = Article.new(:priority => 1, :name => "Hello World")
adapter.matches_condition?(article1, :priority.eq, 1).should be_true
adapter.matches_condition?(article1, :priority.eq, 2).should be_false
adapter.matches_condition?(article1, :priority.eq_any, [1, 2]).should be_true
adapter.matches_condition?(article1, :priority.eq_any, [2, 3]).should be_false
adapter.matches_condition?(article1, :priority.eq_all, [1, 1]).should be_true
adapter.matches_condition?(article1, :priority.eq_all, [1, 2]).should be_false
adapter.matches_condition?(article1, :priority.ne, 2).should be_true
adapter.matches_condition?(article1, :priority.ne, 1).should be_false
adapter.matches_condition?(article1, :priority.in, [1, 2]).should be_true
adapter.matches_condition?(article1, :priority.in, [2, 3]).should be_false
adapter.matches_condition?(article1, :priority.nin, [2, 3]).should be_true
adapter.matches_condition?(article1, :priority.nin, [1, 2]).should be_false
adapter.matches_condition?(article1, :priority.lt, 2).should be_true
adapter.matches_condition?(article1, :priority.lt, 1).should be_false
adapter.matches_condition?(article1, :priority.lteq, 1).should be_true
adapter.matches_condition?(article1, :priority.lteq, 0).should be_false
adapter.matches_condition?(article1, :priority.gt, 0).should be_true
adapter.matches_condition?(article1, :priority.gt, 1).should be_false
adapter.matches_condition?(article1, :priority.gteq, 1).should be_true
adapter.matches_condition?(article1, :priority.gteq, 2).should be_false
adapter.matches_condition?(article1, :name.like, "%ello worl%").should be_true
adapter.matches_condition?(article1, :name.like, "hello world").should be_true
adapter.matches_condition?(article1, :name.like, "hello%").should be_true
adapter.matches_condition?(article1, :name.like, "h%d").should be_true
adapter.matches_condition?(article1, :name.like, "%helo%").should be_false
adapter.matches_condition?(article1, :name.like, "hello").should be_false
adapter.matches_condition?(article1, :name.like, "hello.world").should be_false
# For some reason this is reporting "The not_matches MetaWhere condition is not supported."
# adapter.matches_condition?(article1, :name.nlike, "%helo%").should be_true
# adapter.matches_condition?(article1, :name.nlike, "%ello worl%").should be_false
end
end
end

View File

@ -1,119 +0,0 @@
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 find record" do
article = Article.create
CanCan::ModelAdapters::DataMapperAdapter.find(Article, article.id).should == article
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 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

View File

@ -1,7 +0,0 @@
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

View File

@ -1,227 +0,0 @@
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 find record" do
project = MongoidProject.create
CanCan::ModelAdapters::MongoidAdapter.find(MongoidProject, project.id).should == project
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 be able to read hashes when field is array" do
one_to_three = MongoidProject.create(:numbers => ['one', 'two', 'three'])
two_to_five = MongoidProject.create(:numbers => ['two', 'three', 'four', 'five'])
@ability.can :foo, MongoidProject, :numbers => 'one'
@ability.should be_able_to(:foo, one_to_three)
@ability.should_not be_able_to(:foo, two_to_five)
end
it "should return [] when no ability is defined so no records are found" do
MongoidProject.create(:title => 'Sir')
MongoidProject.create(:title => 'Lord')
MongoidProject.create(:title => 'Dude')
MongoidProject.accessible_by(@ability, :read).entries.should == []
end
it "should return the correct records based on the defined ability" do
@ability.can :read, MongoidProject, :title => "Sir"
sir = MongoidProject.create(:title => 'Sir')
lord = MongoidProject.create(:title => 'Lord')
dude = MongoidProject.create(:title => 'Dude')
MongoidProject.accessible_by(@ability, :read).entries.should == [sir]
end
it "should return the correct records when a mix of can and cannot rules in defined ability" do
@ability.can :manage, MongoidProject, :title => 'Sir'
@ability.cannot :destroy, MongoidProject
sir = MongoidProject.create(:title => 'Sir')
lord = MongoidProject.create(:title => 'Lord')
dude = MongoidProject.create(:title => 'Dude')
MongoidProject.accessible_by(@ability, :destroy).entries.should == [sir]
end
it "should be able to mix empty conditions and hashes" do
@ability.can :read, MongoidProject
@ability.can :read, MongoidProject, :title => 'Sir'
sir = MongoidProject.create(:title => 'Sir')
lord = MongoidProject.create(:title => 'Lord')
MongoidProject.accessible_by(@ability, :read).count.should == 2
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
it "should allow a scope for conditions" do
@ability.can :read, MongoidProject, MongoidProject.where(:title => 'Sir')
sir = MongoidProject.create(:title => 'Sir')
lord = MongoidProject.create(:title => 'Lord')
dude = MongoidProject.create(:title => 'Dude')
MongoidProject.accessible_by(@ability, :read).entries.should == [sir]
end
describe "Mongoid::Criteria where clause Symbol extensions using MongoDB expressions" do
it "should handle :field.in" do
obj = MongoidProject.create(:title => 'Sir')
@ability.can :read, MongoidProject, :title.in => ["Sir", "Madam"]
@ability.can?(:read, obj).should == true
MongoidProject.accessible_by(@ability, :read).should == [obj]
obj2 = MongoidProject.create(:title => 'Lord')
@ability.can?(:read, obj2).should == false
end
describe "activates only when there are Criteria in the hash" do
it "Calls where on the model class when there are criteria" do
obj = MongoidProject.create(:title => 'Bird')
@conditions = {:title.nin => ["Fork", "Spoon"]}
@ability.can :read, MongoidProject, @conditions
@ability.should be_able_to(:read, obj)
end
it "Calls the base version if there are no mongoid criteria" do
obj = MongoidProject.new(:title => 'Bird')
@conditions = {:id => obj.id}
@ability.can :read, MongoidProject, @conditions
@ability.should be_able_to(:read, obj)
end
end
it "should handle :field.nin" do
obj = MongoidProject.create(:title => 'Sir')
@ability.can :read, MongoidProject, :title.nin => ["Lord", "Madam"]
@ability.can?(:read, obj).should == true
MongoidProject.accessible_by(@ability, :read).should == [obj]
obj2 = MongoidProject.create(:title => 'Lord')
@ability.can?(:read, obj2).should == false
end
it "should handle :field.size" do
obj = MongoidProject.create(:titles => ['Palatin', 'Margrave'])
@ability.can :read, MongoidProject, :titles.size => 2
@ability.can?(:read, obj).should == true
MongoidProject.accessible_by(@ability, :read).should == [obj]
obj2 = MongoidProject.create(:titles => ['Palatin', 'Margrave', 'Marquis'])
@ability.can?(:read, obj2).should == false
end
it "should handle :field.exists" do
obj = MongoidProject.create(:titles => ['Palatin', 'Margrave'])
@ability.can :read, MongoidProject, :titles.exists => true
@ability.can?(:read, obj).should == true
MongoidProject.accessible_by(@ability, :read).should == [obj]
obj2 = MongoidProject.create
@ability.can?(:read, obj2).should == false
end
it "should handle :field.gt" do
obj = MongoidProject.create(:age => 50)
@ability.can :read, MongoidProject, :age.gt => 45
@ability.can?(:read, obj).should == true
MongoidProject.accessible_by(@ability, :read).should == [obj]
obj2 = MongoidProject.create(:age => 40)
@ability.can?(:read, obj2).should == false
end
it "should handle instance not saved to database" do
obj = MongoidProject.new(:title => 'Sir')
@ability.can :read, MongoidProject, :title.in => ["Sir", "Madam"]
@ability.can?(:read, obj).should == true
# accessible_by only returns saved records
MongoidProject.accessible_by(@ability, :read).entries.should == []
obj2 = MongoidProject.new(:title => 'Lord')
@ability.can?(:read, obj2).should == false
end
end
it "should call where with matching ability conditions" do
obj = MongoidProject.create(:foo => {:bar => 1})
@ability.can :read, MongoidProject, :foo => {:bar => 1}
MongoidProject.accessible_by(@ability, :read).entries.first.should == obj
end
it "should exclude from the result if set to cannot" do
obj = MongoidProject.create(:bar => 1)
obj2 = MongoidProject.create(:bar => 2)
@ability.can :read, MongoidProject
@ability.cannot :read, MongoidProject, :bar => 2
MongoidProject.accessible_by(@ability, :read).entries.should == [obj]
end
it "should combine the rules" do
obj = MongoidProject.create(:bar => 1)
obj2 = MongoidProject.create(:bar => 2)
obj3 = MongoidProject.create(:bar => 3)
@ability.can :read, MongoidProject, :bar => 1
@ability.can :read, MongoidProject, :bar => 2
MongoidProject.accessible_by(@ability, :read).entries.should =~ [obj, obj2]
end
it "should not allow to fetch records when ability with just block present" do
@ability.can :read, MongoidProject do
false
end
lambda {
MongoidProject.accessible_by(@ability)
}.should raise_error(CanCan::Error)
end
end
end
end

View File

@ -0,0 +1,59 @@
require File.dirname(__FILE__) + '/../spec_helper'
describe CanCan::ResourceAuthorization do
before(:each) do
@controller = Object.new # simple stub for now
stub(@controller).unauthorized! { raise CanCan::AccessDenied }
end
it "should load the resource into an instance variable if params[:id] is specified" do
stub(Ability).find(123) { :some_resource }
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "show", :id => 123)
authorization.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should properly load resource for namespaced controller" do
stub(Ability).find(123) { :some_resource }
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "admin/abilities", :action => "show", :id => 123)
authorization.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should build a new resource with hash if params[:id] is not specified" do
stub(Ability).new(:foo => "bar") { :some_resource }
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "create", :ability => {:foo => "bar"})
authorization.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should build a new resource even if attribute hash isn't specified" do
stub(Ability).new(nil) { :some_resource }
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "new")
authorization.load_resource
@controller.instance_variable_get(:@ability).should == :some_resource
end
it "should not build a resource when on index action" do
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "index")
authorization.load_resource
@controller.instance_variable_get(:@ability).should be_nil
end
it "should perform authorization using controller action and loaded model" do
@controller.instance_variable_set(:@ability, :some_resource)
stub(@controller).cannot?(:show, :some_resource) { true }
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "show")
lambda {
authorization.authorize_resource
}.should raise_error(CanCan::AccessDenied)
end
it "should perform authorization using controller action and non loaded model" do
stub(@controller).cannot?(:show, Ability) { true }
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "show")
lambda {
authorization.authorize_resource
}.should raise_error(CanCan::AccessDenied)
end
end

View File

@ -1,52 +0,0 @@
require "spec_helper"
require "ostruct" # for OpenStruct below
# 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
it "should not be mergeable if conditions are not simple hashes" do
meta_where = OpenStruct.new(:name => 'metawhere', :column => 'test')
@conditions[meta_where] = :bar
@rule.should be_unmergeable
end
it "should be mergeable if conditions is an empty hash" do
@conditions = {}
@rule.should_not be_unmergeable
end
end

View File

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

View File

@ -1,2 +0,0 @@
--color
--backtrace

View File

@ -1,72 +1,18 @@
require 'rubygems'
require 'bundler/setup'
require 'spec'
require 'active_support'
require 'active_record'
require 'action_controller'
require 'action_view'
require File.dirname(__FILE__) + '/../lib/cancan.rb'
Bundler.require(:default)
require 'supermodel' # shouldn't Bundler do this already?
require 'active_support/all'
require 'matchers'
require 'cancan/matchers'
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
Spec::Runner.configure do |config|
config.mock_with :rr
config.before(:each) do
Project.delete_all
Category.delete_all
end
config.extend WithModel if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
end
# Working around CVE-2012-5664 requires us to convert all ID params
# to strings. Let's switch to using string IDs in tests, otherwise
# SuperModel and/or RR will fail (as strings are not fixnums).
module SuperModel
class Base
def generate_id
object_id.to_s
end
end
end
class Ability
include CanCan::Ability
def initialize(user)
end
end
class Category < SuperModel::Base
has_many :projects
end
module Sub
class Project < SuperModel::Base
belongs_to :category
attr_accessor :category # why doesn't SuperModel do this automatically?
def self.respond_to?(method, include_private = false)
if method.to_s == "find_by_name!" # hack to simulate ActiveRecord
true
else
super
end
end
end
end
class Project < SuperModel::Base
belongs_to :category
attr_accessor :category # why doesn't SuperModel do this automatically?
def self.respond_to?(method, include_private = false)
if method.to_s == "find_by_name!" # hack to simulate ActiveRecord
true
else
super
end
end
end