Compare commits

..

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

31 changed files with 126 additions and 783 deletions

View File

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

View File

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

View File

@ -1,124 +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) 1.6.0 (March 11, 2011)
* Added MetaWhere support - see issue #194 and #261 * Added MetaWhere support - see issue #194 and #261
@ -139,8 +18,6 @@
* Raise an exception when trying to make a Ability condition with both a hash of conditions and a block - see issue #269 * 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) 1.5.1 (January 20, 2011)
@ -148,8 +25,6 @@
* Improving Mongoid support for multiple can and cannot definitions (thanks stellard) - see issue #239 * 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) 1.5.0 (January 11, 2011)
@ -171,8 +46,6 @@
* Internal: added .rvmrc to auto-switch to 1.8.7 with gemset - see issue #231 * 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) 1.4.1 (November 12, 2010)
@ -186,8 +59,6 @@
* Fix odd behavior when "cache_classes = false" (thanks mphalliday) - see issue #174 * 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) 1.4.0 (October 5, 2010)
@ -227,15 +98,11 @@
* No longer calling block in +can+ definition when checking on class - see issue #116 * 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) 1.3.4 (August 31, 2010)
* Don't stop at +cannot+ with hash conditions when checking class (thanks tamoya) - see issue #131 * 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) 1.3.3 (August 20, 2010)
@ -243,22 +110,16 @@
* Pluralize nested associations for conditions in accessible_by (thanks mlooney) - see issue #123 * 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) 1.3.2 (August 7, 2010)
* Fixing slice error when passing in custom resource name - see issue #112 * 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) 1.3.1 (August 6, 2010)
* Fixing protected sanitize_sql error - see issue #111 * 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) 1.3.0 (August 6, 2010)
@ -286,8 +147,6 @@
* Supporting deeply nested aliases - see issue #98 * 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) 1.2.0 (July 16, 2010)
@ -303,15 +162,11 @@
* Adding joins clause to accessible_by when conditions are across associations * 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) 1.1.1 (April 17, 2010)
* Fixing behavior in Rails 3 by properly initializing ResourceAuthorization * 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) 1.1.0 (April 17, 2010)
@ -335,8 +190,6 @@
* Support additional arguments to can? which get passed to the block - see issue #48 * 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) 1.0.2 (Dec 30, 2009)
@ -346,8 +199,6 @@
* Adding custom message argument to unauthorized! method (thanks tjwallace) - see issue #18 * 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) 1.0.1 (Dec 14, 2009)
@ -355,8 +206,6 @@
* Don't fetch parent of nested resource if *_id parameter is missing so it works with shallow nested routes - see issue #14 * 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) 1.0.0 (Dec 13, 2009)
@ -372,8 +221,6 @@
* BACKWARDS INCOMPATIBLE: turning load and authorize resource methods into class methods which set up the before filter so they can accept additional arguments. * 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) 0.2.1 (Nov 26, 2009)
@ -383,8 +230,6 @@
* support custom objects (usually symbols) in can definition - see issue #8 * 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) 0.2.0 (Nov 17, 2009)
@ -396,8 +241,6 @@
* BACKWARDS INCOMPATIBLE: use Ability#initialize instead of 'prepare' to set up abilities - see issue #4 * 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) 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!

View File

@ -3,8 +3,8 @@ source "http://rubygems.org"
case ENV["MODEL_ADAPTER"] case ENV["MODEL_ADAPTER"]
when nil, "active_record" when nil, "active_record"
gem "sqlite3" gem "sqlite3"
gem "activerecord", '~> 3.0.9', :require => "active_record" gem "activerecord", :require => "active_record"
gem "with_model", "~> 0.2.5" gem "with_model"
gem "meta_where" gem "meta_where"
when "data_mapper" when "data_mapper"
gem "dm-core", "~> 1.0.2" gem "dm-core", "~> 1.0.2"

View File

@ -1,4 +1,4 @@
= 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] Wiki[https://github.com/ryanb/cancan/wiki] | RDocs[http://rdoc.info/projects/ryanb/cancan] | Screencast[http://railscasts.com/episodes/192-authorization-with-cancan]
@ -31,15 +31,6 @@ User permissions are defined in an +Ability+ class. CanCan 1.5 includes a Rails
rails g cancan:ability rails g cancan:ability
In Rails 2.3, just add a new class in `app/models/ability.rb` with the folowing contents:
class Ability
include CanCan::Ability
def initialize(user)
end
end
See {Defining Abilities}[https://github.com/ryanb/cancan/wiki/defining-abilities] for details. See {Defining Abilities}[https://github.com/ryanb/cancan/wiki/defining-abilities] for details.

View File

@ -1,6 +1,6 @@
Gem::Specification.new do |s| Gem::Specification.new do |s|
s.name = "cancan" s.name = "cancan"
s.version = "1.6.10" s.version = "1.6.0"
s.author = "Ryan Bates" s.author = "Ryan Bates"
s.email = "ryan@railscasts.com" s.email = "ryan@railscasts.com"
s.homepage = "http://github.com/ryanb/cancan" s.homepage = "http://github.com/ryanb/cancan"
@ -10,8 +10,8 @@ Gem::Specification.new do |s|
s.files = Dir["{lib,spec}/**/*", "[A-Z]*", "init.rb"] - ["Gemfile.lock"] s.files = Dir["{lib,spec}/**/*", "[A-Z]*", "init.rb"] - ["Gemfile.lock"]
s.require_path = "lib" s.require_path = "lib"
s.add_development_dependency 'rspec', '~> 2.6.0' s.add_development_dependency 'rspec', '~> 2.1.0'
s.add_development_dependency 'rails', '~> 3.0.9' s.add_development_dependency 'rails', '~> 3.0.0'
s.add_development_dependency 'rr', '~> 0.10.11' # 1.0.0 has respond_to? issues: http://github.com/btakita/rr/issues/issue/43 s.add_development_dependency '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.add_development_dependency 'supermodel', '~> 0.1.4'

View File

@ -10,4 +10,4 @@ require 'cancan/model_adapters/abstract_adapter'
require 'cancan/model_adapters/default_adapter' require 'cancan/model_adapters/default_adapter'
require 'cancan/model_adapters/active_record_adapter' if defined? ActiveRecord require 'cancan/model_adapters/active_record_adapter' if defined? ActiveRecord
require 'cancan/model_adapters/data_mapper_adapter' if defined? DataMapper require 'cancan/model_adapters/data_mapper_adapter' if defined? DataMapper
require 'cancan/model_adapters/mongoid_adapter' if defined?(Mongoid) && defined?(Mongoid::Document) require 'cancan/model_adapters/mongoid_adapter' if defined? Mongoid

View File

@ -172,16 +172,10 @@ module CanCan
# This way one can use params[:action] in the controller to determine the permission. # This way one can use params[:action] in the controller to determine the permission.
def alias_action(*args) def alias_action(*args)
target = args.pop[:to] target = args.pop[:to]
validate_target(target)
aliased_actions[target] ||= [] aliased_actions[target] ||= []
aliased_actions[target] += args aliased_actions[target] += args
end 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. # Returns a hash of aliased actions. The key is the target and the value is an array of actions aliasing the key.
def aliased_actions def aliased_actions
@aliased_actions ||= default_alias_actions @aliased_actions ||= default_alias_actions
@ -207,7 +201,6 @@ module CanCan
message ||= unauthorized_message(action, subject) message ||= unauthorized_message(action, subject)
raise AccessDenied.new(message, action, subject) raise AccessDenied.new(message, action, subject)
end end
subject
end end
def unauthorized_message(action, subject) def unauthorized_message(action, subject)
@ -234,13 +227,6 @@ module CanCan
relevant_rules(action, subject).any?(&:only_raw_sql?) relevant_rules(action, subject).any?(&:only_raw_sql?)
end end
def merge(ability)
ability.send(:rules).each do |rule|
rules << rule.dup
end
self
end
private private
def unauthorized_message_keys(action, subject) def unauthorized_message_keys(action, subject)

View File

@ -94,12 +94,7 @@ module CanCan
# [:+find_by+] # [:+find_by+]
# Find using a different attribute other than id. For example. # Find using a different attribute other than id. For example.
# #
# load_resource :find_by => :permalink # will use find_by_permalink!(params[:id]) # load_resource :find_by => :permalink # will use find_by_permlink!(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+] # [:+collection+]
# Specify which actions are resource collection actions in addition to :+index+. This # Specify which actions are resource collection actions in addition to :+index+. This
@ -156,9 +151,6 @@ module CanCan
# [:+except+] # [:+except+]
# Does not apply before filter to given actions. # Does not apply before filter to given actions.
# #
# [:+singleton+]
# Pass +true+ if this is a singleton resource through a +has_one+ association.
#
# [:+parent+] # [:+parent+]
# True or false depending on if the resource is considered a parent resource. This defaults to +true+ if a resource # 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. # name is given which does not match the controller.
@ -194,7 +186,7 @@ module CanCan
skip_authorize_resource(*args) skip_authorize_resource(*args)
end end
# Skip the loading behavior of CanCan. This is useful when using +load_and_authorize_resource+ but want to # Skip both the loading behavior of CanCan. This is useful when using +load_and_authorize_resource+ but want to
# only do authorization on certain actions. You can pass :only and :except options to specify which actions to # 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. # skip the effects on. It will apply to all actions by default.
# #
@ -210,7 +202,7 @@ module CanCan
cancan_skipper[:load][name] = options cancan_skipper[:load][name] = options
end end
# Skip the authorization behavior of CanCan. This is useful when using +load_and_authorize_resource+ but want to # Skip both the authorization behavior of CanCan. This is useful when using +load_and_authorize_resource+ but want to
# only do loading on certain actions. You can pass :only and :except options to specify which actions to # 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. # skip the effects on. It will apply to all actions by default.
# #
@ -255,9 +247,9 @@ module CanCan
# #
def check_authorization(options = {}) def check_authorization(options = {})
self.after_filter(options.slice(:only, :except)) do |controller| self.after_filter(options.slice(:only, :except)) do |controller|
next if controller.instance_variable_defined?(:@_authorized) return if controller.instance_variable_defined?(:@_authorized)
next if options[:if] && !controller.send(options[:if]) return if options[:if] && !controller.send(options[:if])
next if options[:unless] && controller.send(options[:unless]) return if options[:unless] && controller.send(options[:unless])
raise AuthorizationNotPerformed, "This action failed the check_authorization because it does not authorize_resource. Add skip_authorization_check to bypass this check." raise AuthorizationNotPerformed, "This action failed the check_authorization because it does not authorize_resource. Add skip_authorization_check to bypass this check."
end end
end end
@ -294,7 +286,7 @@ module CanCan
def self.included(base) def self.included(base)
base.extend ClassMethods base.extend ClassMethods
base.helper_method :can?, :cannot?, :current_ability base.helper_method :can?, :cannot?
end end
# Raises a CanCan::AccessDenied exception if the current_ability cannot # Raises a CanCan::AccessDenied exception if the current_ability cannot
@ -390,7 +382,7 @@ module CanCan
end end
end end
if defined? ActionController::Base if defined? ActionController
ActionController::Base.class_eval do ActionController::Base.class_eval do
include CanCan::ControllerAdditions include CanCan::ControllerAdditions
end end

View File

@ -6,8 +6,8 @@ module CanCan
options = args.extract_options! options = args.extract_options!
resource_name = args.first resource_name = args.first
before_filter_method = options.delete(:prepend) ? :prepend_before_filter : :before_filter 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.send(before_filter_method, options.slice(:only, :except)) do |controller|
controller.class.cancan_resource_class.new(controller, resource_name, options.except(:only, :except, :if, :unless)).send(method) controller.class.cancan_resource_class.new(controller, resource_name, options.except(:only, :except)).send(method)
end end
end end
@ -24,10 +24,6 @@ module CanCan
def load_and_authorize_resource def load_and_authorize_resource
load_resource load_resource
authorize_resource authorize_resource
if update_actions.include?(@params[:action].to_sym)
update_resource
authorize_resource # Reauthorize the now-updated resource
end
end end
def load_resource def load_resource
@ -86,64 +82,38 @@ module CanCan
end end
def build_resource def build_resource
resource = resource_base.new(resource_params || {}) method_name = @options[:singleton] && resource_base.respond_to?("build_#{name}") ? "build_#{name}" : "new"
assign_attributes(resource) resource = resource_base.send(method_name, @params[name] || {})
end initial_attributes.each do |name, value|
resource.send("#{name}=", value)
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 end
resource resource
end end
def initial_attributes def initial_attributes
current_ability.attributes_for(@params[:action].to_sym, resource_class).delete_if do |key, value| current_ability.attributes_for(@params[:action].to_sym, resource_class).delete_if do |key, value|
resource_params && resource_params.include?(key) @params[name] && @params[name].include?(key)
end end
end end
def find_resource def find_resource
if @options[:singleton] && parent_resource.respond_to?(name) if @options[:singleton] && resource_base.respond_to?(name)
parent_resource.send(name) resource_base.send(name)
else else
if @options[:find_by] @options[:find_by] ? resource_base.send("find_by_#{@options[:find_by]}!", id_param) : resource_base.find(id_param)
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
end end
def adapter
ModelAdapters::AbstractAdapter.adapter_class(resource_class)
end
def authorization_action def authorization_action
parent? ? :show : @params[:action].to_sym parent? ? :read : @params[:action].to_sym
end end
def id_param def id_param
if @options[:id_param] @params[parent? ? :"#{name}_id" : :id]
@params[@options[:id_param]]
else
@params[parent? ? :"#{name}_id" : :id]
end.to_s
end end
def member_action? 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)) new_actions.include?(@params[:action].to_sym) || (@params[:id] && !collection_actions.include?(@params[:action].to_sym))
end end
# Returns the class used for this resource. This can be overriden by the :class option. # Returns the class used for this resource. This can be overriden by the :class option.
@ -152,7 +122,7 @@ module CanCan
def resource_class def resource_class
case @options[:class] case @options[:class]
when false then name.to_sym when false then name.to_sym
when nil then namespaced_name.to_s.camelize.constantize when nil then name.to_s.camelize.constantize
when String then @options[:class].constantize when String then @options[:class].constantize
else @options[:class] else @options[:class]
end end
@ -185,30 +155,26 @@ module CanCan
def resource_base def resource_base
if @options[:through] if @options[:through]
if parent_resource if parent_resource
@options[:singleton] ? resource_class : parent_resource.send(@options[:through_association] || name.to_s.pluralize) @options[:singleton] ? parent_resource : parent_resource.send(@options[:through_association] || name.to_s.pluralize)
elsif @options[:shallow] elsif @options[:shallow]
resource_class resource_class
else else
raise AccessDenied.new(nil, authorization_action, resource_class) # maybe this should be a record not found error instead? raise AccessDenied # maybe this should be a record not found error instead?
end end
else else
resource_class resource_class
end end
end end
def parent_name
@options[:through] && [@options[:through]].flatten.detect { |i| fetch_parent(i) }
end
# The object to load this resource through. # The object to load this resource through.
def parent_resource def parent_resource
parent_name && fetch_parent(parent_name) @options[:through] && [@options[:through]].flatten.map { |i| fetch_parent(i) }.compact.first
end end
def fetch_parent(name) def fetch_parent(name)
if @controller.instance_variable_defined? "@#{name}" if @controller.instance_variable_defined? "@#{name}"
@controller.instance_variable_get("@#{name}") @controller.instance_variable_get("@#{name}")
elsif @controller.respond_to?(name, true) elsif @controller.respond_to? name
@controller.send(name) @controller.send(name)
end end
end end
@ -221,29 +187,6 @@ module CanCan
@name || name_from_controller @name || name_from_controller
end 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 def name_from_controller
@params[:controller].sub("Controller", "").underscore.split('/').last.singularize @params[:controller].sub("Controller", "").underscore.split('/').last.singularize
end end
@ -259,15 +202,5 @@ module CanCan
def new_actions def new_actions
[:new, :create] + [@options[:new]].flatten [:new, :create] + [@options[:new]].flatten
end 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
end end

View File

@ -40,7 +40,7 @@ module CanCan
@message = message @message = message
@action = action @action = action
@subject = subject @subject = subject
@default_message = I18n.t(:"unauthorized.default", :default => "You are not authorized to access this page.") @default_message = "You are not authorized to access this page."
end end
def to_s def to_s

View File

@ -6,15 +6,14 @@ module CanCan
@controller.send :association_chain @controller.send :association_chain
@controller.instance_variable_get("@#{instance_name}") @controller.instance_variable_get("@#{instance_name}")
elsif new_actions.include? @params[:action].to_sym elsif new_actions.include? @params[:action].to_sym
resource = @controller.send :build_resource @controller.send :build_resource
assign_attributes(resource)
else else
@controller.send :resource @controller.send :resource
end end
end end
def resource_base def resource_base
@controller.send :end_of_association_chain @controller.send :collection
end end
end end
end end

View File

@ -1,5 +1,5 @@
rspec_module = defined?(RSpec::Core) ? 'RSpec' : 'Spec' # for RSpec 1 compatability RSpec = Spec unless defined? RSpec # for RSpec 1 compatability
Kernel.const_get(rspec_module)::Matchers.define :be_able_to do |*args| RSpec::Matchers.define :be_able_to do |*args|
match do |ability| match do |ability|
ability.can?(*args) ability.can?(*args)
end end

View File

@ -15,11 +15,6 @@ module CanCan
false # override in subclass false # override in subclass
end 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. # 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 # If this returns true then matches_conditions_hash? will be called. See Rule#matches_conditions_hash
def self.override_conditions_hash_matching?(subject, conditions) def self.override_conditions_hash_matching?(subject, conditions)

View File

@ -66,22 +66,11 @@ module CanCan
return conditions unless conditions.kind_of? Hash return conditions unless conditions.kind_of? Hash
conditions.inject({}) do |result_hash, (name, value)| conditions.inject({}) do |result_hash, (name, value)|
if value.kind_of? Hash if value.kind_of? Hash
value = value.dup
association_class = model_class.reflect_on_association(name).class_name.constantize association_class = model_class.reflect_on_association(name).class_name.constantize
nested = value.inject({}) do |nested,(k,v)| name = model_class.reflect_on_association(name).table_name.to_sym
if v.kind_of? Hash value = tableized_conditions(value, association_class)
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 end
result_hash[name] = value
result_hash result_hash
end end
end end
@ -98,14 +87,9 @@ module CanCan
def database_records def database_records
if override_scope if override_scope
@model_class.scoped.merge(override_scope) override_scope
elsif @model_class.respond_to?(:where) && @model_class.respond_to?(:joins) elsif @model_class.respond_to?(:where) && @model_class.respond_to?(:joins)
mergeable_conditions = @rules.select {|rule| rule.unmergeable? }.blank? @model_class.where(conditions).joins(joins)
if mergeable_conditions
@model_class.where(conditions).joins(joins)
else
@model_class.where(*(@rules.map(&:conditions))).joins(joins)
end
else else
@model_class.scoped(:conditions => conditions, :joins => joins) @model_class.scoped(:conditions => conditions, :joins => joins)
end end
@ -115,7 +99,7 @@ module CanCan
def override_scope def override_scope
conditions = @rules.map(&:conditions).compact conditions = @rules.map(&:conditions).compact
if defined?(ActiveRecord::Relation) && conditions.any? { |c| c.kind_of?(ActiveRecord::Relation) } if conditions.any? { |c| c.kind_of?(ActiveRecord::Relation) }
if conditions.size == 1 if conditions.size == 1
conditions.first conditions.first
else else
@ -156,8 +140,8 @@ module CanCan
# Takes two hashes and does a deep merge. # Takes two hashes and does a deep merge.
def merge_joins(base, add) def merge_joins(base, add)
add.each do |name, nested| add.each do |name, nested|
if base[name].is_a?(Hash) if base[name].is_a?(Hash) && !nested.empty?
merge_joins(base[name], nested) unless nested.empty? merge_joins(base[name], nested)
else else
base[name] = nested base[name] = nested
end end

View File

@ -5,30 +5,29 @@ module CanCan
model_class <= DataMapper::Resource model_class <= DataMapper::Resource
end end
def self.find(model_class, id)
model_class.get(id)
end
def self.override_conditions_hash_matching?(subject, conditions) def self.override_conditions_hash_matching?(subject, conditions)
conditions.any? { |k,v| !k.kind_of?(Symbol) } conditions.any? { |k,v| !k.kind_of?(Symbol) }
end end
def self.matches_conditions_hash?(subject, conditions) def self.matches_conditions_hash?(subject, conditions)
collection = DataMapper::Collection.new(subject.query, [ subject ]) subject.class.all(:conditions => conditions).include?(subject) # TODO don't use a database query here for performance and other instances
!!collection.first(conditions)
end end
def database_records def database_records
scope = @model_class.all(:conditions => ["0 = 1"]) scope = @model_class.all(:conditions => ["0=1"])
cans, cannots = @rules.partition { |r| r.base_behavior } conditions.each do |condition|
return scope if cans.empty? scope += @model_class.all(:conditions => condition)
# apply unions first, then differences. this mean cannot overrides can end
cans.each { |r| scope += @model_class.all(:conditions => r.conditions) }
cannots.each { |r| scope -= @model_class.all(:conditions => r.conditions) }
scope scope
end end
end # class DataMapper
end # module ModelAdapters
end # module CanCan
DataMapper::Model.append_extensions(CanCan::ModelAdditions::ClassMethods) def conditions
@rules.map(&:conditions)
end
end
end
end
DataMapper::Model.class_eval do
include CanCan::ModelAdditions::ClassMethods
end

View File

@ -6,14 +6,7 @@ module CanCan
end end
def self.override_conditions_hash_matching?(subject, conditions) def self.override_conditions_hash_matching?(subject, conditions)
conditions.any? do |k,v| conditions.any? { |k,v| !k.kind_of?(Symbol) }
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 end
def self.matches_conditions_hash?(subject, conditions) def self.matches_conditions_hash?(subject, conditions)
@ -25,21 +18,12 @@ module CanCan
def database_records def database_records
if @rules.size == 0 if @rules.size == 0
@model_class.where(:_id => {'$exists' => false, '$type' => 7}) # return no records in Mongoid @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 else
# we only need to process can rules if @rules.inject(@model_class.all) do |records, rule|
# there are no rules with empty conditions if rule.base_behavior
rules = @rules.reject { |rule| rule.conditions.empty? && rule.base_behavior } records.or(rule.conditions)
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 else
records records.excludes(rule.conditions)
end end
end end
end end

View File

@ -4,7 +4,7 @@ module CanCan
module ModelAdditions module ModelAdditions
module ClassMethods module ClassMethods
# Returns a scope which fetches only the records that the passed ability # Returns a scope which fetches only the records that the passed ability
# can perform a given action on. The action defaults to :index. This # can perform a given action on. The action defaults to :read. This
# is usually called from a controller and passed the +current_ability+. # is usually called from a controller and passed the +current_ability+.
# #
# @articles = Article.accessible_by(current_ability) # @articles = Article.accessible_by(current_ability)
@ -19,7 +19,7 @@ module CanCan
# @articles = Article.accessible_by(current_ability, :update) # @articles = Article.accessible_by(current_ability, :update)
# #
# Here only the articles which the user can update are returned. # Here only the articles which the user can update are returned.
def accessible_by(ability, action = :index) def accessible_by(ability, action = :read)
ability.model_adapter(self, action).database_records ability.model_adapter(self, action).database_records
end end
end end

View File

@ -54,11 +54,6 @@ module CanCan
@conditions == {} || @conditions.nil? @conditions == {} || @conditions.nil?
end end
def unmergeable?
@conditions.respond_to?(:keys) && @conditions.present? &&
(!@conditions.keys.first.kind_of? Symbol)
end
def associations_hash(conditions = @conditions) def associations_hash(conditions = @conditions)
hash = {} hash = {}
conditions.map do |name, value| conditions.map do |name, value|
@ -114,9 +109,9 @@ module CanCan
if attribute.kind_of? Array if attribute.kind_of? Array
attribute.any? { |element| matches_conditions_hash? element, value } attribute.any? { |element| matches_conditions_hash? element, value }
else else
!attribute.nil? && matches_conditions_hash?(attribute, value) matches_conditions_hash? attribute, value
end end
elsif !value.is_a?(String) && value.kind_of?(Enumerable) elsif value.kind_of?(Array) || value.kind_of?(Range)
value.include? attribute value.include? attribute
else else
attribute == value attribute == value
@ -128,7 +123,7 @@ module CanCan
end end
def nested_subject_matches_conditions?(subject_hash) def nested_subject_matches_conditions?(subject_hash)
parent, child = subject_hash.first parent, child = subject_hash.shift
matches_conditions_hash?(parent, @conditions[parent.class.name.downcase.to_sym] || {}) matches_conditions_hash?(parent, @conditions[parent.class.name.downcase.to_sym] || {})
end end
@ -141,7 +136,7 @@ module CanCan
end end
def model_adapter(subject) def model_adapter(subject)
CanCan::ModelAdapters::AbstractAdapter.adapter_class(subject_class?(subject) ? subject : subject.class) ModelAdapters::AbstractAdapter.adapter_class(subject_class?(subject) ? subject : subject.class)
end end
end end
end end

View File

@ -11,22 +11,18 @@ class Ability
# can :read, :all # can :read, :all
# end # end
# #
# The first argument to `can` is the action you are giving the user # The first argument to `can` is the action you are giving the user permission to do.
# permission to do. # If you pass :manage it will apply to every action. Other common actions here are
# If you pass :manage it will apply to every action. Other common actions # :read, :create, :update and :destroy.
# here are :read, :create, :update and :destroy.
# #
# The second argument is the resource the user can perform the action on. # The second argument is the resource the user can perform the action on. If you pass
# If you pass :all it will apply to every resource. Otherwise pass a Ruby # :all it will apply to every resource. Otherwise pass a Ruby class of the resource.
# class of the resource.
# #
# The third argument is an optional hash of conditions to further filter the # The third argument is an optional hash of conditions to further filter the objects.
# objects.
# For example, here the user can only update published articles. # For example, here the user can only update published articles.
# #
# can :update, Article, :published => true # can :update, Article, :published => true
# #
# See the wiki for details: # See the wiki for details: https://github.com/ryanb/cancan/wiki/Defining-Abilities
# https://github.com/ryanb/cancan/wiki/Defining-Abilities
end end
end end

View File

@ -87,10 +87,6 @@ describe CanCan::Ability do
@ability.can?(:increment, 123).should be_true @ability.can?(:increment, 123).should be_true
end 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 it "should always call block with arguments when passing no arguments to can" do
@ability.can do |action, object_class, object| @ability.can do |action, object_class, object|
action.should == :foo action.should == :foo
@ -254,27 +250,6 @@ describe CanCan::Ability do
@ability.can?(:read, 4..6).should be_false @ability.can?(:read, 4..6).should be_false
end 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 it "should not stop at cannot definition when comparing class" do
@ability.can :read, Range @ability.can :read, Range
@ability.cannot :read, Range, :begin => 1 @ability.cannot :read, Range, :begin => 1
@ -316,14 +291,6 @@ describe CanCan::Ability do
@ability.can?(:read, 123 => Range).should be_true @ability.can?(:read, 123 => Range).should be_true
end 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 it "should allow to check ability on Hash-like object" do
class Container < Hash; end class Container < Hash; end
@ability.can :read, Container @ability.can :read, Container
@ -350,11 +317,9 @@ describe CanCan::Ability do
end end
end end
it "should not raise access denied exception if ability is authorized to perform an action and return subject" do it "should not raise access denied exception if ability is authorized to perform an action" do
@ability.can :read, :foo @ability.can :read, :foo
lambda { lambda { @ability.authorize!(:read, :foo) }.should_not raise_error
@ability.authorize!(:read, :foo).should == :foo
}.should_not raise_error
end end
it "should know when block is used in conditions" do it "should know when block is used in conditions" do
@ -442,17 +407,4 @@ describe CanCan::Ability do
@ability.unauthorized_message(:edit, 1..3).should == "edit range" @ability.unauthorized_message(:edit, 1..3).should == "edit range"
end end
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 end

View File

@ -6,7 +6,7 @@ describe CanCan::ControllerAdditions do
@controller = @controller_class.new @controller = @controller_class.new
stub(@controller).params { {} } stub(@controller).params { {} }
stub(@controller).current_user { :current_user } 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) @controller_class.send(:include, CanCan::ControllerAdditions)
end end
@ -49,14 +49,14 @@ describe CanCan::ControllerAdditions do
it "authorize_resource should setup a before filter which passes call to ControllerResource" do 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 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) } mock(@controller_class).before_filter(:except => :show) { |options, block| block.call(@controller) }
@controller_class.authorize_resource :foo => :bar, :except => :show, :if => true @controller_class.authorize_resource :foo => :bar, :except => :show
end end
it "load_resource should setup a before filter which passes call to ControllerResource" do 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 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) } mock(@controller_class).before_filter(:only => [:show, :index]) { |options, block| block.call(@controller) }
@controller_class.load_resource :foo => :bar, :only => [:show, :index], :unless => false @controller_class.load_resource :foo => :bar, :only => [:show, :index]
end end
it "skip_authorization_check should set up a before filter which sets @_authorized to true" do it "skip_authorization_check should set up a before filter which sets @_authorized to true" do

View File

@ -20,7 +20,7 @@ describe CanCan::ControllerResource do
end end
it "should not load resource into an instance variable if already set" do it "should not load resource into an instance variable if already set" do
@params.merge!(:action => "show", :id => "123") @params.merge!(:action => "show", :id => 123)
@controller.instance_variable_set(:@project, :some_project) @controller.instance_variable_set(:@project, :some_project)
resource = CanCan::ControllerResource.new(@controller) resource = CanCan::ControllerResource.new(@controller)
resource.load_resource resource.load_resource
@ -35,30 +35,6 @@ describe CanCan::ControllerResource do
@controller.instance_variable_get(:@project).should == project @controller.instance_variable_get(:@project).should == project
end 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 it "should properly load resource for namespaced controller when using '::' for namespace" do
project = Project.create! project = Project.create!
@params.merge!(:controller => "Admin::ProjectsController", :action => "show", :id => project.id) @params.merge!(:controller => "Admin::ProjectsController", :action => "show", :id => project.id)
@ -67,16 +43,6 @@ describe CanCan::ControllerResource do
@controller.instance_variable_get(:@project).should == project @controller.instance_variable_get(:@project).should == project
end 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 it "should build a new resource with hash if params[:id] is not specified" do
@params.merge!(:action => "create", :project => {:name => "foobar"}) @params.merge!(:action => "create", :project => {:name => "foobar"})
resource = CanCan::ControllerResource.new(@controller) resource = CanCan::ControllerResource.new(@controller)
@ -84,20 +50,6 @@ describe CanCan::ControllerResource do
@controller.instance_variable_get(:@project).name.should == "foobar" @controller.instance_variable_get(:@project).name.should == "foobar"
end 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 it "should build a new resource with attributes from current ability" do
@params.merge!(:action => "new") @params.merge!(:action => "new")
@ability.can(:create, Project, :name => "from conditions") @ability.can(:create, Project, :name => "from conditions")
@ -152,13 +104,13 @@ describe CanCan::ControllerResource do
it "should authorize parent resource in collection action" do it "should authorize parent resource in collection action" do
@params[:action] = "index" @params[:action] = "index"
@controller.instance_variable_set(:@category, :some_category) @controller.instance_variable_set(:@category, :some_category)
stub(@controller).authorize!(:show, :some_category) { raise CanCan::AccessDenied } stub(@controller).authorize!(:read, :some_category) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller, :category, :parent => true) resource = CanCan::ControllerResource.new(@controller, :category, :parent => true)
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied) lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
end end
it "should perform authorization using controller action and loaded model" do it "should perform authorization using controller action and loaded model" do
@params.merge!(:action => "show", :id => "123") @params.merge!(:action => "show", :id => 123)
@controller.instance_variable_set(:@project, :some_project) @controller.instance_variable_set(:@project, :some_project)
stub(@controller).authorize!(:show, :some_project) { raise CanCan::AccessDenied } stub(@controller).authorize!(:show, :some_project) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller) resource = CanCan::ControllerResource.new(@controller)
@ -166,14 +118,14 @@ describe CanCan::ControllerResource do
end end
it "should perform authorization using controller action and non loaded model" do it "should perform authorization using controller action and non loaded model" do
@params.merge!(:action => "show", :id => "123") @params.merge!(:action => "show", :id => 123)
stub(@controller).authorize!(:show, Project) { raise CanCan::AccessDenied } stub(@controller).authorize!(:show, Project) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller) resource = CanCan::ControllerResource.new(@controller)
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied) lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
end end
it "should call load_resource and authorize_resource for load_and_authorize_resource" do it "should call load_resource and authorize_resource for load_and_authorize_resource" do
@params.merge!(:action => "show", :id => "123") @params.merge!(:action => "show", :id => 123)
resource = CanCan::ControllerResource.new(@controller) resource = CanCan::ControllerResource.new(@controller)
mock(resource).load_resource mock(resource).load_resource
mock(resource).authorize_resource mock(resource).authorize_resource
@ -181,7 +133,7 @@ describe CanCan::ControllerResource do
end end
it "should not build a single resource when on custom collection action even with id" do it "should not build a single resource when on custom collection action even with id" do
@params.merge!(:action => "sort", :id => "123") @params.merge!(:action => "sort", :id => 123)
resource = CanCan::ControllerResource.new(@controller, :collection => [:sort, :list]) resource = CanCan::ControllerResource.new(@controller, :collection => [:sort, :list])
resource.load_resource resource.load_resource
@controller.instance_variable_get(:@project).should be_nil @controller.instance_variable_get(:@project).should be_nil
@ -197,7 +149,7 @@ describe CanCan::ControllerResource do
end end
it "should build a resource when on custom new action even when params[:id] exists" do it "should build a resource when on custom new action even when params[:id] exists" do
@params.merge!(:action => "build", :id => "123") @params.merge!(:action => "build", :id => 123)
stub(Project).new { :some_project } stub(Project).new { :some_project }
resource = CanCan::ControllerResource.new(@controller, :new => :build) resource = CanCan::ControllerResource.new(@controller, :new => :build)
resource.load_resource resource.load_resource
@ -231,47 +183,39 @@ describe CanCan::ControllerResource do
resource.should_not be_parent resource.should_not be_parent
end 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 it "should load parent resource through proper id parameter" do
project = Project.create! project = Project.create!
@params.merge!(:controller => "categories", :action => "index", :project_id => project.id) @params.merge!(:action => "index", :project_id => project.id)
resource = CanCan::ControllerResource.new(@controller, :project) resource = CanCan::ControllerResource.new(@controller, :project, :parent => true)
resource.load_resource resource.load_resource
@controller.instance_variable_get(:@project).should == project @controller.instance_variable_get(:@project).should == project
end end
it "should load resource through the association of another parent resource using instance variable" do it "should load resource through the association of another parent resource using instance variable" do
@params.merge!(:action => "show", :id => "123") @params.merge!(:action => "show", :id => 123)
category = Object.new category = Object.new
@controller.instance_variable_set(:@category, category) @controller.instance_variable_set(:@category, category)
stub(category).projects.stub!.find("123") { :some_project } stub(category).projects.stub!.find(123) { :some_project }
resource = CanCan::ControllerResource.new(@controller, :through => :category) resource = CanCan::ControllerResource.new(@controller, :through => :category)
resource.load_resource resource.load_resource
@controller.instance_variable_get(:@project).should == :some_project @controller.instance_variable_get(:@project).should == :some_project
end end
it "should load resource through the custom association name" do it "should load resource through the custom association name" do
@params.merge!(:action => "show", :id => "123") @params.merge!(:action => "show", :id => 123)
category = Object.new category = Object.new
@controller.instance_variable_set(:@category, category) @controller.instance_variable_set(:@category, category)
stub(category).custom_projects.stub!.find("123") { :some_project } stub(category).custom_projects.stub!.find(123) { :some_project }
resource = CanCan::ControllerResource.new(@controller, :through => :category, :through_association => :custom_projects) resource = CanCan::ControllerResource.new(@controller, :through => :category, :through_association => :custom_projects)
resource.load_resource resource.load_resource
@controller.instance_variable_get(:@project).should == :some_project @controller.instance_variable_get(:@project).should == :some_project
end end
it "should load resource through the association of another parent resource using method" do it "should load resource through the association of another parent resource using method" do
@params.merge!(:action => "show", :id => "123") @params.merge!(:action => "show", :id => 123)
category = Object.new category = Object.new
stub(@controller).category { category } stub(@controller).category { category }
stub(category).projects.stub!.find("123") { :some_project } stub(category).projects.stub!.find(123) { :some_project }
resource = CanCan::ControllerResource.new(@controller, :through => :category) resource = CanCan::ControllerResource.new(@controller, :through => :category)
resource.load_resource resource.load_resource
@controller.instance_variable_get(:@project).should == :some_project @controller.instance_variable_get(:@project).should == :some_project
@ -291,10 +235,7 @@ describe CanCan::ControllerResource do
resource = CanCan::ControllerResource.new(@controller, :through => :category) resource = CanCan::ControllerResource.new(@controller, :through => :category)
lambda { lambda {
resource.load_resource resource.load_resource
}.should raise_error(CanCan::AccessDenied) { |exception| }.should raise_error(CanCan::AccessDenied)
exception.action.should == :show
exception.subject.should == Project
}
@controller.instance_variable_get(:@project).should be_nil @controller.instance_variable_get(:@project).should be_nil
end end
@ -308,17 +249,17 @@ describe CanCan::ControllerResource do
end end
it "should load through first matching if multiple are given" do it "should load through first matching if multiple are given" do
@params.merge!(:action => "show", :id => "123") @params.merge!(:action => "show", :id => 123)
category = Object.new category = Object.new
@controller.instance_variable_set(:@category, category) @controller.instance_variable_set(:@category, category)
stub(category).projects.stub!.find("123") { :some_project } stub(category).projects.stub!.find(123) { :some_project }
resource = CanCan::ControllerResource.new(@controller, :through => [:category, :user]) resource = CanCan::ControllerResource.new(@controller, :through => [:category, :user])
resource.load_resource resource.load_resource
@controller.instance_variable_get(:@project).should == :some_project @controller.instance_variable_get(:@project).should == :some_project
end end
it "should find record through has_one association with :singleton option without id param" do it "should find record through has_one association with :singleton option" do
@params.merge!(:action => "show", :id => nil) @params.merge!(:action => "show", :id => 123)
category = Object.new category = Object.new
@controller.instance_variable_set(:@category, category) @controller.instance_variable_set(:@category, category)
stub(category).project { :some_project } stub(category).project { :some_project }
@ -327,14 +268,14 @@ describe CanCan::ControllerResource do
@controller.instance_variable_get(:@project).should == :some_project @controller.instance_variable_get(:@project).should == :some_project
end 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 it "should build record through has_one association with :singleton option" do
@params.merge!(:action => "create", :project => {:name => "foobar"}) @params.merge!(:action => "create", :project => {:name => "foobar"})
category = Category.new category = Object.new
@controller.instance_variable_set(:@category, category) @controller.instance_variable_set(:@category, category)
stub(category).build_project { |attributes| Project.new(attributes) }
resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true) resource = CanCan::ControllerResource.new(@controller, :through => :category, :singleton => true)
resource.load_resource resource.load_resource
@controller.instance_variable_get(:@project).name.should == "foobar" @controller.instance_variable_get(:@project).name.should == "foobar"
@controller.instance_variable_get(:@project).category.should == category
end end
it "should find record through has_one association with :singleton and :shallow options" do it "should find record through has_one association with :singleton and :shallow options" do
@ -352,10 +293,10 @@ describe CanCan::ControllerResource do
@controller.instance_variable_get(:@project).name.should == "foobar" @controller.instance_variable_get(:@project).name.should == "foobar"
end end
it "should only authorize :show action on parent resource" do it "should only authorize :read action on parent resource" do
project = Project.create! project = Project.create!
@params.merge!(:action => "new", :project_id => project.id) @params.merge!(:action => "new", :project_id => project.id)
stub(@controller).authorize!(:show, project) { raise CanCan::AccessDenied } stub(@controller).authorize!(:read, project) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller, :project, :parent => true) resource = CanCan::ControllerResource.new(@controller, :project, :parent => true)
lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied) lambda { resource.load_and_authorize_resource }.should raise_error(CanCan::AccessDenied)
end end
@ -368,16 +309,8 @@ describe CanCan::ControllerResource do
@controller.instance_variable_get(:@project).should == project @controller.instance_variable_get(:@project).should == project
end 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 it "should authorize based on resource name if class is false" do
@params.merge!(:action => "show", :id => "123") @params.merge!(:action => "show", :id => 123)
stub(@controller).authorize!(:show, :project) { raise CanCan::AccessDenied } stub(@controller).authorize!(:show, :project) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(@controller, :class => false) resource = CanCan::ControllerResource.new(@controller, :class => false)
lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied) lambda { resource.authorize_resource }.should raise_error(CanCan::AccessDenied)
@ -392,21 +325,6 @@ describe CanCan::ControllerResource do
@controller.instance_variable_get(:@custom_project).should == project @controller.instance_variable_get(:@custom_project).should == project
end 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 it "should load resource using custom find_by attribute" do
project = Project.create!(:name => "foo") project = Project.create!(:name => "foo")
@params.merge!(:action => "show", :id => "foo") @params.merge!(:action => "show", :id => "foo")
@ -415,14 +333,6 @@ describe CanCan::ControllerResource do
@controller.instance_variable_get(:@project).should == project @controller.instance_variable_get(:@project).should == project
end 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 it "should raise ImplementationRemoved when adding :name option" do
lambda { lambda {
CanCan::ControllerResource.new(@controller, :name => :foo) CanCan::ControllerResource.new(@controller, :name => :foo)

View File

@ -32,27 +32,4 @@ describe CanCan::AccessDenied do
@exception.message.should == "Access denied!" @exception.message.should == "Access denied!"
end end
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 end

View File

@ -32,29 +32,11 @@ describe CanCan::InheritedResource do
@controller.instance_variable_get(:@project).should == :project_resource @controller.instance_variable_get(:@project).should == :project_resource
end end
it "index should load through @controller.end_of_association_chain" do it "index should load through @controller.collection" do
@params[:action] = "index" @params[:action] = "index"
stub(Project).accessible_by(@ability, :index) { :projects } stub(Project).accessible_by(@ability, :index) { :projects }
stub(@controller).end_of_association_chain { Project } stub(@controller).collection { Project }
CanCan::InheritedResource.new(@controller).load_resource CanCan::InheritedResource.new(@controller).load_resource
@controller.instance_variable_get(:@projects).should == :projects @controller.instance_variable_get(:@projects).should == :projects
end 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 end

View File

@ -1,6 +1,10 @@
if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record" if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
require "spec_helper" require "spec_helper"
RSpec.configure do |config|
config.extend WithModel
end
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:") ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
describe CanCan::ModelAdapters::ActiveRecordAdapter do describe CanCan::ModelAdapters::ActiveRecordAdapter do
@ -20,12 +24,10 @@ if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
t.boolean "secret" t.boolean "secret"
t.integer "priority" t.integer "priority"
t.integer "category_id" t.integer "category_id"
t.integer "user_id"
end end
model do model do
belongs_to :category belongs_to :category
has_many :comments has_many :comments
belongs_to :user
end end
end end
@ -39,15 +41,6 @@ if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
end end
end end
with_model :user do
table do |t|
end
model do
has_many :articles
end
end
before(:each) do before(:each) do
Article.delete_all Article.delete_all
Comment.delete_all Comment.delete_all
@ -63,11 +56,6 @@ if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
CanCan::ModelAdapters::AbstractAdapter.adapter_class(Article).should == CanCan::ModelAdapters::ActiveRecordAdapter CanCan::ModelAdapters::AbstractAdapter.adapter_class(Article).should == CanCan::ModelAdapters::ActiveRecordAdapter
end 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 it "should not fetch any records when no abilities are defined" do
Article.create! Article.create!
Article.accessible_by(@ability).should be_empty Article.accessible_by(@ability).should be_empty
@ -137,15 +125,6 @@ if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
Article.accessible_by(@ability).should == [article1] Article.accessible_by(@ability).should == [article1]
end 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 it "should raise an exception when trying to merge scope with other conditions" do
@ability.can :read, Article, :published => true @ability.can :read, Article, :published => true
@ability.can :read, Article, Article.where(:secret => true) @ability.can :read, Article, Article.where(:secret => true)
@ -207,16 +186,6 @@ if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
@ability.model_adapter(Article, :read).conditions.should == "'t'='t'" @ability.model_adapter(Article, :read).conditions.should == "'t'='t'"
end 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 it "should not forget conditions when calling with SQL string" do
@ability.can :read, Article, :published => true @ability.can :read, Article, :published => true
@ability.can :read, Article, ['secret=?', false] @ability.can :read, Article, ['secret=?', false]
@ -248,21 +217,6 @@ if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
@ability.model_adapter(Article, :read).joins.should == [:project] @ability.model_adapter(Article, :read).joins.should == [:project]
end 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 it "should restrict articles given a MetaWhere condition" do
@ability.can :read, Article, :priority.lt => 2 @ability.can :read, Article, :priority.lt => 2
article1 = Article.create!(:priority => 1) article1 = Article.create!(:priority => 1)
@ -272,16 +226,6 @@ if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
@ability.should_not be_able_to(:read, article2) @ability.should_not be_able_to(:read, article2)
end 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 it "should match any MetaWhere condition" do
adapter = CanCan::ModelAdapters::ActiveRecordAdapter adapter = CanCan::ModelAdapters::ActiveRecordAdapter
article1 = Article.new(:priority => 1, :name => "Hello World") article1 = Article.new(:priority => 1, :name => "Hello World")
@ -312,9 +256,8 @@ if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
adapter.matches_condition?(article1, :name.like, "%helo%").should be_false 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").should be_false
adapter.matches_condition?(article1, :name.like, "hello.world").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, "%helo%").should be_true adapter.matches_condition?(article1, :name.nlike, "%ello worl%").should be_false
# adapter.matches_condition?(article1, :name.nlike, "%ello worl%").should be_false
end end
end end
end end

View File

@ -36,11 +36,6 @@ if ENV["MODEL_ADAPTER"] == "data_mapper"
CanCan::ModelAdapters::AbstractAdapter.adapter_class(Article).should == CanCan::ModelAdapters::DataMapperAdapter CanCan::ModelAdapters::AbstractAdapter.adapter_class(Article).should == CanCan::ModelAdapters::DataMapperAdapter
end 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 it "should not fetch any records when no abilities are defined" do
Article.create Article.create
Article.accessible_by(@ability).should be_empty Article.accessible_by(@ability).should be_empty
@ -70,6 +65,7 @@ if ENV["MODEL_ADAPTER"] == "data_mapper"
end end
it "should fetch only the articles that are published and not secret" do it "should fetch only the articles that are published and not secret" do
pending "the `cannot` may require some custom SQL, maybe abstract out from Active Record adapter"
@ability.can :read, Article, :published => true @ability.can :read, Article, :published => true
@ability.cannot :read, Article, :secret => true @ability.cannot :read, Article, :secret => true
article1 = Article.create(:published => true, :secret => false) article1 = Article.create(:published => true, :secret => false)

View File

@ -36,26 +36,12 @@ if ENV["MODEL_ADAPTER"] == "mongoid"
CanCan::ModelAdapters::AbstractAdapter.adapter_class(MongoidProject).should == CanCan::ModelAdapters::MongoidAdapter CanCan::ModelAdapters::AbstractAdapter.adapter_class(MongoidProject).should == CanCan::ModelAdapters::MongoidAdapter
end 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 it "should compare properties on mongoid documents with the conditions hash" do
model = MongoidProject.new model = MongoidProject.new
@ability.can :read, MongoidProject, :id => model.id @ability.can :read, MongoidProject, :id => model.id
@ability.should be_able_to(:read, model) @ability.should be_able_to(:read, model)
end 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 it "should return [] when no ability is defined so no records are found" do
MongoidProject.create(:title => 'Sir') MongoidProject.create(:title => 'Sir')
MongoidProject.create(:title => 'Lord') MongoidProject.create(:title => 'Lord')
@ -73,26 +59,6 @@ if ENV["MODEL_ADAPTER"] == "mongoid"
MongoidProject.accessible_by(@ability, :read).entries.should == [sir] MongoidProject.accessible_by(@ability, :read).entries.should == [sir]
end 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 it "should return everything when the defined ability is manage all" do
@ability.can :manage, :all @ability.can :manage, :all
sir = MongoidProject.create(:title => 'Sir') sir = MongoidProject.create(:title => 'Sir')
@ -102,14 +68,6 @@ if ENV["MODEL_ADAPTER"] == "mongoid"
MongoidProject.accessible_by(@ability, :read).entries.should == [sir, lord, dude] MongoidProject.accessible_by(@ability, :read).entries.should == [sir, lord, dude]
end 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 describe "Mongoid::Criteria where clause Symbol extensions using MongoDB expressions" do
it "should handle :field.in" do it "should handle :field.in" do

View File

@ -1,5 +1,4 @@
require "spec_helper" require "spec_helper"
require "ostruct" # for OpenStruct below
# Most of Rule functionality is tested in Ability specs # Most of Rule functionality is tested in Ability specs
describe CanCan::Rule do describe CanCan::Rule do
@ -37,16 +36,4 @@ describe CanCan::Rule do
rule = CanCan::Rule.new(true, :read, Integer, nil, nil) rule = CanCan::Rule.new(true, :read, Integer, nil, nil)
rule.associations_hash.should == {} rule.associations_hash.should == {}
end 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 end

View File

@ -9,27 +9,11 @@ require 'matchers'
require 'cancan/matchers' require 'cancan/matchers'
RSpec.configure do |config| 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
config.mock_with :rr config.mock_with :rr
config.before(:each) do config.before(:each) do
Project.delete_all Project.delete_all
Category.delete_all Category.delete_all
end 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 end
class Ability class Ability
@ -43,30 +27,6 @@ class Category < SuperModel::Base
has_many :projects has_many :projects
end 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 class Project < SuperModel::Base
belongs_to :category 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