Compare commits
361 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6bf4c8d12 | ||
|
|
68ea78b6e9 | ||
|
|
1f7e4c8b6b | ||
|
|
f1cebde51a | ||
|
|
9550154b09 | ||
|
|
17043ca61c | ||
|
|
aed9f26e56 | ||
|
|
6c1828acb6 | ||
|
|
6886aecb9a | ||
|
|
de000fdec7 | ||
|
|
1e89b31bad | ||
|
|
5f1be25419 | ||
|
|
6d7bce78fc | ||
|
|
a0200166cc | ||
|
|
112a995327 | ||
|
|
944804183e | ||
|
|
2b89dbbdfa | ||
|
|
aff8ca60e4 | ||
|
|
33e33c584e | ||
|
|
a1254ca1c6 | ||
|
|
88aba4664a | ||
|
|
b965f5bab4 | ||
|
|
c2c0b86c3a | ||
|
|
d5baed6281 | ||
|
|
76d465ae13 | ||
|
|
7bf683d8f4 | ||
|
|
da663aaed1 | ||
|
|
354e34b8ab | ||
|
|
245b83f6b4 | ||
|
|
78cbcf1db9 | ||
|
|
80a8c39a93 | ||
|
|
b3f9ffe93b | ||
|
|
c27ead5b9f | ||
|
|
0c21831b4d | ||
|
|
b347c7b78c | ||
|
|
1cdd7b3c18 | ||
|
|
7f4f469e58 | ||
|
|
ccd24ab30f | ||
|
|
4986de8b3e | ||
|
|
14e1f5cad4 | ||
|
|
8e46ccad8c | ||
|
|
0e8c7ca01f | ||
|
|
48ed6f9353 | ||
|
|
0bbe2e1802 | ||
|
|
10cbfbb923 | ||
|
|
a8a85f13a3 | ||
|
|
c1f7181336 | ||
|
|
70515de8c1 | ||
|
|
b73bd062a8 | ||
|
|
d1176245e6 | ||
|
|
78e1a17258 | ||
|
|
6e8bc851be | ||
|
|
65bbf0e354 | ||
|
|
167d3832fc | ||
|
|
88cd11ba02 | ||
|
|
1ff1b70de4 | ||
|
|
8c72ab40a4 | ||
|
|
ec36137aa6 | ||
|
|
b37f2d083e | ||
|
|
aed37cda03 | ||
|
|
51702e0f7b | ||
|
|
f166b5945a | ||
|
|
ba01349eb0 | ||
|
|
37a42e3666 | ||
|
|
83e2dcebd0 | ||
|
|
baadcb923b | ||
|
|
e65f9bd4fd | ||
|
|
f18f53c9ce | ||
|
|
98312940e4 | ||
|
|
7797b37c7e | ||
|
|
80ceaf8e17 | ||
|
|
9eebeb2155 | ||
|
|
67a3038628 | ||
|
|
26b40f2b49 | ||
|
|
98326394f0 | ||
|
|
b3fc5add34 | ||
|
|
c94de4ab18 | ||
|
|
6de9e4675a | ||
|
|
1fb2c0160c | ||
|
|
aa83fee7a4 | ||
|
|
eafd6cfcde | ||
|
|
67c93619c1 | ||
|
|
610d7e3ec4 | ||
|
|
092b510a2f | ||
|
|
2160183e86 | ||
|
|
cfb801ed8d | ||
|
|
0edd310c41 | ||
|
|
86063e4846 | ||
|
|
0442634d5a | ||
|
|
6c1d685f2c | ||
|
|
6ef2c44f57 | ||
|
|
5ab7dea2f0 | ||
|
|
916f97fbf3 | ||
|
|
2be3f98e11 | ||
|
|
0343f8f0b5 | ||
|
|
987dce0dc2 | ||
|
|
e0492f5d75 | ||
|
|
0fc67e4d56 | ||
|
|
d24ef454e0 | ||
|
|
e561532bab | ||
|
|
1ab4e2d48c | ||
|
|
7937a282a3 | ||
|
|
d35419fa4c | ||
|
|
6c497b8dd9 | ||
|
|
3b33b36de9 | ||
|
|
600a3e16a5 | ||
|
|
ccd7a94d40 | ||
|
|
8f815c422a | ||
|
|
1c3e61725f | ||
|
|
71f60bc4ac | ||
|
|
596ad235a9 | ||
|
|
b8ff2dbc6a | ||
|
|
613ab1c1ab | ||
|
|
c031f82dd2 | ||
|
|
f6c2054f7e | ||
|
|
a29e31606b | ||
|
|
e24d5d146b | ||
|
|
6a01427317 | ||
|
|
843fe89c63 | ||
|
|
74c9d582b2 | ||
|
|
4e4c5a9a7f | ||
|
|
dde88c92b7 | ||
|
|
cb9777be5f | ||
|
|
5a64d94d09 | ||
|
|
0882450232 | ||
|
|
ad62d60b20 | ||
|
|
ff13a82dda | ||
|
|
16bdb8d42e | ||
|
|
d6851debd4 | ||
|
|
6d39b0ae07 | ||
|
|
a6af47d213 | ||
|
|
17c52a7983 | ||
|
|
18c1007d3f | ||
|
|
63865cc7d8 | ||
|
|
2b6204117f | ||
|
|
b1424dfa49 | ||
|
|
6aaab9e440 | ||
|
|
a10243a569 | ||
|
|
81f00f9024 | ||
|
|
7bcfd3d295 | ||
|
|
e96cf5bea4 | ||
|
|
c6f9abb6ab | ||
|
|
e5b76210e4 | ||
|
|
baa1dacc21 | ||
|
|
f41b39406c | ||
|
|
27eba72e4b | ||
|
|
5d68caefd0 | ||
|
|
35fbee578f | ||
|
|
cf2896f011 | ||
|
|
bcac159b3e | ||
|
|
fb8e9bde57 | ||
|
|
89e40987d8 | ||
|
|
1ac8099f7a | ||
|
|
346ca2c74e | ||
|
|
242e912519 | ||
|
|
488cc2dfdd | ||
|
|
0f3753491d | ||
|
|
85efbdb8d0 | ||
|
|
a03d35272b | ||
|
|
7ee942c334 | ||
|
|
3a825ed0d1 | ||
|
|
98ed39264e | ||
|
|
5d97cfb236 | ||
|
|
7688025404 | ||
|
|
3efa069349 | ||
|
|
b0c1646fee | ||
|
|
3f6cecbfcf | ||
|
|
fdd5ad022d | ||
|
|
3639ca90eb | ||
|
|
efa3ff1c0f | ||
|
|
9bee4a8d4b | ||
|
|
eb2826f135 | ||
|
|
a49269175e | ||
|
|
0de43c445b | ||
|
|
f9b181af05 | ||
|
|
80f1ab20fb | ||
|
|
37102fe6f8 | ||
|
|
ba999970b1 | ||
|
|
951d70e057 | ||
|
|
3a07d62782 | ||
|
|
2c2fa306cc | ||
|
|
28a9a0ac07 | ||
|
|
bcf2756ad2 | ||
|
|
c53ed1e497 | ||
|
|
07088a0cdc | ||
|
|
ff5aaf543b | ||
|
|
52435e97d9 | ||
|
|
e3eab13b86 | ||
|
|
79995e4309 | ||
|
|
8722fbc7a5 | ||
|
|
3901cbe499 | ||
|
|
471d54ce01 | ||
|
|
f23bbe04ef | ||
|
|
f1ea21b2a6 | ||
|
|
b2028c8aa7 | ||
|
|
929579f03b | ||
|
|
f9ad4858f5 | ||
|
|
5c4c179c5a | ||
|
|
78cbea5733 | ||
|
|
cff922915e | ||
|
|
2012311c40 | ||
|
|
55c8a5045b | ||
|
|
344832d199 | ||
|
|
52b33589dc | ||
|
|
04522c9bc6 | ||
|
|
120eafeabd | ||
|
|
e49190fc21 | ||
|
|
39bffe91ab | ||
|
|
3885f469d5 | ||
|
|
e2910a74ee | ||
|
|
57327119a8 | ||
|
|
71ceb83ded | ||
|
|
045a850565 | ||
|
|
9a14c706d2 | ||
|
|
12b0bff0b6 | ||
|
|
bc9ecb226d | ||
|
|
15ca8ade3b | ||
|
|
cef6c21232 | ||
|
|
685e926d96 | ||
|
|
bd9480cb51 | ||
|
|
f759ab7e54 | ||
|
|
6ccb4dd684 | ||
|
|
70b5f9a613 | ||
|
|
f9f71d679d | ||
|
|
fc867c9c0d | ||
|
|
ec616ae75b | ||
|
|
f7a494dc51 | ||
|
|
f5dce44697 | ||
|
|
e8d298c223 | ||
|
|
8628aa0038 | ||
|
|
bbb02f7c8f | ||
|
|
cc30e838c0 | ||
|
|
af9e77a79e | ||
|
|
4c5ba09f4c | ||
|
|
f8760b7149 | ||
|
|
2dc2a573f9 | ||
|
|
f9a498d2fc | ||
|
|
5183113d2d | ||
|
|
d315e22e7a | ||
|
|
2d31cbdf60 | ||
|
|
e14e1edec2 | ||
|
|
ebb8e1bf8b | ||
|
|
4339ac6546 | ||
|
|
5e1e6e182b | ||
|
|
9b8e84944c | ||
|
|
37c149182c | ||
|
|
a6959c0ab2 | ||
|
|
2ee6908a2a | ||
|
|
84c590e8c7 | ||
|
|
5ebca1f9bf | ||
|
|
f6aaa581ef | ||
|
|
872e4cfba8 | ||
|
|
787511a208 | ||
|
|
92995d791e | ||
|
|
ebf77ed647 | ||
|
|
9a7c427373 | ||
|
|
cf263c105d | ||
|
|
79180de372 | ||
|
|
dbcd93e095 | ||
|
|
d256aeb26e | ||
|
|
25bf479f48 | ||
|
|
ab82dcbc8f | ||
|
|
be74df0548 | ||
|
|
f901c367fc | ||
|
|
67cd83dd96 | ||
|
|
6c3e87eea9 | ||
|
|
fa766e71ed | ||
|
|
b0cec5251c | ||
|
|
18b45d5cfc | ||
|
|
8f49f28713 | ||
|
|
12037d7f43 | ||
|
|
1f81b8dd1e | ||
|
|
3391c5a0d7 | ||
|
|
c11ffb6fd1 | ||
|
|
264e2d2b68 | ||
|
|
ebef3cc745 | ||
|
|
cef55c95e7 | ||
|
|
7e0e72276e | ||
|
|
ff9a91705b | ||
|
|
a0f73fe0f7 | ||
|
|
e2c341b8d3 | ||
|
|
f236b1b5a4 | ||
|
|
0b270f2d0f | ||
|
|
961df90ecd | ||
|
|
4eee637270 | ||
|
|
a5ff826e40 | ||
|
|
9d915457af | ||
|
|
158c908d3b | ||
|
|
bf9b8ad1a6 | ||
|
|
1af6c6f395 | ||
|
|
7c5243321f | ||
|
|
721939babd | ||
|
|
a744377ac9 | ||
|
|
1be5bf7a57 | ||
|
|
c88cb8f459 | ||
|
|
737f8acff5 | ||
|
|
a5f838a964 | ||
|
|
66314a89f8 | ||
|
|
b1fb179aaf | ||
|
|
6105edc6a7 | ||
|
|
04b523eea4 | ||
|
|
5a353c1cba | ||
|
|
4fe44af45d | ||
|
|
a10a38c82f | ||
|
|
caed4fcee5 | ||
|
|
e893e12260 | ||
|
|
3d7742ea43 | ||
|
|
a566ea0f4f | ||
|
|
333ddf1970 | ||
|
|
cd74267364 | ||
|
|
f8631dcc93 | ||
|
|
7a17586eb3 | ||
|
|
13427e18d5 | ||
|
|
1dccc0252a | ||
|
|
75ce2bdefa | ||
|
|
c9e0f4e3ef | ||
|
|
7d9e710f05 | ||
|
|
236cece3b3 | ||
|
|
84f4c904b7 | ||
|
|
6998e8bdd1 | ||
|
|
961b8c2477 | ||
|
|
a157b65fbf | ||
|
|
47f0aa597e | ||
|
|
67b069579e | ||
|
|
156839b73e | ||
|
|
25a1c553bf | ||
|
|
8dee01195d | ||
|
|
5eae169d7b | ||
|
|
66ff1f2ea3 | ||
|
|
18dcf2a121 | ||
|
|
9b26f4d767 | ||
|
|
25637bb33a | ||
|
|
c5737f6d28 | ||
|
|
1659f21bb3 | ||
|
|
ba8cb3cf6d | ||
|
|
e098ddaacd | ||
|
|
964a4765b1 | ||
|
|
a42e067f3b | ||
|
|
60848143b7 | ||
|
|
5d8f04363d | ||
|
|
cad425989e | ||
|
|
1b4377cbf3 | ||
|
|
75eb1917f9 | ||
|
|
5fd793090a | ||
|
|
ac19422a90 | ||
|
|
9c0346b90b | ||
|
|
b473d8827f | ||
|
|
bcab8d6369 | ||
|
|
dbc1538054 | ||
|
|
46f03013f3 | ||
|
|
1ade44221a | ||
|
|
2a3dd85a18 | ||
|
|
dfd84a10ed | ||
|
|
7543eedd6a | ||
|
|
605063b974 | ||
|
|
7d7d249182 | ||
|
|
06296b0a40 | ||
|
|
e20081454f | ||
|
|
4da31c0709 | ||
|
|
5aa6252df6 | ||
|
|
bbbc8a68e0 |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1 +1,5 @@
|
||||
*.swp
|
||||
**/*.swp
|
||||
*.gem
|
||||
Gemfile.lock
|
||||
.bundle
|
||||
|
||||
1
.rbenv-version
Normal file
1
.rbenv-version
Normal file
@@ -0,0 +1 @@
|
||||
1.9.3-p194
|
||||
8
.travis.yml
Normal file
8
.travis.yml
Normal file
@@ -0,0 +1,8 @@
|
||||
rvm:
|
||||
- 1.9.3
|
||||
- 1.9.2
|
||||
- 1.8.7
|
||||
- ree
|
||||
notifications:
|
||||
recipients:
|
||||
- ryan@railscasts.com
|
||||
299
CHANGELOG.rdoc
299
CHANGELOG.rdoc
@@ -1,7 +1,294 @@
|
||||
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)
|
||||
|
||||
@@ -25,6 +312,8 @@
|
||||
|
||||
* 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)
|
||||
|
||||
@@ -34,6 +323,8 @@
|
||||
|
||||
* 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)
|
||||
|
||||
@@ -41,6 +332,8 @@
|
||||
|
||||
* 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)
|
||||
|
||||
@@ -56,6 +349,8 @@
|
||||
|
||||
* 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)
|
||||
|
||||
@@ -65,6 +360,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)
|
||||
|
||||
@@ -76,6 +373,8 @@
|
||||
|
||||
* 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)
|
||||
|
||||
|
||||
2
LICENSE
2
LICENSE
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2009 Ryan Bates
|
||||
Copyright (c) 2011 Ryan Bates
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
|
||||
179
README.rdoc
179
README.rdoc
@@ -1,147 +1,108 @@
|
||||
= CanCan
|
||||
= CanCan {<img src="https://secure.travis-ci.org/ryanb/cancan.png" />}[http://travis-ci.org/ryanb/cancan]
|
||||
|
||||
Wiki[http://wiki.github.com/ryanb/cancan] | RDocs[http://rdoc.info/projects/ryanb/cancan] | Screencast[http://railscasts.com/episodes/192-authorization-with-cancan] | Metrics[http://getcaliper.com/caliper/project?repo=git%3A%2F%2Fgithub.com%2Fryanb%2Fcancan.git]
|
||||
This is the branch for CanCan 2.0 which is in very early development. For a stable release please check out the {master branch}[https://github.com/ryanb/cancan]
|
||||
|
||||
CanCan is an authorization solution for Ruby on Rails. This restricts what a given user is allowed to access throughout the application. It is completely decoupled from any role based implementation and focusses on keeping permission logic in a single location (the +Ability+ class) so it is not duplicated across controllers, views, and database queries.
|
||||
|
||||
This assumes you already have authentication (such as Authlogic[http://github.com/binarylogic/authlogic] or Devise[http://github.com/plataformatec/devise]) that provides a +current_user+ method which CanCan relies on. See {Changing Defaults}[http://wiki.github.com/ryanb/cancan/changing-defaults] if you need different behavior.
|
||||
Here are some instructions for setting up CanCan 2.0. Try this out and provide feedback in the {issue tracker}[https://github.com/ryanb/cancan/issues].
|
||||
|
||||
|
||||
== Installation
|
||||
== Setup
|
||||
|
||||
CanCan is provided as a gem. Simply include it in your environment.rb or Gemfile.
|
||||
CanCan expects your controllers to have a +current_user+ method. Add some authentication for this (such as Devise[https://github.com/plataformatec/devise], Authlogic[https://github.com/binarylogic/authlogic] or {nifty:authentication}[https://github.com/ryanb/nifty-generators]). See {Changing Defaults}[https://github.com/ryanb/cancan/wiki/Changing-Defaults] to customize this behavior.
|
||||
|
||||
config.gem "cancan"
|
||||
To install CanCan, add it to your Gemfile and run the `bundle` command.
|
||||
|
||||
Alternatively it can be installed as a plugin.
|
||||
gem "cancan", :git => "git://github.com/ryanb/cancan.git", :branch => "2.0"
|
||||
|
||||
script/plugin install git://github.com/ryanb/cancan.git
|
||||
Next generate an Ability class, this is where your permissions will be defined.
|
||||
|
||||
rails g cancan:ability
|
||||
|
||||
== Getting Started
|
||||
|
||||
First, define a class called +Ability+ in "models/ability.rb". It should look something like this.
|
||||
|
||||
class Ability
|
||||
include CanCan::Ability
|
||||
|
||||
def initialize(user)
|
||||
if user.admin?
|
||||
can :manage, :all
|
||||
else
|
||||
can :read, :all
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
This is where all permissions will go. See the "Defining Abilities" section below for more information.
|
||||
|
||||
The current user's permissions can be accessed using the "can?" and "cannot?" methods in the view and controller.
|
||||
|
||||
<% if can? :update, @article %>
|
||||
<%= link_to "Edit", edit_article_path(@article) %>
|
||||
<% end %>
|
||||
|
||||
See {Checking Abilities}[http://wiki.github.com/ryanb/cancan/checking-abilities] for more information
|
||||
|
||||
The "authorize!" method in the controller will raise an exception if the user is not able to perform the given action.
|
||||
|
||||
def show
|
||||
@article = Article.find(params[:id])
|
||||
authorize! :read, @article
|
||||
end
|
||||
|
||||
Setting this for every action can be tedious, therefore the +load_and_authorize_resource+ method is provided to automatically authorize all actions in a RESTful style resource controller. It will use a before filter to load the resource into an instance variable and authorize it for each action.
|
||||
|
||||
class ArticlesController < ApplicationController
|
||||
load_and_authorize_resource
|
||||
|
||||
def show
|
||||
# @article is already loaded and authorized
|
||||
end
|
||||
end
|
||||
|
||||
See {Authorizing Controller Actions}[http://wiki.github.com/ryanb/cancan/authorizing-controller-actions] for more information
|
||||
|
||||
If the user authorization fails, a CanCan::AccessDenied exception will be raised. You can catch this and modify its behavior in the +ApplicationController+.
|
||||
Add authorization by calling {enable_authorization}[https://github.com/ryanb/cancan/wiki/enable_authorization] in your ApplicationController.
|
||||
|
||||
class ApplicationController < ActionController::Base
|
||||
rescue_from CanCan::AccessDenied do |exception|
|
||||
flash[:error] = exception.message
|
||||
redirect_to root_url
|
||||
end
|
||||
enable_authorization
|
||||
end
|
||||
|
||||
See {Exception Handling}[http://wiki.github.com/ryanb/cancan/exception-handling] for more information.
|
||||
This will add an authorization check locking down every controller action. If you try visiting a page, a <tt>CanCan::Unauthorized</tt> exception will be raised since you have not granted the user ability to access it.
|
||||
|
||||
|
||||
== Defining Abilities
|
||||
|
||||
As shown above, the +Ability+ class is where all user permissions are defined. The user model is passed into the initialize method so the permissions can be modified based on any user attributes. CanCan makes no assumptions about how roles are handled in your application. See {Role Based Authorization}[http://wiki.github.com/ryanb/cancan/role-based-authorization] for an example.
|
||||
You grant access to controller actions through the +Ability+ class which was generated above. The +current_user+ is passed in allowing you to define permissions based on user attributes. For example:
|
||||
|
||||
The +can+ method is used to define permissions and requires two arguments. The first one is the action you're setting the permission for, the second one is the class of object you're setting it on.
|
||||
|
||||
can :update, Article
|
||||
|
||||
You can pass an array for either of these parameters to match any one. In this case the user will have the ability to update or destroy both articles and comments.
|
||||
|
||||
can [:update, :destroy], [Article, Comment]
|
||||
|
||||
Use :+manage+ to represent any action and :+all+ to represent any class. Here are some examples.
|
||||
|
||||
can :manage, Article # has permissions to do anything to articles
|
||||
can :read, :all # has permission to read any model
|
||||
can :manage, :all # has permission to do anything to any model
|
||||
|
||||
You can pass a hash of conditions as the third argument to further restrict what the user is able to access. Here the user will only have permission to read active projects which he owns.
|
||||
|
||||
can :read, Project, :active => true, :user_id => user.id
|
||||
|
||||
See {Defining Abilities with Hashes}[http://wiki.github.com/ryanb/cancan/defining-abilities-with-hashes] for more information.
|
||||
|
||||
Blocks can also be used if you need more control.
|
||||
|
||||
can :update, Project do |project|
|
||||
project && project.groups.include?(user.group)
|
||||
if user
|
||||
can :access, :all
|
||||
else
|
||||
can :access, :home
|
||||
can :create, [:users, :sessions]
|
||||
end
|
||||
|
||||
If the block returns true then the user has that :+update+ ability for that project, otherwise he will be denied access. See {Defining Abilities with Blocks}[http://wiki.github.com/ryanb/cancan/defining-abilities-with-blocks] for more information.
|
||||
Here if there is a user he will be able to perform any action on any controller. If someone is not logged in he can only access the home, users, and sessions controllers.
|
||||
|
||||
The first argument to +can+ is the action the user can perform. The second argument is the controller name they can perform that action on. You can pass <tt>:access</tt> and <tt>:all</tt> to represent any action and controller respectively.
|
||||
|
||||
As shown above, pass an array to either of these will grant permission on each item in the array. It isn't necessary to pass the +new+ action here because CanCan includes some default aliases. See the {Aliases}[https://github.com/ryanb/cancan/wiki/Aliases] page for details.
|
||||
|
||||
You can check permissions in any controller or view using the <tt>can?</tt> method.
|
||||
|
||||
<% if can? :create, :comments %>
|
||||
<%= link_to "New Comment", new_comment_path %>
|
||||
<% end %>
|
||||
|
||||
Here the link will only show up the user can create comments.
|
||||
|
||||
|
||||
== Aliasing Actions
|
||||
== Resource Conditions
|
||||
|
||||
You will usually be working with four actions when defining and checking permissions: :+read+, :+create+, :+update+, :+destroy+. These aren't the same as the 7 RESTful actions in Rails. CanCan automatically adds some default aliases for mapping those actions.
|
||||
What if you need to change authorization based on a model's attributes? You can do so by passing a hash of conditions as the last argument to +can+. For example, if you want to only allow one to access projects which he owns you can set the <tt>:user_id</tt>.
|
||||
|
||||
alias_action :index, :show, :to => :read
|
||||
alias_action :new, :to => :create
|
||||
alias_action :edit, :to => :update
|
||||
can :access, :projects, :user_id => user.id
|
||||
|
||||
Notice the +edit+ action is aliased to +update+. If the user is able to update a record he also has permission to edit it. You can define your own aliases in the +Ability+ class
|
||||
A block can also be used for complex condition checks just like in CanCan 1, but here it is not necessary.
|
||||
|
||||
alias_action :update, :destroy, :to => :modify
|
||||
can :modify, Comment
|
||||
can? :update, Comment # => true
|
||||
If you try visiting any of the project pages at this point you will see a <tt>CanCan::InsufficientAuthorizationCheck</tt> exception is raised. This is because the default authorization has no way to check permissions on the <tt>@project</tt> instance. You can check permissions on an object manually using the <tt>authorize!</tt> method.
|
||||
|
||||
See {Custom Actions}[http://wiki.github.com/ryanb/cancan/custom-actions] for information on adding other actions.
|
||||
def edit
|
||||
@project = Project.find(params[:id])
|
||||
authorize! :edit, @project
|
||||
end
|
||||
|
||||
However this can get tedious. Instead CanCan provides a +load_and_authorize_resource+ method to load the <tt>@project</tt> instance in every controller action and authorize it.
|
||||
|
||||
class ProjectsController < ApplicationController
|
||||
load_and_authorize_resource
|
||||
def edit
|
||||
# @project already loaded here and authorized
|
||||
end
|
||||
end
|
||||
|
||||
The +index+ (and other collection actions) will load the <tt>@projects</tt> instance which automatically limits the projects the user is allowed to access. This is a scope so you can make further calls to +where+ to limit what is returned from the database.
|
||||
|
||||
def index
|
||||
@projects = @projects.where(:hidden => false)
|
||||
end
|
||||
|
||||
You can check permissions on instances using the <tt>can?</tt> method.
|
||||
|
||||
<%= link_to "Edit Project", edit_project_path if can? :update, @project %>
|
||||
|
||||
Here it will only show the edit link if the +user_id+ matches.
|
||||
|
||||
|
||||
== Fetching Records
|
||||
== Resource Attributes
|
||||
|
||||
In the controller +index+ action you may want to fetch only the records which the user has permission to read. You can do this with the +accessible_by+ scope.
|
||||
In CanCan 2.0 it is possible to define permissions on specific resource attributes. For example, if you want to allow a user to only update the name and priority of a project, pass that as the third argument to +can+.
|
||||
|
||||
@articles = Article.accessible_by(current_ability)
|
||||
can :update, :projects, [:name, :priority]
|
||||
|
||||
See {Fetching Records}[http://wiki.github.com/ryanb/cancan/fetching-records] for more information.
|
||||
If you use this in combination with +load_and_authorize_resource+ it will ensure that only those two attributes exist in <tt>params[:project]</tt> when updating the project. If you do this everywhere it will not be necessary to use +attr_accessible+ in your models.
|
||||
|
||||
You can combine this with a hash of conditions. For example, here the user can update all attributes except the price when the product is discontinued.
|
||||
|
||||
== Additional Docs
|
||||
can :update, :products
|
||||
cannot :update, :products, :price, :discontinued => true
|
||||
|
||||
* {Upgrading to 1.1}[http://wiki.github.com/ryanb/cancan/upgrading-to-11]
|
||||
* {Testing Abilities}[http://wiki.github.com/ryanb/cancan/testing-abilities]
|
||||
* {Accessing Request Data}[http://wiki.github.com/ryanb/cancan/accessing-request-data]
|
||||
* {Admin Namespace}[http://wiki.github.com/ryanb/cancan/admin-namespace]
|
||||
* {See more}[http://wiki.github.com/ryanb/cancan/]
|
||||
You can check permissions on specific attributes to determine what to show in the form.
|
||||
|
||||
== Special Thanks
|
||||
<%= f.text_field :name if can? :update, @project, :name %>
|
||||
|
||||
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.
|
||||
|
||||
31
Rakefile
31
Rakefile
@@ -1,13 +1,18 @@
|
||||
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
|
||||
|
||||
task :default => :spec
|
||||
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
|
||||
|
||||
@@ -1,15 +1,26 @@
|
||||
Gem::Specification.new do |s|
|
||||
s.name = "cancan"
|
||||
s.version = "1.1.1"
|
||||
s.version = "2.0.0.alpha"
|
||||
s.author = "Ryan Bates"
|
||||
s.email = "ryan@railscasts.com"
|
||||
s.homepage = "http://github.com/ryanb/cancan"
|
||||
s.summary = "Simple authorization solution for Rails."
|
||||
s.description = "Simple authorization solution for Rails which is completely decoupled from the user's roles. All permissions are stored in a single location for convenience."
|
||||
|
||||
s.files = Dir["{lib,spec}/**/*", "[A-Z]*", "init.rb"]
|
||||
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.9.0"
|
||||
s.add_development_dependency "rails", "~> 3.2.6"
|
||||
s.add_development_dependency "sqlite3", "~> 1.3.5"
|
||||
|
||||
s.add_development_dependency "dm-core", "~> 1.2.0"
|
||||
s.add_development_dependency "dm-sqlite-adapter", "~> 1.2.0"
|
||||
s.add_development_dependency "dm-migrations", "~> 1.2.0"
|
||||
|
||||
s.add_development_dependency "mongoid", "~> 2.4.8"
|
||||
s.add_development_dependency "bson_ext", "~> 1.6.2"
|
||||
|
||||
s.rubyforge_project = s.name
|
||||
s.required_rubygems_version = ">= 1.3.4"
|
||||
end
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
require 'cancan/ability'
|
||||
require 'cancan/rule'
|
||||
require 'cancan/controller_resource'
|
||||
require 'cancan/resource_authorization'
|
||||
require 'cancan/controller_additions'
|
||||
require 'cancan/active_record_additions'
|
||||
require 'cancan/model_additions'
|
||||
require 'cancan/exceptions'
|
||||
require 'cancan/inherited_resource'
|
||||
|
||||
require 'cancan/model_adapters/abstract_adapter'
|
||||
require 'cancan/model_adapters/default_adapter'
|
||||
require 'cancan/model_adapters/active_record_adapter' if defined? ActiveRecord
|
||||
require 'cancan/model_adapters/data_mapper_adapter' if defined? DataMapper
|
||||
require 'cancan/model_adapters/mongoid_adapter' if defined?(Mongoid) && defined?(Mongoid::Document)
|
||||
|
||||
@@ -1,275 +1,348 @@
|
||||
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
|
||||
#
|
||||
# def initialize(user)
|
||||
# if user.admin?
|
||||
# can :manage, :all
|
||||
# can :access, :all
|
||||
# else
|
||||
# can :read, :all
|
||||
# end
|
||||
# end
|
||||
# end
|
||||
#
|
||||
#
|
||||
module Ability
|
||||
# Use to check the user's permission for a given action and object.
|
||||
#
|
||||
# Check if the user has permission to perform a given action on an object.
|
||||
#
|
||||
# can? :destroy, @project
|
||||
#
|
||||
#
|
||||
# You can also pass the class instead of an instance (if you don't have one handy).
|
||||
#
|
||||
# can? :create, 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),
|
||||
#
|
||||
# can? :create, :projects
|
||||
#
|
||||
# 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 => :projects
|
||||
#
|
||||
# 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
|
||||
#
|
||||
def can?(action, subject, *extra_args)
|
||||
matching_can_definition(action, subject) do |base_behavior, defined_actions, defined_subjects, defined_conditions, defined_block|
|
||||
result = can_perform_action?(action, subject, defined_actions, defined_subjects, defined_conditions, defined_block, extra_args)
|
||||
return base_behavior ? result : !result
|
||||
#
|
||||
# Also see the RSpec Matchers to aid in testing.
|
||||
def can?(action, subject, attribute = nil)
|
||||
match = relevant_rules_for_match(action, subject, attribute).detect do |rule|
|
||||
rule.matches_conditions?(action, subject, attribute)
|
||||
end
|
||||
false
|
||||
match ? match.base_behavior : 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
|
||||
#
|
||||
#
|
||||
# can :update, :articles
|
||||
#
|
||||
# You can pass an array for either of these parameters to match any one.
|
||||
# Here the user has the ability to update or destroy both articles and comments.
|
||||
#
|
||||
# can [:update, :destroy], [Article, Comment]
|
||||
# can [:update, :destroy], [:articles, :comments]
|
||||
#
|
||||
# In this case the user has the ability to update or destroy both articles and comments.
|
||||
#
|
||||
# You can pass a hash of conditions as the third argument.
|
||||
# You can pass :all to match any object and :access to match any action. Here are some examples.
|
||||
#
|
||||
# can :read, Project, :active => true, :user_id => user.id
|
||||
#
|
||||
# Here the user can only see active projects which he owns. See ControllerAdditions#conditions for a way to
|
||||
# use this in database queries.
|
||||
#
|
||||
# If the conditions hash does not give you enough control over defining abilities, you can use a block to
|
||||
# write any Ruby code you want.
|
||||
# can :access, :all
|
||||
# can :update, :all
|
||||
# can :access, :projects
|
||||
#
|
||||
# can :update, Project do |project|
|
||||
# project && project.groups.include?(user.group)
|
||||
# You can pass a hash of conditions as the third argument. Here the user can only see active projects which he owns.
|
||||
#
|
||||
# can :read, :projects, :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, :projects do |project|
|
||||
# project.groups.include?(user.group)
|
||||
# end
|
||||
#
|
||||
#
|
||||
# If the block returns true then the user has that :update ability for that project, otherwise he
|
||||
# will be denied access. It's possible for the passed in model to be nil if one isn't specified,
|
||||
# so be sure to take that into consideration.
|
||||
#
|
||||
# The downside to using a block is that it cannot be used to generate conditions for database queries.
|
||||
#
|
||||
# You can pass :all to reference every type of object. In this case the object type will be passed
|
||||
# into the block as well (just in case object is nil).
|
||||
#
|
||||
# can :read, :all do |object_class, object|
|
||||
# object_class != Order
|
||||
# will be denied access. The downside to using a block is that it cannot be used to generate
|
||||
# conditions for database queries.
|
||||
#
|
||||
# IMPORTANT: Neither a hash of conditions or a block will be used when checking permission on a symbol.
|
||||
#
|
||||
# can :update, :projects, :priority => 3
|
||||
# can? :update, :projects # => 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, subject, object|
|
||||
# # check the database and return true/false
|
||||
# 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
|
||||
#
|
||||
def can(action, subject, conditions = nil, &block)
|
||||
@can_definitions ||= []
|
||||
@can_definitions << [true, action, subject, conditions, block]
|
||||
#
|
||||
def can(*args, &block)
|
||||
rules << Rule.new(true, *args, &block)
|
||||
end
|
||||
|
||||
# Define an ability which cannot be done. Accepts the same arguments as "can".
|
||||
#
|
||||
|
||||
# Defines an ability which cannot be done. Accepts the same arguments as "can".
|
||||
#
|
||||
# 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|
|
||||
#
|
||||
# cannot :read, :projects do |product|
|
||||
# product.invisible?
|
||||
# end
|
||||
#
|
||||
def cannot(action, subject, conditions = nil, &block)
|
||||
@can_definitions ||= []
|
||||
@can_definitions << [false, action, subject, conditions, block]
|
||||
#
|
||||
def cannot(*args, &block)
|
||||
rules << Rule.new(false, *args, &block)
|
||||
end
|
||||
|
||||
|
||||
# Alias one or more actions into another one.
|
||||
#
|
||||
#
|
||||
# alias_action :update, :destroy, :to => :modify
|
||||
# can :modify, Comment
|
||||
#
|
||||
# can :modify, :comments
|
||||
#
|
||||
# Then :modify permission will apply to both :update and :destroy requests.
|
||||
#
|
||||
# can? :update, Comment # => true
|
||||
# can? :destroy, Comment # => true
|
||||
#
|
||||
#
|
||||
# can? :update, :comments # => true
|
||||
# can? :destroy, :comments # => 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
|
||||
#
|
||||
# can :update, :comments
|
||||
# can? :modify, :comments # => false
|
||||
#
|
||||
# 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]
|
||||
aliased_actions[target] ||= []
|
||||
aliased_actions[target] += args
|
||||
aliases[:actions][target] ||= []
|
||||
aliases[:actions][target] += args
|
||||
end
|
||||
|
||||
# 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
|
||||
@aliased_actions ||= default_alias_actions
|
||||
|
||||
# Alias one or more subjects into another one.
|
||||
#
|
||||
# alias_subject :admins, :moderators, :to => :users
|
||||
# can :update, :users
|
||||
#
|
||||
# Then :modify permission will apply to both :update and :destroy requests.
|
||||
#
|
||||
# can? :update, :admins # => true
|
||||
# can? :update, :moderators # => true
|
||||
#
|
||||
# This only works in one direction. Passing the aliased subject into the "can?" call
|
||||
# will not work because aliases are meant to generate more generic subjects.
|
||||
#
|
||||
# alias_subject :admins, :moderators, :to => :users
|
||||
# can :update, :admins
|
||||
# can? :update, :users # => false
|
||||
#
|
||||
def alias_subject(*args)
|
||||
target = args.pop[:to]
|
||||
aliases[:subjects][target] ||= []
|
||||
aliases[:subjects][target] += args
|
||||
end
|
||||
|
||||
# Removes previously aliased actions including the defaults.
|
||||
def clear_aliased_actions
|
||||
@aliased_actions = {}
|
||||
|
||||
# Returns a hash of action and subject aliases.
|
||||
def aliases
|
||||
@aliases ||= default_aliases
|
||||
end
|
||||
|
||||
# Returns a hash of conditions which match the given ability. This is useful if you need to generate a database
|
||||
# query based on the current ability.
|
||||
#
|
||||
# can :read, Article, :visible => true
|
||||
# conditions :read, Article # returns { :visible => true }
|
||||
#
|
||||
# Normally you will not call this method directly, but instead go through ActiveRecordAdditions#accessible_by method.
|
||||
#
|
||||
# If the ability is not defined then false is returned so be sure to take that into consideration.
|
||||
# If the ability is defined using a block then this will raise an exception since a hash of conditions cannot be
|
||||
# determined from that.
|
||||
def conditions(action, subject)
|
||||
matching_can_definition(action, subject) do |base_behavior, defined_actions, defined_subjects, defined_conditions, defined_block|
|
||||
raise Error, "Cannot determine ability conditions from block for #{action.inspect} #{subject.inspect}" if defined_block
|
||||
return defined_conditions || {}
|
||||
|
||||
# Removes previously aliased actions or subjects including the defaults.
|
||||
def clear_aliases
|
||||
aliases[:actions] = {}
|
||||
aliases[:subjects] = {}
|
||||
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.to_s.underscore.pluralize.to_sym))
|
||||
end
|
||||
|
||||
# See ControllerAdditions#authorize! for documentation.
|
||||
def authorize!(action, subject, *args)
|
||||
message = nil
|
||||
if args.last.kind_of?(Hash)
|
||||
message = args.pop[:message]
|
||||
end
|
||||
false
|
||||
attribute = args.first
|
||||
if cannot?(action, subject, *args)
|
||||
message ||= unauthorized_message(action, subject)
|
||||
raise Unauthorized.new(message, action, subject)
|
||||
elsif sufficient_attribute_check?(action, subject, attribute) && sufficient_condition_check?(action, subject)
|
||||
fully_authorized!(action, subject)
|
||||
end
|
||||
subject
|
||||
end
|
||||
|
||||
|
||||
def unauthorized_message(action, subject)
|
||||
keys = unauthorized_message_keys(action, subject)
|
||||
variables = {:action => action.to_s}
|
||||
variables[:subject] = (subject.kind_of?(Symbol) ? subject.to_s : subject.class.to_s.underscore.humanize.downcase.pluralize)
|
||||
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 has_instance_conditions?(action, subject)
|
||||
relevant_rules(action, subject).any?(&:instance_conditions?)
|
||||
end
|
||||
|
||||
def has_attributes?(action, subject)
|
||||
relevant_rules(action, subject).any?(&:attributes?)
|
||||
end
|
||||
|
||||
def fully_authorized?(action, subject)
|
||||
@fully_authorized ||= []
|
||||
@fully_authorized.include? [action.to_sym, subject.to_sym]
|
||||
end
|
||||
|
||||
def fully_authorized!(action, subject)
|
||||
subject = subject.class.to_s.underscore.pluralize.to_sym unless subject.kind_of?(Symbol) || subject.kind_of?(String)
|
||||
@fully_authorized ||= []
|
||||
@fully_authorized << [action.to_sym, subject.to_sym]
|
||||
end
|
||||
|
||||
def merge(ability)
|
||||
ability.send(:rules).each do |rule|
|
||||
rules << rule.dup
|
||||
end
|
||||
self
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def matching_can_definition(action, subject, &block)
|
||||
(@can_definitions || []).reverse.each do |base_behavior, defined_action, defined_subject, defined_conditions, defined_block|
|
||||
defined_actions = expand_actions(defined_action)
|
||||
defined_subjects = [defined_subject].flatten
|
||||
if includes_action?(defined_actions, action) && includes_subject?(defined_subjects, subject)
|
||||
return block.call(base_behavior, defined_actions, defined_subjects, defined_conditions, defined_block)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def default_alias_actions
|
||||
{
|
||||
:read => [:index, :show],
|
||||
:create => [:new],
|
||||
:update => [:edit],
|
||||
}
|
||||
end
|
||||
|
||||
def expand_actions(actions)
|
||||
[actions].flatten.map do |action|
|
||||
if aliased_actions[action]
|
||||
[action, *aliased_actions[action]]
|
||||
else
|
||||
action
|
||||
|
||||
def unauthorized_message_keys(action, subject)
|
||||
subject = (subject.kind_of?(Symbol) ? subject.to_s : subject.class.to_s.underscore.pluralize)
|
||||
[aliases_for(:subjects, subject.to_sym), :all].flatten.map do |try_subject|
|
||||
[aliases_for(:actions, action.to_sym), :access].flatten.map do |try_action|
|
||||
:"#{try_action}.#{try_subject}"
|
||||
end
|
||||
end.flatten
|
||||
end
|
||||
|
||||
def can_perform_action?(action, subject, defined_actions, defined_subjects, defined_conditions, defined_block, extra_args)
|
||||
if defined_block
|
||||
block_args = []
|
||||
block_args << action if defined_actions.include?(:manage)
|
||||
block_args << (subject.class == Class ? subject : subject.class) if defined_subjects.include?(:all)
|
||||
block_args << (subject.class == Class ? nil : subject)
|
||||
block_args += extra_args
|
||||
defined_block.call(*block_args)
|
||||
elsif defined_conditions
|
||||
if subject.class == Class
|
||||
true
|
||||
else
|
||||
matches_conditions? subject, defined_conditions
|
||||
end
|
||||
else
|
||||
true
|
||||
end
|
||||
|
||||
def sufficient_attribute_check?(action, subject, attribute)
|
||||
!(%w[create update].include?(action.to_s) && attribute.nil? && has_attributes?(action, subject))
|
||||
end
|
||||
|
||||
def matches_conditions?(subject, defined_conditions)
|
||||
defined_conditions.all? do |name, value|
|
||||
attribute = subject.send(name)
|
||||
if value.kind_of?(Hash)
|
||||
matches_conditions? attribute, value
|
||||
elsif value.kind_of?(Array) || value.kind_of?(Range)
|
||||
value.include? attribute
|
||||
else
|
||||
attribute == value
|
||||
|
||||
def sufficient_condition_check?(action, subject)
|
||||
!((subject.kind_of?(Symbol) || subject.kind_of?(String)) && has_instance_conditions?(action, subject))
|
||||
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_aliases(type, items)
|
||||
items.map do |item|
|
||||
aliases[type][item] ? [item, *expand_aliases(type, aliases[type][item])] : item
|
||||
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_aliases.
|
||||
def aliases_for(type, action)
|
||||
results = [action]
|
||||
aliases[type].each do |aliased_action, actions|
|
||||
results += aliases_for(type, 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, attribute = nil)
|
||||
specificity = 0
|
||||
rules.reverse.each_with_object([]) do |rule, relevant_rules|
|
||||
rule.expanded_actions = expand_aliases(:actions, rule.actions)
|
||||
rule.expanded_subjects = expand_aliases(:subjects, rule.subjects)
|
||||
if rule.relevant?(action, subject, attribute) && rule.specificity >= specificity
|
||||
specificity = rule.specificity if rule.base_behavior
|
||||
relevant_rules << rule
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def includes_action?(actions, action)
|
||||
actions.include?(:manage) || actions.include?(action)
|
||||
|
||||
def relevant_rules_for_match(action, subject, attribute)
|
||||
relevant_rules(action, subject, attribute).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 includes_subject?(subjects, subject)
|
||||
subjects.include?(:all) || subjects.include?(subject) || subjects.any? { |c| c.kind_of?(Class) && subject.kind_of?(c) }
|
||||
|
||||
def relevant_rules_for_query(action, subject)
|
||||
relevant_rules(action, subject, nil).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_aliases
|
||||
{
|
||||
:subjects => {},
|
||||
:actions => {
|
||||
:read => [:index, :show],
|
||||
:create => [:new],
|
||||
:update => [:edit],
|
||||
:destroy => [:delete],
|
||||
}
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,35 +1,39 @@
|
||||
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(options = {})
|
||||
ResourceAuthorization.add_before_filter(self, :load_and_authorize_resource, options)
|
||||
#
|
||||
def load_and_authorize_resource(*args)
|
||||
cancan_resource_class.add_before_filter(self, {:load => true, :authorize => true}, *args)
|
||||
end
|
||||
|
||||
# Sets up a before filter which loads the appropriate model resource into an instance variable.
|
||||
|
||||
# Sets up a before filter which loads the model resource into an instance variable.
|
||||
# For example, given an ArticlesController it will load the current article into the @article
|
||||
# instance variable. It does this by either calling Article.find(params[:id]) or
|
||||
# Article.new(params[:article]) depending upon the action. It does nothing for the "index"
|
||||
# action.
|
||||
#
|
||||
# Article.new(params[:article]) depending upon the action. The index action will
|
||||
# automatically set @articles to Article.accessible_by(current_ability).
|
||||
#
|
||||
# If a conditions hash is used in the Ability, the +new+ and +create+ actions will set
|
||||
# the initial attributes based on these conditions. This way these actions will satisfy
|
||||
# the ability restrictions.
|
||||
#
|
||||
# Call this method directly on the controller class.
|
||||
#
|
||||
#
|
||||
# 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
|
||||
@@ -40,163 +44,348 @@ module CanCan
|
||||
# @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.
|
||||
#
|
||||
# [:+nested+]
|
||||
# Specify which resource this is nested under.
|
||||
#
|
||||
# load_resource :nested => :author
|
||||
#
|
||||
# Deep nesting can be defined in an array.
|
||||
#
|
||||
# load_resource :nested => [:publisher, :author]
|
||||
#
|
||||
# [:+resource+]
|
||||
#
|
||||
# [:+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])
|
||||
#
|
||||
# [:+collection+]
|
||||
# Specify which actions are resource collection actions in addition to :+index+. This
|
||||
# is usually not necessary because it will try to guess depending on if an :+id+
|
||||
# is present in +params+.
|
||||
#
|
||||
# is usually not necessary because it will try to guess depending on if the id param is present.
|
||||
#
|
||||
# load_resource :collection => [:sort, :list]
|
||||
#
|
||||
#
|
||||
# [:+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
|
||||
#
|
||||
def load_resource(options = {})
|
||||
ResourceAuthorization.add_before_filter(self, :load_resource, options)
|
||||
#
|
||||
# [:+prepend+]
|
||||
# Passing +true+ will use prepend_before_filter instead of a normal before_filter.
|
||||
#
|
||||
def load_resource(*args)
|
||||
raise ImplementationRemoved, "The load_resource method has been removed, use load_and_authorize_resource instead."
|
||||
cancan_resource_class.add_before_filter(self, {:load => true}, *args)
|
||||
end
|
||||
|
||||
# Sets up a before filter which authorizes the current resource using the instance variable.
|
||||
|
||||
# Sets up a before filter which authorizes the resource using the instance variable.
|
||||
# For example, if you have an ArticlesController it will check the @article instance variable
|
||||
# and ensure the user can perform the current action on it. Under the hood it is doing
|
||||
# something like the following.
|
||||
#
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
# [:+resource+]
|
||||
# The class to use for the model (string or constant). Alternatively pass a symbol
|
||||
# to represent a resource which does not have a class.
|
||||
#
|
||||
def authorize_resource(options = {})
|
||||
ResourceAuthorization.add_before_filter(self, :authorize_resource, options)
|
||||
#
|
||||
# [:+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)
|
||||
raise ImplementationRemoved, "The authorize_resource method has been removed, use load_and_authorize_resource instead."
|
||||
cancan_resource_class.add_before_filter(self, {:authorize => true}, *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)
|
||||
raise ImplementationRemoved, "The skip_load_resource method has been removed, use skip_load_and_authorize_resource instead."
|
||||
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)
|
||||
raise ImplementationRemoved, "The skip_authorize_resource method has been removed, use skip_load_and_authorize_resource instead."
|
||||
options = args.extract_options!
|
||||
name = args.first
|
||||
cancan_skipper[:authorize][name] = options
|
||||
end
|
||||
|
||||
# Add this to a controller to automatically perform authorization on every action.
|
||||
#
|
||||
# class ApplicationController < ActionController::Base
|
||||
# enable_authorization
|
||||
# end
|
||||
#
|
||||
# Internally it does this in a before_filter for every action.
|
||||
#
|
||||
# authorize! params[:action], params[:controller]
|
||||
#
|
||||
# If you need to "skip" authorization in a given controller, it is best to enable :+access+ to it in the +Ability+.
|
||||
#
|
||||
# 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 only takes place if this returns true.
|
||||
#
|
||||
# enable_authorization :if => :admin_controller?
|
||||
#
|
||||
# [:+unless+]
|
||||
# Supply the name of a controller method to be called. The authorization only takes place if this returns false.
|
||||
#
|
||||
# enable_authorization :unless => :devise_controller?
|
||||
#
|
||||
def enable_authorization(options = {}, &block)
|
||||
before_filter(options.slice(:only, :except)) do |controller|
|
||||
break if options[:if] && !controller.send(options[:if])
|
||||
break if options[:unless] && controller.send(options[:unless])
|
||||
controller.authorize! controller.params[:action], controller.params[:controller]
|
||||
end
|
||||
after_filter(options.slice(:only, :except)) do |controller|
|
||||
break if options[:if] && !controller.send(options[:if])
|
||||
break if options[:unless] && controller.send(options[:unless])
|
||||
unless controller.current_ability.fully_authorized? controller.params[:action], controller.params[:controller]
|
||||
raise CanCan::InsufficientAuthorizationCheck, "Authorization check is not sufficient for this action. This is probably because you have conditions or attributes defined in Ability and are not checking for them in the action. One way to solve this is adding load_and_authorize_resource to this controller."
|
||||
end
|
||||
end
|
||||
rescue_from(CanCan::Unauthorized, &block) if block
|
||||
end
|
||||
|
||||
def cancan_resource_class
|
||||
if ancestors.map(&:to_s).include? "InheritedResources::Actions"
|
||||
InheritedResource
|
||||
else
|
||||
ControllerResource
|
||||
end
|
||||
end
|
||||
|
||||
def check_authorization(options = {})
|
||||
raise ImplementationRemoved, "The check_authorization method has been removed, use enable_authorization instead."
|
||||
end
|
||||
|
||||
def skip_authorization_check(*args)
|
||||
raise ImplementationRemoved, "The skip_authorization_check method has been removed, instead authorize access to controller in Ability to 'skip'."
|
||||
end
|
||||
|
||||
def cancan_skipper
|
||||
raise ImplementationRemoved, "The skip_authorization_check method has been removed, instead authorize access to controller in Ability to 'skip'."
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
def self.included(base)
|
||||
base.extend ClassMethods
|
||||
base.helper_method :can?, :cannot?
|
||||
base.helper_method :can?, :cannot?, :current_ability
|
||||
end
|
||||
|
||||
# Raises a CanCan::AccessDenied exception if the current_ability cannot
|
||||
|
||||
# Raises a CanCan::Unauthorized 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.
|
||||
#
|
||||
#
|
||||
# def show
|
||||
# @article = Article.find(params[:id])
|
||||
# authorize! :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.
|
||||
#
|
||||
#
|
||||
# class ApplicationController < ActionController::Base
|
||||
# rescue_from CanCan::AccessDenied do |exception|
|
||||
# flash[:error] = exception.message
|
||||
# redirect_to root_url
|
||||
# rescue_from CanCan::Unauthorized do |exception|
|
||||
# redirect_to root_url, :alert => exception.message
|
||||
# end
|
||||
# end
|
||||
#
|
||||
# See the CanCan::AccessDenied exception for more details on working with the exception.
|
||||
#
|
||||
#
|
||||
# See the CanCan::Unauthorized 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!(action, subject, *args)
|
||||
message = nil
|
||||
if args.last.kind_of?(Hash) && args.last.has_key?(:message)
|
||||
message = args.pop[:message]
|
||||
end
|
||||
raise AccessDenied.new(message, action, subject) if cannot?(action, subject, *args)
|
||||
def authorize!(*args)
|
||||
@_authorized = true
|
||||
current_ability.authorize!(*args)
|
||||
end
|
||||
|
||||
def unauthorized!(message = nil)
|
||||
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.
|
||||
#
|
||||
#
|
||||
# def current_ability
|
||||
# # instead of Ability.new(current_user)
|
||||
# @current_ability ||= UserAbility.new(current_account)
|
||||
# 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)
|
||||
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)
|
||||
end
|
||||
|
||||
|
||||
# Convenience method which works the same as "can?" but returns the opposite value.
|
||||
#
|
||||
#
|
||||
# cannot? :destroy, @project
|
||||
#
|
||||
#
|
||||
def cannot?(*args)
|
||||
current_ability.cannot?(*args)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if defined? ActionController
|
||||
if defined? ActionController::Base
|
||||
ActionController::Base.class_eval do
|
||||
include CanCan::ControllerAdditions
|
||||
end
|
||||
|
||||
@@ -1,47 +1,266 @@
|
||||
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 initialize(controller, name, parent = nil, options = {})
|
||||
raise ImplementationRemoved, "The :class option has been renamed to :resource for specifying the class in CanCan." if options.has_key? :class
|
||||
def self.add_before_filter(controller_class, behavior, *args)
|
||||
options = args.extract_options!.merge(behavior)
|
||||
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)).process
|
||||
end
|
||||
end
|
||||
|
||||
def initialize(controller, *args)
|
||||
@controller = controller
|
||||
@name = name
|
||||
@parent = parent
|
||||
@options = options
|
||||
@params = controller.params
|
||||
@options = args.extract_options!
|
||||
@name = args.first
|
||||
end
|
||||
|
||||
def model_class
|
||||
if @options[:resource].nil?
|
||||
@name.to_s.camelize.constantize
|
||||
elsif @options[:resource].kind_of? String
|
||||
@options[:resource].constantize
|
||||
else
|
||||
@options[:resource]
|
||||
|
||||
def process
|
||||
if @options[:load]
|
||||
if load_instance?
|
||||
self.resource_instance ||= load_resource_instance
|
||||
elsif load_collection?
|
||||
self.collection_instance ||= load_collection
|
||||
current_ability.fully_authorized! @params[:action], @params[:controller]
|
||||
end
|
||||
end
|
||||
if @options[:authorize]
|
||||
if resource_instance
|
||||
if resource_params && (authorization_action == :create || authorization_action == :update)
|
||||
resource_params.each do |key, value|
|
||||
@controller.authorize!(authorization_action, resource_instance, key.to_sym)
|
||||
end
|
||||
else
|
||||
@controller.authorize!(authorization_action, resource_instance)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def find(id)
|
||||
self.model_instance ||= base.find(id)
|
||||
|
||||
def parent?
|
||||
@options.has_key?(:parent) ? @options[:parent] : @name && @name != name_from_controller.to_sym
|
||||
end
|
||||
|
||||
def build(attributes)
|
||||
if base.kind_of? Class
|
||||
self.model_instance ||= base.new(attributes)
|
||||
else
|
||||
self.model_instance ||= base.build(attributes)
|
||||
|
||||
# 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_and_update_resource
|
||||
end
|
||||
end
|
||||
|
||||
def model_instance
|
||||
@controller.instance_variable_get("@#{@name}")
|
||||
|
||||
def load_instance?
|
||||
parent? || member_action?
|
||||
end
|
||||
|
||||
def model_instance=(instance)
|
||||
@controller.instance_variable_set("@#{@name}", instance)
|
||||
|
||||
def load_collection?
|
||||
resource_base.respond_to?(:accessible_by) && !current_ability.has_block?(authorization_action, subject_name)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def base
|
||||
@parent ? @parent.model_instance.send(@name.to_s.pluralize) : model_class
|
||||
|
||||
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 assign_attributes(resource)
|
||||
initial_attributes.each do |attr_name, value|
|
||||
resource.send("#{attr_name}=", value)
|
||||
end
|
||||
|
||||
resource.send("#{parent_name}=", parent_resource) if @options[:singleton] && parent_resource
|
||||
resource
|
||||
end
|
||||
|
||||
def initial_attributes
|
||||
current_ability.attributes_for(@params[:action].to_sym, subject_name).delete_if do |key, value|
|
||||
resource_params && resource_params.include?(key)
|
||||
end
|
||||
end
|
||||
|
||||
def find_and_update_resource
|
||||
resource = find_resource
|
||||
if resource_params
|
||||
@controller.authorize!(authorization_action, resource) if @options[:authorize]
|
||||
resource.attributes = resource_params
|
||||
end
|
||||
resource
|
||||
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)
|
||||
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
|
||||
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 subject_name
|
||||
resource_class.to_s.underscore.pluralize.to_sym
|
||||
end
|
||||
|
||||
def subject_name_with_parent
|
||||
parent_resource ? {parent_resource => subject_name} : subject_name
|
||||
end
|
||||
|
||||
def resource_instance=(instance)
|
||||
@controller.instance_variable_set("@#{instance_name}", instance)
|
||||
end
|
||||
|
||||
def resource_instance
|
||||
if load_instance?
|
||||
if @controller.instance_variable_defined? "@#{instance_name}"
|
||||
@controller.instance_variable_get("@#{instance_name}")
|
||||
elsif @controller.respond_to?(instance_name, true)
|
||||
@controller.send(instance_name)
|
||||
end
|
||||
end
|
||||
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 Unauthorized.new(nil, authorization_action, @params[:controller].to_sym) # 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[@options[:class].to_s.underscore.gsub('/', '_')]
|
||||
else
|
||||
@params[namespaced_name.to_s.underscore.gsub("/", "_")]
|
||||
end
|
||||
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
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,41 +1,51 @@
|
||||
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
|
||||
|
||||
# Raised when enable_authorization is used and not fully authorized by the end of the action
|
||||
class InsufficientAuthorizationCheck < 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)
|
||||
#
|
||||
#
|
||||
# raise CanCan::Unauthorized.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 anot authorized
|
||||
#
|
||||
# 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.
|
||||
class AccessDenied < Error
|
||||
#
|
||||
# See ControllerAdditions#authorize! for more information on rescuing from this exception
|
||||
# and customizing the message using I18n.
|
||||
class Unauthorized < 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 = "You are not authorized to access this page."
|
||||
@default_message = I18n.t(:"unauthorized.default", :default => "You are not authorized to access this page.")
|
||||
end
|
||||
|
||||
|
||||
def to_s
|
||||
@message || @default_message
|
||||
end
|
||||
|
||||
20
lib/cancan/inherited_resource.rb
Normal file
20
lib/cancan/inherited_resource.rb
Normal file
@@ -0,0 +1,20 @@
|
||||
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
|
||||
@@ -1,4 +1,5 @@
|
||||
Spec::Matchers.define :be_able_to do |*args|
|
||||
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
|
||||
|
||||
56
lib/cancan/model_adapters/abstract_adapter.rb
Normal file
56
lib/cancan/model_adapters/abstract_adapter.rb
Normal file
@@ -0,0 +1,56 @@
|
||||
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
|
||||
172
lib/cancan/model_adapters/active_record_adapter.rb
Normal file
172
lib/cancan/model_adapters/active_record_adapter.rb
Normal file
@@ -0,0 +1,172 @@
|
||||
module CanCan
|
||||
module ModelAdapters
|
||||
class ActiveRecordAdapter < AbstractAdapter
|
||||
def self.for_class?(model_class)
|
||||
model_class <= ActiveRecord::Base
|
||||
end
|
||||
|
||||
def self.override_condition_matching?(subject, name, value)
|
||||
name.kind_of?(MetaWhere::Column) if defined? MetaWhere
|
||||
end
|
||||
|
||||
def self.matches_condition?(subject, name, value)
|
||||
subject_value = subject.send(name.column)
|
||||
if name.method.to_s.ends_with? "_any"
|
||||
value.any? { |v| meta_where_match? subject_value, name.method.to_s.sub("_any", ""), v }
|
||||
elsif name.method.to_s.ends_with? "_all"
|
||||
value.all? { |v| meta_where_match? subject_value, name.method.to_s.sub("_all", ""), v }
|
||||
else
|
||||
meta_where_match? subject_value, name.method, value
|
||||
end
|
||||
end
|
||||
|
||||
def self.meta_where_match?(subject_value, method, value)
|
||||
case method.to_sym
|
||||
when :eq then subject_value == value
|
||||
when :not_eq then subject_value != value
|
||||
when :in then value.include?(subject_value)
|
||||
when :not_in then !value.include?(subject_value)
|
||||
when :lt then subject_value < value
|
||||
when :lteq then subject_value <= value
|
||||
when :gt then subject_value > value
|
||||
when :gteq then subject_value >= value
|
||||
when :matches then subject_value =~ Regexp.new("^" + Regexp.escape(value).gsub("%", ".*") + "$", true)
|
||||
when :does_not_match then !meta_where_match?(subject_value, :matches, value)
|
||||
else raise NotImplemented, "The #{method} MetaWhere condition is not supported."
|
||||
end
|
||||
end
|
||||
|
||||
# Returns conditions intended to be used inside a database query. Normally you will not call this
|
||||
# method directly, but instead go through ModelAdditions#accessible_by.
|
||||
#
|
||||
# If there is only one "can" definition, a hash of conditions will be returned matching the one defined.
|
||||
#
|
||||
# can :manage, User, :id => 1
|
||||
# query(:manage, User).conditions # => { :id => 1 }
|
||||
#
|
||||
# If there are multiple "can" definitions, a SQL string will be returned to handle complex cases.
|
||||
#
|
||||
# can :manage, User, :id => 1
|
||||
# can :manage, User, :manager_id => 1
|
||||
# cannot :manage, User, :self_managed => true
|
||||
# query(:manage, User).conditions # => "not (self_managed = 't') AND ((manager_id = 1) OR (id = 1))"
|
||||
#
|
||||
def conditions
|
||||
if @rules.size == 1 && @rules.first.base_behavior
|
||||
# Return the conditions directly if there's just one definition
|
||||
tableized_conditions(@rules.first.conditions).dup
|
||||
else
|
||||
@rules.reverse.inject(false_sql) do |sql, rule|
|
||||
merge_conditions(sql, tableized_conditions(rule.conditions).dup, rule.base_behavior)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def tableized_conditions(conditions, model_class = @model_class)
|
||||
return conditions unless conditions.kind_of? Hash
|
||||
conditions.inject({}) do |result_hash, (name, value)|
|
||||
if value.kind_of? Hash
|
||||
association_class = model_class.reflect_on_association(name).class_name.constantize
|
||||
name = model_class.reflect_on_association(name).table_name.to_sym
|
||||
value = tableized_conditions(value, association_class)
|
||||
end
|
||||
result_hash[name] = value
|
||||
result_hash
|
||||
end
|
||||
end
|
||||
|
||||
# Returns the associations used in conditions for the :joins option of a search.
|
||||
# See ModelAdditions#accessible_by
|
||||
def joins
|
||||
joins_hash = {}
|
||||
@rules.each do |rule|
|
||||
merge_joins(joins_hash, rule.associations_hash)
|
||||
end
|
||||
clean_joins(joins_hash) unless joins_hash.empty?
|
||||
end
|
||||
|
||||
def database_records
|
||||
if override_scope
|
||||
@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) && !nested.empty?
|
||||
merge_joins(base[name], nested)
|
||||
else
|
||||
base[name] = nested
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Removes empty hashes and moves everything into arrays.
|
||||
def clean_joins(joins_hash)
|
||||
joins = []
|
||||
joins_hash.each do |name, nested|
|
||||
joins << (nested.empty? ? name : {name => clean_joins(nested)})
|
||||
end
|
||||
joins
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
ActiveSupport.on_load(:active_record) do
|
||||
ActiveRecord::Base.class_eval do
|
||||
include CanCan::ModelAdditions
|
||||
end
|
||||
end
|
||||
34
lib/cancan/model_adapters/data_mapper_adapter.rb
Normal file
34
lib/cancan/model_adapters/data_mapper_adapter.rb
Normal file
@@ -0,0 +1,34 @@
|
||||
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)
|
||||
7
lib/cancan/model_adapters/default_adapter.rb
Normal file
7
lib/cancan/model_adapters/default_adapter.rb
Normal file
@@ -0,0 +1,7 @@
|
||||
module CanCan
|
||||
module ModelAdapters
|
||||
class DefaultAdapter < AbstractAdapter
|
||||
# This adapter is used when no matching adapter is found
|
||||
end
|
||||
end
|
||||
end
|
||||
54
lib/cancan/model_adapters/mongoid_adapter.rb
Normal file
54
lib/cancan/model_adapters/mongoid_adapter.rb
Normal file
@@ -0,0 +1,54 @@
|
||||
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
|
||||
@@ -1,42 +1,29 @@
|
||||
module CanCan
|
||||
# This module is automatically included into all Active Record.
|
||||
module ActiveRecordAdditions
|
||||
|
||||
# This module adds the accessible_by class method to a model. It is included in the model adapters.
|
||||
module ModelAdditions
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
module ClassMethods
|
||||
# Returns a scope which fetches only the records that the passed ability
|
||||
# can perform a given action on. The action defaults to :read. This
|
||||
# can perform a given action on. The action defaults to :index. This
|
||||
# is usually called from a controller and passed the +current_ability+.
|
||||
#
|
||||
# @articles = Article.accessible_by(current_ability)
|
||||
#
|
||||
#
|
||||
# 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. This
|
||||
# internally uses Ability#conditions method, see that for more information.
|
||||
def accessible_by(ability, action = :read)
|
||||
conditions = ability.conditions(action, self) || {:id => nil}
|
||||
if respond_to? :where
|
||||
where(conditions)
|
||||
else
|
||||
scoped(:conditions => conditions)
|
||||
end
|
||||
#
|
||||
# Here only the articles which the user can update are returned.
|
||||
def accessible_by(ability, action = :index)
|
||||
ability.model_adapter(self, action).database_records
|
||||
end
|
||||
end
|
||||
|
||||
def self.included(base)
|
||||
base.extend ClassMethods
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if defined? ActiveRecord
|
||||
ActiveRecord::Base.class_eval do
|
||||
include CanCan::ActiveRecordAdditions
|
||||
end
|
||||
end
|
||||
@@ -1,68 +0,0 @@
|
||||
module CanCan
|
||||
class ResourceAuthorization # :nodoc:
|
||||
attr_reader :params
|
||||
|
||||
def self.add_before_filter(controller_class, method, options = {})
|
||||
controller_class.before_filter(options.slice(:only, :except)) do |controller|
|
||||
ResourceAuthorization.new(controller, controller.params, options.except(:only, :except)).send(method)
|
||||
end
|
||||
end
|
||||
|
||||
def initialize(controller, params, options = {})
|
||||
@controller = controller
|
||||
@params = params
|
||||
@options = options
|
||||
end
|
||||
|
||||
def load_and_authorize_resource
|
||||
load_resource
|
||||
authorize_resource
|
||||
end
|
||||
|
||||
def load_resource
|
||||
unless collection_actions.include? params[:action].to_sym
|
||||
if new_actions.include? params[:action].to_sym
|
||||
resource.build(params[model_name.to_sym])
|
||||
elsif params[:id]
|
||||
resource.find(params[:id])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def authorize_resource
|
||||
@controller.authorize!(params[:action].to_sym, resource.model_instance || resource.model_class)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def resource
|
||||
@resource ||= ControllerResource.new(@controller, model_name, parent_resource, @options)
|
||||
end
|
||||
|
||||
def parent_resource
|
||||
parent = nil
|
||||
[@options[:nested]].flatten.compact.each do |name|
|
||||
id = @params["#{name}_id".to_sym]
|
||||
if id
|
||||
parent = ControllerResource.new(@controller, name, parent)
|
||||
parent.find(id)
|
||||
else
|
||||
parent = nil
|
||||
end
|
||||
end
|
||||
parent
|
||||
end
|
||||
|
||||
def model_name
|
||||
params[:controller].sub("Controller", "").underscore.split('/').last.singularize
|
||||
end
|
||||
|
||||
def collection_actions
|
||||
[:index] + [@options[:collection]].flatten
|
||||
end
|
||||
|
||||
def new_actions
|
||||
[:new, :create] + [@options[:new]].flatten
|
||||
end
|
||||
end
|
||||
end
|
||||
178
lib/cancan/rule.rb
Normal file
178
lib/cancan/rule.rb
Normal file
@@ -0,0 +1,178 @@
|
||||
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, :expanded_subjects
|
||||
|
||||
# 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 = nil, subject = nil, *extra_args, &block)
|
||||
@match_all = action.nil? && subject.nil?
|
||||
@base_behavior = base_behavior
|
||||
@actions = [action].flatten
|
||||
@subjects = [subject].flatten
|
||||
@attributes = [extra_args.shift].flatten if extra_args.first.kind_of?(Symbol) || extra_args.first.kind_of?(Array) && extra_args.first.first.kind_of?(Symbol)
|
||||
raise Error, "You are not able to supply a block with a hash of conditions in #{action} #{subject} ability. Use either one." if extra_args.first.kind_of?(Hash) && !block.nil?
|
||||
@conditions = extra_args.first || {}
|
||||
@block = block
|
||||
end
|
||||
|
||||
# Matches the subject, action, and given attribute. Conditions are not checked here.
|
||||
def relevant?(action, subject, attribute)
|
||||
subject = subject.values.first if subject.class == Hash
|
||||
@match_all || (matches_action?(action) && matches_subject?(subject) && matches_attribute?(attribute))
|
||||
end
|
||||
|
||||
# Matches the block or conditions hash
|
||||
def matches_conditions?(action, subject, attribute)
|
||||
if @match_all
|
||||
call_block_with_all(action, subject, attribute)
|
||||
elsif @block && subject_object?(subject)
|
||||
@block.arity == 1 ? @block.call(subject) : @block.call(subject, attribute)
|
||||
elsif @conditions.kind_of?(Hash) && subject.class == Hash
|
||||
nested_subject_matches_conditions?(subject)
|
||||
elsif @conditions.kind_of?(Hash) && subject_object?(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? && !@block.nil?
|
||||
end
|
||||
|
||||
def only_raw_sql?
|
||||
@block.nil? && conditions? && !@conditions.kind_of?(Hash)
|
||||
end
|
||||
|
||||
def attributes?
|
||||
@attributes.present?
|
||||
end
|
||||
|
||||
def conditions?
|
||||
@conditions.present?
|
||||
end
|
||||
|
||||
def instance_conditions?
|
||||
@block || conditions?
|
||||
end
|
||||
|
||||
def unmergeable?
|
||||
@conditions.respond_to?(:keys) && (! @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
|
||||
|
||||
def specificity
|
||||
specificity = 1
|
||||
specificity += 1 if attributes? || conditions?
|
||||
specificity += 2 unless base_behavior
|
||||
specificity
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def subject_object?(subject)
|
||||
# klass = (subject.kind_of?(Hash) ? subject.values.first : subject).class
|
||||
# klass == Class || klass == Module
|
||||
!subject.kind_of?(Symbol) && !subject.kind_of?(String)
|
||||
end
|
||||
|
||||
def matches_action?(action)
|
||||
@expanded_actions.include?(:access) || @expanded_actions.include?(action.to_sym)
|
||||
end
|
||||
|
||||
def matches_subject?(subject)
|
||||
subject = subject_name(subject) if subject_object? subject
|
||||
@expanded_subjects.include?(:all) || @expanded_subjects.include?(subject.to_sym) || @expanded_subjects.include?(subject) # || matches_subject_class?(subject)
|
||||
end
|
||||
|
||||
def matches_attribute?(attribute)
|
||||
# don't consider attributes in a cannot clause when not matching - this can probably be refactored
|
||||
if !@base_behavior && @attributes && attribute.nil?
|
||||
false
|
||||
else
|
||||
@attributes.nil? || attribute.nil? || @attributes.include?(attribute.to_sym)
|
||||
end
|
||||
end
|
||||
|
||||
# TODO deperecate this
|
||||
def matches_subject_class?(subject)
|
||||
@expanded_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 && matches_conditions_hash?(attribute, value)
|
||||
end
|
||||
elsif 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, attribute)
|
||||
if subject_object? subject
|
||||
@block.call(action, subject_name(subject), subject, attribute)
|
||||
else
|
||||
@block.call(action, subject, nil, attribute)
|
||||
end
|
||||
end
|
||||
|
||||
def subject_name(subject)
|
||||
subject.class.to_s.underscore.pluralize.to_sym
|
||||
end
|
||||
|
||||
def model_adapter(subject)
|
||||
CanCan::ModelAdapters::AbstractAdapter.adapter_class(subject_object?(subject) ? subject.class : subject)
|
||||
end
|
||||
end
|
||||
end
|
||||
5
lib/generators/cancan/ability/USAGE
Normal file
5
lib/generators/cancan/ability/USAGE
Normal file
@@ -0,0 +1,5 @@
|
||||
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. A test/spec file is also generated depending
|
||||
on if a spec directory exists.
|
||||
16
lib/generators/cancan/ability/ability_generator.rb
Normal file
16
lib/generators/cancan/ability/ability_generator.rb
Normal file
@@ -0,0 +1,16 @@
|
||||
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"
|
||||
if File.exist?(File.join(destination_root, "spec"))
|
||||
copy_file "ability_spec.rb", "spec/models/ability_spec.rb"
|
||||
else
|
||||
copy_file "ability_test.rb", "test/unit/ability_test.rb"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
24
lib/generators/cancan/ability/templates/ability.rb
Normal file
24
lib/generators/cancan/ability/templates/ability.rb
Normal file
@@ -0,0 +1,24 @@
|
||||
class Ability
|
||||
include CanCan::Ability
|
||||
|
||||
def initialize(user)
|
||||
# Define abilities for the passed in (current) user. For example:
|
||||
#
|
||||
# if user
|
||||
# can :access, :all
|
||||
# else
|
||||
# can :access, :home
|
||||
# can :create, [:users, :sessions]
|
||||
# end
|
||||
#
|
||||
# Here if there is a user he will be able to perform any action on any controller.
|
||||
# If someone is not logged in he can only access the home, users, and sessions controllers.
|
||||
#
|
||||
# The first argument to `can` is the action the user can perform. The second argument
|
||||
# is the controller name they can perform that action on. You can pass :access and :all
|
||||
# to represent any action and controller respectively. Passing an array to either of
|
||||
# these will grant permission on each item in the array.
|
||||
#
|
||||
# See the wiki for details: https://github.com/ryanb/cancan/wiki/Defining-Abilities
|
||||
end
|
||||
end
|
||||
16
lib/generators/cancan/ability/templates/ability_spec.rb
Normal file
16
lib/generators/cancan/ability/templates/ability_spec.rb
Normal file
@@ -0,0 +1,16 @@
|
||||
require "spec_helper"
|
||||
require "cancan/matchers"
|
||||
|
||||
describe Ability do
|
||||
describe "as guest" do
|
||||
before(:each) do
|
||||
@ability = Ability.new(nil)
|
||||
end
|
||||
|
||||
it "can only create a user" do
|
||||
# Define what a guest can and cannot do
|
||||
# @ability.should be_able_to(:create, :users)
|
||||
# @ability.should_not be_able_to(:update, :users)
|
||||
end
|
||||
end
|
||||
end
|
||||
10
lib/generators/cancan/ability/templates/ability_test.rb
Normal file
10
lib/generators/cancan/ability/templates/ability_test.rb
Normal file
@@ -0,0 +1,10 @@
|
||||
require "test_helper"
|
||||
|
||||
class AbilityTest < ActiveSupport::TestCase
|
||||
def guest_can_only_create_user
|
||||
ability = Ability.new(nil)
|
||||
# Define what a guest can and cannot do
|
||||
# assert ability.can?(:create, :users)
|
||||
# assert ability.cannot?(:update, :users)
|
||||
end
|
||||
end
|
||||
28
spec/README.rdoc
Normal file
28
spec/README.rdoc
Normal file
@@ -0,0 +1,28 @@
|
||||
= CanCan Specs
|
||||
|
||||
== Running the specs
|
||||
|
||||
To run the specs first run the +bundle+ command to install the necessary gems and the +rake+ command to run the specs.
|
||||
|
||||
bundle
|
||||
rake
|
||||
|
||||
The specs currently require Ruby 1.8.7. Ruby 1.9.2 support will be coming soon.
|
||||
|
||||
|
||||
== Model Adapters
|
||||
|
||||
CanCan offers separate specs for different model adapters (such as Mongoid and Data Mapper). By default it will use Active Record but you can change this by setting the +MODEL_ADAPTER+ environment variable before running. You can run the +bundle+ command with this as well to ensure you have the installed gems.
|
||||
|
||||
MODEL_ADAPTER=data_mapper bundle
|
||||
MODEL_ADAPTER=data_mapper rake
|
||||
|
||||
The different model adapters you can specify are:
|
||||
|
||||
* active_record (default)
|
||||
* data_mapper
|
||||
* mongoid
|
||||
|
||||
You can also run the +spec_all+ rake task to run specs for each adapter.
|
||||
|
||||
rake spec_all
|
||||
@@ -5,187 +5,537 @@ describe CanCan::Ability do
|
||||
@ability = Object.new
|
||||
@ability.extend(CanCan::Ability)
|
||||
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
|
||||
|
||||
|
||||
# Basic Action & Subject
|
||||
|
||||
it "allows access to only what is defined" do
|
||||
@ability.can?(:paint, :fences).should be_false
|
||||
@ability.can :paint, :fences
|
||||
@ability.can?(:paint, :fences).should be_true
|
||||
@ability.can?(:wax, :fences).should be_false
|
||||
@ability.can?(:paint, :cars).should be_false
|
||||
end
|
||||
|
||||
it "should not have permission to do something it doesn't know about" do
|
||||
@ability.can?(:foodfight, String).should be_false
|
||||
|
||||
it "allows access to everything when :access, :all is used" do
|
||||
@ability.can?(:paint, :fences).should be_false
|
||||
@ability.can :access, :all
|
||||
@ability.can?(:paint, :fences).should be_true
|
||||
@ability.can?(:wax, :fences).should be_true
|
||||
@ability.can?(:paint, :cars).should be_true
|
||||
end
|
||||
|
||||
it "should return what block returns on a can call" do
|
||||
@ability.can :read, :all
|
||||
@ability.can :read, Symbol do |sym|
|
||||
sym
|
||||
end
|
||||
@ability.can?(:read, Symbol).should be_nil
|
||||
@ability.can?(:read, :some_symbol).should == :some_symbol
|
||||
|
||||
it "allows access to multiple actions and subjects" do
|
||||
@ability.can [:paint, :sand], [:fences, :decks]
|
||||
@ability.can?(:paint, :fences).should be_true
|
||||
@ability.can?(:sand, :fences).should be_true
|
||||
@ability.can?(:paint, :decks).should be_true
|
||||
@ability.can?(:sand, :decks).should be_true
|
||||
@ability.can?(:wax, :fences).should be_false
|
||||
@ability.can?(:paint, :cars).should be_false
|
||||
end
|
||||
|
||||
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?(:preview, 123).should == [Fixnum, 123]
|
||||
|
||||
it "allows strings instead of symbols in ability check" do
|
||||
@ability.can :paint, :fences
|
||||
@ability.can?("paint", "fences").should be_true
|
||||
end
|
||||
|
||||
it "should pass class with no object if :all objects are accepted and class is passed directly" do
|
||||
@ability.can :preview, :all do |object_class, object|
|
||||
[object_class, object]
|
||||
end
|
||||
@ability.can?(:preview, Hash).should == [Hash, nil]
|
||||
|
||||
|
||||
# Aliases
|
||||
|
||||
it "has default index, show, new, update, delete aliases" do
|
||||
@ability.can :read, :projects
|
||||
@ability.can?(:index, :projects).should be_true
|
||||
@ability.can?(:show, :projects).should be_true
|
||||
@ability.can :create, :projects
|
||||
@ability.can?(:new, :projects).should be_true
|
||||
@ability.can :update, :projects
|
||||
@ability.can?(:edit, :projects).should be_true
|
||||
@ability.can :destroy, :projects
|
||||
@ability.can?(:delete, :projects).should be_true
|
||||
end
|
||||
|
||||
it "should pass action and object for global manage actions" do
|
||||
@ability.can :manage, Array do |action, object|
|
||||
[action, object]
|
||||
end
|
||||
@ability.can?(:stuff, [1, 2]).should == [:stuff, [1, 2]]
|
||||
@ability.can?(:stuff, Array).should == [:stuff, nil]
|
||||
end
|
||||
|
||||
it "should alias update or destroy actions to modify action" do
|
||||
|
||||
it "follows deep action aliases" do
|
||||
@ability.alias_action :update, :destroy, :to => :modify
|
||||
@ability.can(:modify, :all) { :modify_called }
|
||||
@ability.can?(:update, 123).should == :modify_called
|
||||
@ability.can?(:destroy, 123).should == :modify_called
|
||||
@ability.can :modify, :projects
|
||||
@ability.can?(:update, :projects).should be_true
|
||||
@ability.can?(:destroy, :projects).should be_true
|
||||
@ability.can?(:edit, :projects).should be_true
|
||||
end
|
||||
|
||||
it "should return block result for action, object_class, and object for any action" do
|
||||
@ability.can :manage, :all do |action, object_class, object|
|
||||
[action, object_class, object]
|
||||
end
|
||||
@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) { :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, Array]
|
||||
@ability.can?(:update, "foo").should be_true
|
||||
@ability.can?(:update, []).should be_true
|
||||
@ability.can?(:update, 123).should be_false
|
||||
end
|
||||
|
||||
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 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 support block on 'cannot' method" do
|
||||
@ability.can :read, :all
|
||||
@ability.cannot :read, Integer do |int|
|
||||
int > 5
|
||||
end
|
||||
@ability.can?(:read, "foo").should be_true
|
||||
@ability.can?(:read, 3).should be_true
|
||||
@ability.can?(:read, 123).should be_false
|
||||
end
|
||||
|
||||
it "should append aliased actions" do
|
||||
|
||||
it "adds up action aliases" do
|
||||
@ability.alias_action :update, :to => :modify
|
||||
@ability.alias_action :destroy, :to => :modify
|
||||
@ability.aliased_actions[:modify].should == [:update, :destroy]
|
||||
@ability.can :modify, :projects
|
||||
@ability.can?(:update, :projects).should be_true
|
||||
@ability.can?(:destroy, :projects).should be_true
|
||||
end
|
||||
|
||||
it "should clear aliased actions" do
|
||||
@ability.alias_action :update, :to => :modify
|
||||
@ability.clear_aliased_actions
|
||||
@ability.aliased_actions[:modify].should be_nil
|
||||
|
||||
it "follows deep subject aliases" do
|
||||
@ability.alias_subject :mammals, :to => :animals
|
||||
@ability.alias_subject :cats, :to => :mammals
|
||||
@ability.can :pet, :animals
|
||||
@ability.can?(:pet, :mammals).should be_true
|
||||
end
|
||||
|
||||
it "should pass additional arguments to block from can?" do
|
||||
@ability.can :read, Integer do |int, x|
|
||||
int > x
|
||||
|
||||
it "clears current and default aliases" do
|
||||
@ability.alias_action :update, :destroy, :to => :modify
|
||||
@ability.clear_aliases
|
||||
@ability.can :modify, :projects
|
||||
@ability.can?(:update, :projects).should be_false
|
||||
@ability.can :read, :projects
|
||||
@ability.can?(:show, :projects).should be_false
|
||||
end
|
||||
|
||||
|
||||
# Hash Conditions
|
||||
|
||||
it "maps object to pluralized subject name" do
|
||||
@ability.can :read, :ranges
|
||||
@ability.can?(:read, :ranges).should be_true
|
||||
@ability.can?(:read, 1..3).should be_true
|
||||
@ability.can?(:read, 123).should be_false
|
||||
end
|
||||
|
||||
it "checks conditions hash on instances only" do
|
||||
@ability.can :read, :ranges, :begin => 1
|
||||
@ability.can?(:read, :ranges).should be_true
|
||||
@ability.can?(:read, 1..3).should be_true
|
||||
@ability.can?(:read, 2..4).should be_false
|
||||
end
|
||||
|
||||
it "checks conditions on both rules and matches either one" do
|
||||
@ability.can :read, :ranges, :begin => 1
|
||||
@ability.can :read, :ranges, :begin => 2
|
||||
@ability.can?(:read, 1..3).should be_true
|
||||
@ability.can?(:read, 2..4).should be_true
|
||||
@ability.can?(:read, 3..5).should be_false
|
||||
end
|
||||
|
||||
it "checks an array of options in conditions hash" do
|
||||
@ability.can :read, :ranges, :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 "checks a range of options in conditions hash" do
|
||||
@ability.can :read, :ranges, :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 "checks nested conditions hash" do
|
||||
@ability.can :read, :ranges, :begin => { :to_i => 5 }
|
||||
@ability.can?(:read, 5..7).should be_true
|
||||
@ability.can?(:read, 6..8).should be_false
|
||||
end
|
||||
|
||||
it "matches any element passed in to nesting if it's an array (for has_many associations)" do
|
||||
@ability.can :read, :ranges, :to_a => { :to_i => 3 }
|
||||
@ability.can?(:read, 1..5).should be_true
|
||||
@ability.can?(:read, 4..6).should be_false
|
||||
end
|
||||
|
||||
it "takes presedence over rule defined without a condition" do
|
||||
@ability.can :read, :ranges
|
||||
@ability.can :read, :ranges, :begin => 1
|
||||
@ability.can?(:read, 1..5).should be_true
|
||||
@ability.can?(:read, 4..6).should be_false
|
||||
end
|
||||
|
||||
|
||||
# Block Conditions
|
||||
|
||||
it "executes block passing object only when instance is used" do
|
||||
@ability.can :read, :ranges do |range|
|
||||
range.begin == 5
|
||||
end
|
||||
@ability.can?(:read, 2, 1).should be_true
|
||||
@ability.can?(:read, 2, 3).should be_false
|
||||
@ability.can?(:read, :ranges).should be_true
|
||||
@ability.can?(:read, 5..7).should be_true
|
||||
@ability.can?(:read, 6..8).should be_false
|
||||
end
|
||||
|
||||
it "should use conditions as third parameter and determine abilities from it" do
|
||||
@ability.can :read, Array, :first => 1, :last => 3
|
||||
@ability.can?(:read, [1, 2, 3]).should be_true
|
||||
@ability.can?(:read, [1, 2, 3, 4]).should be_false
|
||||
@ability.can?(:read, Array).should be_true
|
||||
end
|
||||
|
||||
it "should allow an array of options in conditions hash" do
|
||||
@ability.can :read, Array, :first => [1, 3, 5]
|
||||
@ability.can?(:read, [1, 2, 3]).should be_true
|
||||
@ability.can?(:read, [2, 3]).should be_false
|
||||
@ability.can?(:read, [3, 4]).should be_true
|
||||
end
|
||||
|
||||
it "should allow a range of options in conditions hash" do
|
||||
@ability.can :read, Array, :first => 1..3
|
||||
@ability.can?(:read, [1, 2, 3]).should be_true
|
||||
@ability.can?(:read, [3, 4]).should be_true
|
||||
@ability.can?(:read, [4, 5]).should be_false
|
||||
end
|
||||
|
||||
it "should allow nested hashes in conditions hash" do
|
||||
@ability.can :read, Array, :first => { :length => 5 }
|
||||
@ability.can?(:read, ["foo", "bar"]).should be_false
|
||||
@ability.can?(:read, ["test1", "foo"]).should be_true
|
||||
end
|
||||
|
||||
it "should return conditions for a given ability" do
|
||||
@ability.can :read, Array, :first => 1, :last => 3
|
||||
@ability.conditions(:show, Array).should == {:first => 1, :last => 3}
|
||||
end
|
||||
|
||||
it "should raise an exception when a block is used on condition" do
|
||||
@ability.can :read, Array do |a|
|
||||
true
|
||||
|
||||
it "returns true when other object is returned in block" do
|
||||
@ability.can :read, :ranges do |range|
|
||||
"foo"
|
||||
end
|
||||
lambda { @ability.conditions(:show, Array) }.should raise_error(CanCan::Error, "Cannot determine ability conditions from block for :show Array")
|
||||
@ability.can?(:read, 5..7).should be_true
|
||||
end
|
||||
|
||||
it "should return an empty hash for conditions when there are no conditions" do
|
||||
@ability.can :read, Array
|
||||
@ability.conditions(:show, Array).should == {}
|
||||
|
||||
it "passes to previous rule when block returns false" do
|
||||
@ability.can :read, :fixnums do |i|
|
||||
i < 5
|
||||
end
|
||||
@ability.can :read, :fixnums do |i|
|
||||
i > 10
|
||||
end
|
||||
@ability.can?(:read, 11).should be_true
|
||||
@ability.can?(:read, 1).should be_true
|
||||
@ability.can?(:read, 6).should be_false
|
||||
end
|
||||
|
||||
it "should return false when performed on an action which isn't defined" do
|
||||
@ability.conditions(:foo, Array).should == false
|
||||
|
||||
it "calls block passing arguments when no arguments are given to can" do
|
||||
@ability.can do |action, subject, object|
|
||||
action.should == :read
|
||||
subject.should == :ranges
|
||||
object.should == (2..4)
|
||||
@block_called = true
|
||||
end
|
||||
@ability.can?(:read, 2..4)
|
||||
@block_called.should be_true
|
||||
end
|
||||
|
||||
it "raises 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, :ranges, :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 ranges ability. Use either one.")
|
||||
end
|
||||
|
||||
it "does not raise an error when attempting to use a block with an array of SQL conditions" do
|
||||
lambda {
|
||||
@ability.can :read, :ranges, ["published = ?", true] do
|
||||
false
|
||||
end
|
||||
}.should_not raise_error(CanCan::Error)
|
||||
end
|
||||
|
||||
|
||||
# Attributes
|
||||
|
||||
it "allows permission on attributes" do
|
||||
@ability.can :update, :users, :name
|
||||
@ability.can :update, :users, [:email, :age]
|
||||
@ability.can?(:update, :users, :name).should be_true
|
||||
@ability.can?(:update, :users, :email).should be_true
|
||||
@ability.can?(:update, :users, :password).should be_false
|
||||
end
|
||||
|
||||
it "allows permission on all attributes when none are given" do
|
||||
@ability.can :update, :users
|
||||
@ability.can?(:update, :users, :password).should be_true
|
||||
end
|
||||
|
||||
it "allows strings when chekcing attributes" do
|
||||
@ability.can :update, :users, :name
|
||||
@ability.can?(:update, :users, "name").should be_true
|
||||
end
|
||||
|
||||
it "combines attribute check with conditions hash" do
|
||||
@ability.can :update, :ranges, :begin => 1
|
||||
@ability.can :update, :ranges, :name, :begin => 2
|
||||
@ability.can?(:update, 1..3, :foobar).should be_true
|
||||
@ability.can?(:update, 2..4, :foobar).should be_false
|
||||
@ability.can?(:update, 2..4, :name).should be_true
|
||||
@ability.can?(:update, 3..5, :name).should be_false
|
||||
end
|
||||
|
||||
it "passes attribute to block and nil if no attribute checked" do
|
||||
@ability.can :update, :ranges do |range, attribute|
|
||||
attribute == :name
|
||||
end
|
||||
@ability.can?(:update, 1..3, :name).should be_true
|
||||
@ability.can?(:update, 2..4).should be_false
|
||||
end
|
||||
|
||||
it "passes attribute to block for global can definition" do
|
||||
@ability.can do |action, subject, object, attribute|
|
||||
attribute == :name
|
||||
end
|
||||
@ability.can?(:update, 1..3, :name).should be_true
|
||||
@ability.can?(:update, 2..4).should be_false
|
||||
end
|
||||
|
||||
|
||||
# Checking if Fully Authorized
|
||||
|
||||
it "is not fully authorized when no authorize! call is made" do
|
||||
@ability.can :update, :ranges, :begin => 1
|
||||
@ability.can?(:update, :ranges).should be_true
|
||||
@ability.should_not be_fully_authorized(:update, :ranges)
|
||||
end
|
||||
|
||||
it "is fully authorized when calling authorize! with a matching action and subject" do
|
||||
@ability.can :update, :ranges
|
||||
@ability.authorize! :update, :ranges
|
||||
@ability.should be_fully_authorized(:update, :ranges)
|
||||
@ability.should_not be_fully_authorized(:create, :ranges)
|
||||
end
|
||||
|
||||
it "is fully authorized when marking action and subject as such" do
|
||||
@ability.fully_authorized! :update, :ranges
|
||||
@ability.should be_fully_authorized(:update, :ranges)
|
||||
end
|
||||
|
||||
it "is not fully authorized when a conditions hash exists but no instance is used" do
|
||||
@ability.can :update, :ranges, :begin => 1
|
||||
@ability.authorize! :update, :ranges
|
||||
@ability.should_not be_fully_authorized(:update, :ranges)
|
||||
@ability.authorize! "update", "ranges"
|
||||
@ability.should_not be_fully_authorized(:update, :ranges)
|
||||
@ability.authorize! :update, 1..3
|
||||
@ability.should be_fully_authorized(:update, :ranges)
|
||||
end
|
||||
|
||||
it "is not fully authorized when a block exists but no instance is used" do
|
||||
@ability.can :update, :ranges do |range|
|
||||
range.begin == 1
|
||||
end
|
||||
@ability.authorize! :update, :ranges
|
||||
@ability.should_not be_fully_authorized(:update, :ranges)
|
||||
@ability.authorize! :update, 1..3
|
||||
@ability.should be_fully_authorized(:update, :ranges)
|
||||
end
|
||||
|
||||
it "should accept a set as a condition value" do
|
||||
object_with_foo_2 = Object.new
|
||||
object_with_foo_2.should_receive(:foo) { 2 }
|
||||
object_with_foo_3 = Object.new
|
||||
object_with_foo_3.should_receive(:foo) { 3 }
|
||||
@ability.can :read, :objects, :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 "does not match subjects return nil for methods that must match nested a nested conditions hash" do
|
||||
object_with_foo = Object.new
|
||||
object_with_foo.should_receive(:foo) { :bar }
|
||||
@ability.can :read, :arrays, :first => { :foo => :bar }
|
||||
@ability.can?(:read, [object_with_foo]).should be_true
|
||||
@ability.can?(:read, []).should be_false
|
||||
end
|
||||
|
||||
it "is not fully authorized when attributes are required but not checked in update/create actions" do
|
||||
@ability.can :access, :users, :name
|
||||
@ability.authorize! :update, :users
|
||||
@ability.should_not be_fully_authorized(:update, :users)
|
||||
@ability.authorize! :create, :users
|
||||
@ability.should_not be_fully_authorized(:create, :users)
|
||||
@ability.authorize! :create, :users, :name
|
||||
@ability.should be_fully_authorized(:create, :users)
|
||||
@ability.authorize! :destroy, :users
|
||||
@ability.should be_fully_authorized(:destroy, :users)
|
||||
end
|
||||
|
||||
it "marks as fully authorized when authorizing with strings instead of symbols" do
|
||||
@ability.fully_authorized! "update", "ranges"
|
||||
@ability.should be_fully_authorized(:update, :ranges)
|
||||
@ability.should be_fully_authorized("update", "ranges")
|
||||
@ability.can :update, :users
|
||||
@ability.authorize! "update", "users"
|
||||
@ability.should be_fully_authorized(:update, :users)
|
||||
end
|
||||
|
||||
|
||||
# Cannot
|
||||
|
||||
it "offers cannot? method which inverts can?" do
|
||||
@ability.cannot?(:wax, :cars).should be_true
|
||||
end
|
||||
|
||||
it "supports 'cannot' method to define what user cannot do" do
|
||||
@ability.can :read, :all
|
||||
@ability.cannot :read, :ranges
|
||||
@ability.can?(:read, :books).should be_true
|
||||
@ability.can?(:read, 1..3).should be_false
|
||||
@ability.can?(:read, :ranges).should be_false
|
||||
end
|
||||
|
||||
it "passes to previous rule if cannot check returns false" do
|
||||
@ability.can :read, :all
|
||||
@ability.cannot :read, :ranges, :begin => 3
|
||||
@ability.cannot :read, :ranges do |range|
|
||||
range.begin == 5
|
||||
end
|
||||
@ability.can?(:read, :books).should be_true
|
||||
@ability.can?(:read, 2..4).should be_true
|
||||
@ability.can?(:read, 3..7).should be_false
|
||||
@ability.can?(:read, 5..9).should be_false
|
||||
end
|
||||
|
||||
it "rejects permission only to a given attribute" do
|
||||
@ability.can :update, :books
|
||||
@ability.cannot :update, :books, :author
|
||||
@ability.can?(:update, :books).should be_true
|
||||
@ability.can?(:update, :books, :author).should be_false
|
||||
end
|
||||
|
||||
# Hash Association
|
||||
|
||||
it "checks permission through association when hash is passed as subject" do
|
||||
@ability.can :read, :books, :range => {:begin => 3}
|
||||
@ability.can?(:read, (1..4) => :books).should be_false
|
||||
@ability.can?(:read, (3..5) => :books).should be_true
|
||||
@ability.can?(:read, 123 => :books).should be_true
|
||||
end
|
||||
|
||||
it "checks permissions on association hash with multiple rules" do
|
||||
@ability.can :read, :books, :range => {:begin => 3}
|
||||
@ability.can :read, :books, :range => {:end => 6}
|
||||
@ability.can?(:read, (1..4) => :books).should be_false
|
||||
@ability.can?(:read, (3..5) => :books).should be_true
|
||||
@ability.can?(:read, (1..6) => :books).should be_true
|
||||
@ability.can?(:read, 123 => :books).should be_true
|
||||
end
|
||||
|
||||
it "checks ability on hash subclass" do
|
||||
class Container < Hash; end
|
||||
@ability.can :read, :containers
|
||||
@ability.can?(:read, Container.new).should be_true
|
||||
end
|
||||
|
||||
|
||||
# Initial Attributes
|
||||
|
||||
it "has initial attributes based on hash conditions for a given action" do
|
||||
@ability.can :access, :ranges, :foo => "foo", :hash => {:skip => "hashes"}
|
||||
@ability.can :create, :ranges, :bar => 123, :array => %w[skip arrays]
|
||||
@ability.can :new, :ranges, :baz => "baz", :range => 1..3
|
||||
@ability.cannot :new, :ranges, :ignore => "me"
|
||||
@ability.attributes_for(:new, :ranges).should == {:foo => "foo", :bar => 123, :baz => "baz"}
|
||||
end
|
||||
|
||||
|
||||
# Unauthorized Exception
|
||||
|
||||
it "raises CanCan::Unauthorized when calling authorize! on unauthorized action" do
|
||||
begin
|
||||
@ability.authorize! :read, :books, :message => "Access denied!"
|
||||
rescue CanCan::Unauthorized => e
|
||||
e.message.should == "Access denied!"
|
||||
e.action.should == :read
|
||||
e.subject.should == :books
|
||||
else
|
||||
fail "Expected CanCan::Unauthorized exception to be raised"
|
||||
end
|
||||
end
|
||||
|
||||
it "does 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 "knows 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 "knows 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 "raises access denied exception with default message if not specified" do
|
||||
begin
|
||||
@ability.authorize! :read, :books
|
||||
rescue CanCan::Unauthorized => e
|
||||
e.default_message = "Access denied!"
|
||||
e.message.should == "Access denied!"
|
||||
else
|
||||
fail "Expected CanCan::Unauthorized exception to be raised"
|
||||
end
|
||||
end
|
||||
|
||||
it "does not raise access denied exception if ability is authorized to perform an action and return subject" do
|
||||
@ability.can :read, :books
|
||||
lambda {
|
||||
@ability.authorize!(:read, :books).should == :books
|
||||
}.should_not raise_error
|
||||
end
|
||||
|
||||
|
||||
# Determining Kind of Conditions
|
||||
|
||||
it "knows when a block is used for conditions" do
|
||||
@ability.can :read, :books
|
||||
@ability.should_not have_block(:read, :books)
|
||||
@ability.can :read, :books do |foo|
|
||||
false
|
||||
end
|
||||
@ability.should have_block(:read, :books)
|
||||
end
|
||||
|
||||
it "knows when raw sql is used for conditions" do
|
||||
@ability.can :read, :books
|
||||
@ability.should_not have_raw_sql(:read, :books)
|
||||
@ability.can :read, :books, 'false'
|
||||
@ability.should have_raw_sql(:read, :books)
|
||||
end
|
||||
|
||||
it "determines model adapter class by asking AbstractAdapter" do
|
||||
model_class = Object.new
|
||||
adapter_class = Object.new
|
||||
CanCan::ModelAdapters::AbstractAdapter.stub(:adapter_class).with(model_class) { adapter_class }
|
||||
adapter_class.stub(:new).with(model_class, []) { :adapter_instance }
|
||||
@ability.model_adapter(model_class, :read).should == :adapter_instance
|
||||
end
|
||||
|
||||
|
||||
# Unauthorized I18n Message
|
||||
|
||||
describe "unauthorized message" do
|
||||
after(:each) do
|
||||
I18n.backend = nil
|
||||
end
|
||||
|
||||
it "uses action/subject in i18n" do
|
||||
I18n.backend.store_translations :en, :unauthorized => {:update => {:ranges => "update ranges"}}
|
||||
@ability.unauthorized_message(:update, :ranges).should == "update ranges"
|
||||
@ability.unauthorized_message(:update, 2..4).should == "update ranges"
|
||||
@ability.unauthorized_message(:update, :missing).should be_nil
|
||||
end
|
||||
|
||||
it "uses 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 "falls back to 'access' and 'all'" do
|
||||
I18n.backend.store_translations :en, :unauthorized => {
|
||||
:access => {:all => "access all", :ranges => "access ranges"},
|
||||
:update => {:all => "update all", :ranges => "update ranges"}
|
||||
}
|
||||
@ability.unauthorized_message(:update, :ranges).should == "update ranges"
|
||||
@ability.unauthorized_message(:update, :hashes).should == "update all"
|
||||
@ability.unauthorized_message(:create, :ranges).should == "access ranges"
|
||||
@ability.unauthorized_message(:create, :hashes).should == "access all"
|
||||
end
|
||||
|
||||
it "follows aliases" do
|
||||
I18n.backend.store_translations :en, :unauthorized => {:modify => {:ranges => "modify ranges"}}
|
||||
@ability.alias_action :update, :to => :modify
|
||||
@ability.alias_subject :areas, :to => :ranges
|
||||
@ability.unauthorized_message(:update, :areas).should == "modify ranges"
|
||||
@ability.unauthorized_message(:edit, :ranges).should == "modify ranges"
|
||||
end
|
||||
|
||||
it "has variables for action and subject" do
|
||||
I18n.backend.store_translations :en, :unauthorized => {:access => {:all => "%{action} %{subject}"}} # old syntax for now in case testing with old I18n
|
||||
@ability.unauthorized_message(:update, :ranges).should == "update ranges"
|
||||
@ability.unauthorized_message(:edit, 1..3).should == "edit ranges"
|
||||
# @ability.unauthorized_message(:update, ArgumentError).should == "update argument error"
|
||||
end
|
||||
end
|
||||
|
||||
it "merges the rules from another 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
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
require "spec_helper"
|
||||
|
||||
describe CanCan::ActiveRecordAdditions do
|
||||
before(:each) do
|
||||
@model_class = Class.new
|
||||
stub(@model_class).scoped { :scoped_stub }
|
||||
@model_class.send(:include, CanCan::ActiveRecordAdditions)
|
||||
@ability = Object.new
|
||||
@ability.extend(CanCan::Ability)
|
||||
end
|
||||
|
||||
it "should call where(:id => nil) when no ability is defined so no records are found" do
|
||||
stub(@model_class).where(:id => nil) { :no_where }
|
||||
@model_class.accessible_by(@ability, :read).should == :no_where
|
||||
end
|
||||
|
||||
it "should call where with matching ability conditions" do
|
||||
@ability.can :read, @model_class, :foo => 1
|
||||
stub(@model_class).where(:foo => 1) { :found_records }
|
||||
@model_class.accessible_by(@ability, :read).should == :found_records
|
||||
end
|
||||
|
||||
it "should default to :read ability and use scoped when where isn't available" do
|
||||
@ability.can :read, @model_class, :foo => 1
|
||||
stub(@model_class).scoped(:conditions => {:foo => 1}) { :found_records }
|
||||
@model_class.accessible_by(@ability).should == :found_records
|
||||
end
|
||||
end
|
||||
@@ -2,71 +2,117 @@ require "spec_helper"
|
||||
|
||||
describe CanCan::ControllerAdditions do
|
||||
before(:each) do
|
||||
@params = HashWithIndifferentAccess.new
|
||||
@controller_class = Class.new
|
||||
@controller = @controller_class.new
|
||||
stub(@controller).params { {} }
|
||||
stub(@controller).current_user { :current_user }
|
||||
mock(@controller_class).helper_method(:can?, :cannot?)
|
||||
@controller.stub(:params) { @params }
|
||||
@controller.stub(:current_user) { :current_user }
|
||||
@controller_class.should_receive(:helper_method).with(:can?, :cannot?, :current_ability)
|
||||
@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 "raises ImplementationRemoved when attempting to call load/authorize/skip/check calls on a controller" do
|
||||
lambda { @controller_class.load_resource }.should raise_error(CanCan::ImplementationRemoved)
|
||||
lambda { @controller_class.authorize_resource }.should raise_error(CanCan::ImplementationRemoved)
|
||||
lambda { @controller_class.skip_load_resource }.should raise_error(CanCan::ImplementationRemoved)
|
||||
lambda { @controller_class.skip_authorize_resource }.should raise_error(CanCan::ImplementationRemoved)
|
||||
lambda { @controller_class.check_authorization }.should raise_error(CanCan::ImplementationRemoved)
|
||||
lambda { @controller_class.skip_authorization_check }.should raise_error(CanCan::ImplementationRemoved)
|
||||
lambda { @controller_class.cancan_skipper }.should raise_error(CanCan::ImplementationRemoved)
|
||||
end
|
||||
|
||||
it "should raise access denied exception if ability us unauthorized to perform a certain action" do
|
||||
begin
|
||||
@controller.authorize! :read, :foo, 1, 2, 3, :message => "Access denied!"
|
||||
rescue CanCan::AccessDenied => e
|
||||
e.message.should == "Access denied!"
|
||||
e.action.should == :read
|
||||
e.subject.should == :foo
|
||||
else
|
||||
fail "Expected CanCan::AccessDenied exception to be raised"
|
||||
end
|
||||
|
||||
it "authorize! should pass args to current ability" do
|
||||
@controller.current_ability.should_receive(:authorize!).with(:foo, :bar)
|
||||
@controller.authorize!(:foo, :bar)
|
||||
end
|
||||
|
||||
it "should not raise access denied exception if ability is authorized to perform an action" do
|
||||
@controller.current_ability.can :read, :foo
|
||||
lambda { @controller.authorize!(:read, :foo) }.should_not raise_error
|
||||
end
|
||||
|
||||
it "should raise access denied exception with default message if not specified" do
|
||||
begin
|
||||
@controller.authorize! :read, :foo
|
||||
rescue CanCan::AccessDenied => e
|
||||
e.default_message = "Access denied!"
|
||||
e.message.should == "Access denied!"
|
||||
else
|
||||
fail "Expected CanCan::AccessDenied exception to be raised"
|
||||
end
|
||||
end
|
||||
|
||||
it "should have a current_ability method which generates an ability for the current user" do
|
||||
@controller.current_ability.should be_kind_of(Ability)
|
||||
end
|
||||
|
||||
it "should provide a can? and cannot? methods which go through the current ability" do
|
||||
|
||||
it "provides a can? and cannot? methods which go through the current ability" do
|
||||
@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 ResourceAuthorization" do
|
||||
stub(CanCan::ResourceAuthorization).new(@controller, @controller.params, :foo => :bar).mock!.load_and_authorize_resource
|
||||
mock(@controller_class).before_filter({}) { |options, block| block.call(@controller) }
|
||||
|
||||
it "load_and_authorize_resource adds a before filter which passes call to ControllerResource" do
|
||||
controller_resource = double("controller_resource")
|
||||
controller_resource.should_receive(:process)
|
||||
CanCan::ControllerResource.stub(:new).with(@controller, nil, :load => true, :authorize => true, :foo => :bar) { controller_resource }
|
||||
@controller_class.should_receive(:before_filter).with({}).and_yield(@controller)
|
||||
@controller_class.load_and_authorize_resource :foo => :bar
|
||||
end
|
||||
|
||||
it "authorize_resource should setup a before filter which passes call to ResourceAuthorization" do
|
||||
stub(CanCan::ResourceAuthorization).new(@controller, @controller.params, :foo => :bar).mock!.authorize_resource
|
||||
mock(@controller_class).before_filter(:except => :show) { |options, block| block.call(@controller) }
|
||||
@controller_class.authorize_resource :foo => :bar, :except => :show
|
||||
|
||||
it "load_and_authorize_resource passes first argument as the resource name" do
|
||||
controller_resource = double("controller_resource")
|
||||
controller_resource.should_receive(:process)
|
||||
CanCan::ControllerResource.stub(:new).with(@controller, :project, :load => true, :authorize => true, :foo => :bar) { controller_resource }
|
||||
@controller_class.should_receive(:before_filter).with({}).and_yield(@controller)
|
||||
@controller_class.load_and_authorize_resource :project, :foo => :bar
|
||||
end
|
||||
|
||||
it "load_resource should setup a before filter which passes call to ResourceAuthorization" do
|
||||
stub(CanCan::ResourceAuthorization).new(@controller, @controller.params, :foo => :bar).mock!.load_resource
|
||||
mock(@controller_class).before_filter(:only => [:show, :index]) { |options, block| block.call(@controller) }
|
||||
@controller_class.load_resource :foo => :bar, :only => [:show, :index]
|
||||
|
||||
it "load_and_authorize_resource passes :only, :except, :if, :unless options to before filter" do
|
||||
controller_resource = double("controller_resource")
|
||||
controller_resource.should_receive(:process)
|
||||
CanCan::ControllerResource.stub(:new).with(@controller, nil, :load => true, :authorize => true) { controller_resource }
|
||||
@controller_class.should_receive(:before_filter).with(:only => 1, :except => 2, :if => 3, :unless => 4).and_yield(@controller)
|
||||
@controller_class.load_and_authorize_resource :only => 1, :except => 2, :if => 3, :unless => 4
|
||||
end
|
||||
|
||||
it "load_and_authorize_resource with :prepend prepends the before filter" do
|
||||
@controller_class.should_receive(:prepend_before_filter).with({})
|
||||
@controller_class.load_and_authorize_resource :foo => :bar, :prepend => true
|
||||
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
|
||||
@controller.class.stub(:ancestors) { ["InheritedResources::Actions"] }
|
||||
@controller.class.cancan_resource_class.should == CanCan::InheritedResource
|
||||
end
|
||||
|
||||
it "enable_authorization should call authorize! with controller and action name" do
|
||||
@params.merge!(:controller => "projects", :action => "create")
|
||||
@controller.should_receive(:authorize!).with("create", "projects")
|
||||
@controller_class.stub(:before_filter).with(:only => :foo, :except => :bar).and_yield(@controller)
|
||||
@controller_class.stub(:after_filter).with(:only => :foo, :except => :bar)
|
||||
@controller_class.enable_authorization(:only => :foo, :except => :bar)
|
||||
end
|
||||
|
||||
it "enable_authorization should raise InsufficientAuthorizationCheck when not fully authoried" do
|
||||
@params.merge!(:controller => "projects", :action => "create")
|
||||
@controller_class.stub(:before_filter).with(:only => :foo, :except => :bar)
|
||||
@controller_class.stub(:after_filter).with(:only => :foo, :except => :bar).and_yield(@controller)
|
||||
lambda {
|
||||
@controller_class.enable_authorization(:only => :foo, :except => :bar)
|
||||
}.should raise_error(CanCan::InsufficientAuthorizationCheck)
|
||||
end
|
||||
|
||||
it "enable_authorization should not call authorize! when :if is false" do
|
||||
@authorize_called = false
|
||||
@controller.stub(:authorize?) { false }
|
||||
@controller.stub(:authorize!) { @authorize_called = true }
|
||||
@controller_class.should_receive(:before_filter).with({}).and_yield(@controller)
|
||||
@controller_class.should_receive(:after_filter).with({}).and_yield(@controller)
|
||||
@controller_class.enable_authorization(:if => :authorize?)
|
||||
@authorize_called.should be_false
|
||||
end
|
||||
|
||||
it "enable_authorization should not call authorize! when :unless is true" do
|
||||
@authorize_called = false
|
||||
@controller.stub(:engine_controller?) { true }
|
||||
@controller.stub(:authorize!) { @authorize_called = true }
|
||||
@controller_class.should_receive(:before_filter).with({}).and_yield(@controller)
|
||||
@controller_class.should_receive(:after_filter).with({}).and_yield(@controller)
|
||||
@controller_class.enable_authorization(:unless => :engine_controller?)
|
||||
@authorize_called.should be_false
|
||||
end
|
||||
|
||||
it "enable_authorization should pass block to rescue_from CanCan::Unauthorized call" do
|
||||
@block_called = false
|
||||
@controller_class.should_receive(:before_filter).with({})
|
||||
@controller_class.should_receive(:after_filter).with({})
|
||||
@controller_class.should_receive(:rescue_from).with(CanCan::Unauthorized).and_yield(:exception)
|
||||
@controller_class.enable_authorization { |e| @block_called = (e == :exception) }
|
||||
@block_called.should be_true
|
||||
end
|
||||
end
|
||||
|
||||
@@ -2,58 +2,550 @@ require "spec_helper"
|
||||
|
||||
describe CanCan::ControllerResource do
|
||||
before(:each) do
|
||||
@controller = Object.new
|
||||
Project.delete_all
|
||||
Category.delete_all
|
||||
@params = HashWithIndifferentAccess.new(:controller => "projects")
|
||||
@controller_class = Class.new
|
||||
@controller = @controller_class.new
|
||||
@ability = Ability.new(nil)
|
||||
@controller.stub(:params) { @params }
|
||||
@controller.stub(:current_ability) { @ability }
|
||||
@controller.stub(:authorize!) { |*args| @ability.authorize!(*args) }
|
||||
# @controller_class.stub(:cancan_skipper) { {:authorize => {}, :load => {}} }
|
||||
end
|
||||
|
||||
it "should determine model class by constantizing give name" do
|
||||
CanCan::ControllerResource.new(@controller, :ability).model_class.should == Ability
|
||||
|
||||
it "loads the resource into an instance variable if params[:id] is specified" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "should fetch model through model class and assign it to the instance" do
|
||||
stub(Ability).find(123) { :some_ability }
|
||||
CanCan::ControllerResource.new(@controller, :ability).find(123)
|
||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
||||
|
||||
it "does not load resource into an instance variable if already set" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
@controller.instance_variable_set(:@project, :some_project)
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "should fetch model through parent and assign it to the instance" do
|
||||
parent = Object.new
|
||||
stub(parent).model_instance.stub!.abilities.stub!.find(123) { :some_ability }
|
||||
CanCan::ControllerResource.new(@controller, :ability, parent).find(123)
|
||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
||||
|
||||
it "loads resource for namespaced controller" do
|
||||
project = Project.create!
|
||||
@params.merge!(:controller => "admin/projects", :action => "show", :id => project.id)
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "should build model through model class and assign it to the instance" do
|
||||
stub(Ability).new(123) { :some_ability }
|
||||
CanCan::ControllerResource.new(@controller, :ability).build(123)
|
||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
||||
|
||||
it "attempts to load a resource with the same namespace as the controller when using :: for namespace" do
|
||||
module SomeEngine
|
||||
class Project < ::Project; end
|
||||
end
|
||||
project = SomeEngine::Project.create!
|
||||
@params.merge!(:controller => "SomeEngine::ProjectsController", :action => "show", :id => project.id)
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "should build model through parent and assign it to the instance" do
|
||||
parent = Object.new
|
||||
stub(parent).model_instance.stub!.abilities.stub!.build(123) { :some_ability }
|
||||
CanCan::ControllerResource.new(@controller, :ability, parent).build(123)
|
||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
||||
|
||||
# Rails includes namespace in params, see issue #349
|
||||
it "creates through the namespaced params" do
|
||||
module SomeEngine
|
||||
class Project < ::Project; end
|
||||
end
|
||||
@params.merge!(:controller => "SomeEngine::ProjectsController", :action => "create", :some_engine_project => {:name => "foobar"})
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||
end
|
||||
|
||||
it "should not load resource if instance variable is already provided" do
|
||||
@controller.instance_variable_set(:@ability, :some_ability)
|
||||
CanCan::ControllerResource.new(@controller, :ability).find(123)
|
||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
||||
|
||||
it "loads resource for namespaced controller when using '::' for namespace" do
|
||||
project = Project.create!
|
||||
@params.merge!(:controller => "Admin::ProjectsController", :action => "show", :id => project.id)
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "should use the model class option if provided" do
|
||||
stub(Person).find(123) { :some_resource }
|
||||
CanCan::ControllerResource.new(@controller, :ability, nil, :resource => Person).find(123)
|
||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||
|
||||
it "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")
|
||||
@controller.authorize!(:index, "admin/dashboard")
|
||||
resource = CanCan::ControllerResource.new(@controller, :authorize => true)
|
||||
resource.send(:resource_class).should == Admin::Dashboard
|
||||
end
|
||||
|
||||
it "should convert string to constant for resource" do
|
||||
CanCan::ControllerResource.new(@controller, :ability, nil, :resource => "Person").model_class.should == Person
|
||||
|
||||
it "builds a new resource with hash if params[:id] is not specified and authorize on each attribute" do
|
||||
@params.merge!(:action => "create", :project => {:name => "foobar"})
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||
end
|
||||
|
||||
it "should raise an exception when specifying :class option since it is no longer used" do
|
||||
|
||||
it "builds a new resource for namespaced model with hash if params[:id] is not specified" do
|
||||
module SomeEngine
|
||||
class Project < ::Project; end
|
||||
end
|
||||
@params.merge!(:action => "create", :some_engine_project => {:name => "foobar"})
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :class => SomeEngine::Project).process
|
||||
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||
end
|
||||
|
||||
it "builds a new resource with attributes from current ability" do
|
||||
@params.merge!(:action => "new")
|
||||
@ability.can(:create, :projects, :name => "from conditions")
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).name.should == "from conditions"
|
||||
end
|
||||
|
||||
it "overrides initial attributes with params" do
|
||||
@params.merge!(:action => "new", :project => {:name => "from params"})
|
||||
@ability.can(:create, :projects, :name => "from conditions")
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).name.should == "from params"
|
||||
end
|
||||
|
||||
it "builds a collection when on index action when class responds to accessible_by and mark ability as fully authorized" do
|
||||
Project.stub(:accessible_by).with(@ability, :index) { :found_projects }
|
||||
@params[:action] = "index"
|
||||
CanCan::ControllerResource.new(@controller, :project, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
@controller.instance_variable_get(:@projects).should == :found_projects
|
||||
@ability.should be_fully_authorized(:index, :projects)
|
||||
end
|
||||
|
||||
it "does not build a collection when on index action when class does not respond to accessible_by and not mark ability as fully authorized" do
|
||||
class CustomModel
|
||||
end
|
||||
@params[:controller] = "custom_models"
|
||||
@params[:action] = "index"
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
@controller.instance_variable_defined?(:@projects).should be_false
|
||||
@ability.should_not be_fully_authorized(:index, :projects)
|
||||
end
|
||||
|
||||
it "does not use accessible_by when defining abilities through a block" do
|
||||
Project.stub(:accessible_by).with(@ability) { :found_projects }
|
||||
@params[:action] = "index"
|
||||
@ability.can(:read, :projects) { |p| false }
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
@controller.instance_variable_defined?(:@projects).should be_false
|
||||
end
|
||||
|
||||
it "does not authorize resource in collection action" do
|
||||
@params[:action] = "index"
|
||||
@controller.instance_variable_set(:@project, :some_project)
|
||||
@controller.stub(:authorize!).with(:index, :projects) { raise CanCan::Unauthorized }
|
||||
resource = CanCan::ControllerResource.new(@controller, :authorize => true)
|
||||
lambda { resource.process }.should_not raise_error(CanCan::Unauthorized)
|
||||
end
|
||||
|
||||
it "authorizes parent resource in collection action" do
|
||||
@params[:action] = "index"
|
||||
@controller.instance_variable_set(:@category, :some_category)
|
||||
@controller.stub(:authorize!).with(:show, :some_category) { raise CanCan::Unauthorized }
|
||||
resource = CanCan::ControllerResource.new(@controller, :category, :parent => true, :authorize => true)
|
||||
lambda { resource.process }.should raise_error(CanCan::Unauthorized)
|
||||
end
|
||||
|
||||
it "performs authorization using controller action and loaded model" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
@controller.instance_variable_set(:@project, :some_project)
|
||||
@controller.stub(:authorize!).with(:show, :some_project) { raise CanCan::Unauthorized }
|
||||
resource = CanCan::ControllerResource.new(@controller, :authorize => true)
|
||||
lambda { resource.process }.should raise_error(CanCan::Unauthorized)
|
||||
end
|
||||
|
||||
it "does not perform authorization using controller action when no loaded model" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
@controller.stub(:authorize!).with(:show, :projects) { raise CanCan::Unauthorized }
|
||||
resource = CanCan::ControllerResource.new(@controller, :authorize => true)
|
||||
lambda { resource.process }.should_not raise_error(CanCan::Unauthorized)
|
||||
end
|
||||
|
||||
it "does not build a single resource when on custom collection action even with id" do
|
||||
@params.merge!(:action => "sort", :id => 123)
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :collection => [:sort, :list]).process
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
end
|
||||
|
||||
it "loads a collection resource when on custom action with no id param" do
|
||||
Project.stub(:accessible_by).with(@ability, :sort) { :found_projects }
|
||||
@params[:action] = "sort"
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
@controller.instance_variable_get(:@projects).should == :found_projects
|
||||
end
|
||||
|
||||
it "builds a resource when on custom new action even when params[:id] exists" do
|
||||
@params.merge!(:action => "build", :id => 123)
|
||||
Project.stub(:new) { :some_project }
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :new => :build).process
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "does not try to load resource for other action if params[:id] is undefined" do
|
||||
@params[:action] = "list"
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
end
|
||||
|
||||
it "is 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 "does 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 "is parent if specified in options" do
|
||||
resource = CanCan::ControllerResource.new(@controller, :project, {:parent => true})
|
||||
resource.should be_parent
|
||||
end
|
||||
|
||||
it "does not be parent if specified in options" do
|
||||
resource = CanCan::ControllerResource.new(@controller, :category, {:parent => false})
|
||||
resource.should_not be_parent
|
||||
end
|
||||
|
||||
it "has the specified resource_class if name is passed to load_resource" do
|
||||
resource = CanCan::ControllerResource.new(@controller, :category)
|
||||
resource.send(:resource_class).should == Category
|
||||
end
|
||||
|
||||
it "loads parent resource through proper id parameter" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "index", :project_id => project.id)
|
||||
CanCan::ControllerResource.new(@controller, :project, :load => true, :parent => true).process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "loads resource through the association of another parent resource using instance variable" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
category = double("category", :projects => double("projects"))
|
||||
category.projects.stub(:find).with(123) { :some_project }
|
||||
@controller.instance_variable_set(:@category, category)
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :through => :category).process
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "loads resource through the custom association name" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
category = double("category", :custom_projects => double("custom_projects"))
|
||||
category.custom_projects.stub(:find).with(123) { :some_project }
|
||||
@controller.instance_variable_set(:@category, category)
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :through => :category, :through_association => :custom_projects).process
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "loads resource through the association of another parent resource using method" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
category = double("category", :projects => double("projects"))
|
||||
@controller.stub(:category) { category }
|
||||
category.projects.stub(:find).with(123) { :some_project }
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :through => :category).process
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "does not load through parent resource if instance isn't loaded when shallow" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :through => :category, :shallow => true).process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "raises Unauthorized when attempting to load resource through nil" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
resource = CanCan::ControllerResource.new(@controller, :load => true, :through => :category)
|
||||
lambda {
|
||||
CanCan::ControllerResource.new(@controller, :ability, nil, :class => Person)
|
||||
}.should raise_error(CanCan::ImplementationRemoved)
|
||||
resource.process
|
||||
}.should raise_error(CanCan::Unauthorized) { |exception|
|
||||
exception.action.should == :show
|
||||
exception.subject.should == :projects
|
||||
}
|
||||
@controller.instance_variable_get(:@project).should be_nil
|
||||
end
|
||||
|
||||
it "named resources should be loaded independently of the controller name" do
|
||||
category = Category.create!
|
||||
@params.merge!(:action => "new", :category_id => category.id)
|
||||
CanCan::ControllerResource.new(@controller, :category, :load => true).process
|
||||
CanCan::ControllerResource.new(@controller, :project, :load => true, :through => :category).process
|
||||
@controller.instance_variable_get(:@category).should eq(category)
|
||||
project = @controller.instance_variable_get(:@project)
|
||||
project.category.should eq(category)
|
||||
end
|
||||
|
||||
it "parent resources shouldn't be altered" do
|
||||
category = Category.create!
|
||||
@params.merge!(:action => "create", :category_id => category.id, :project => { :name => 'foo' })
|
||||
CanCan::ControllerResource.new(@controller, :category, :load => true).process
|
||||
CanCan::ControllerResource.new(@controller, :project, :load => true, :through => :category).process
|
||||
project = @controller.instance_variable_get(:@project)
|
||||
project.should be_new_record
|
||||
project.name.should eq('foo')
|
||||
end
|
||||
|
||||
it "does not overrides an attribute if it is based on parent resource" do
|
||||
user = double('user')
|
||||
user.should_receive(:category_id).and_return nil
|
||||
@ability = Ability.new user
|
||||
@ability.can :new, :projects, :category_id => user.category_id
|
||||
category = Category.create!
|
||||
@controller.instance_variable_set(:@category, category)
|
||||
|
||||
@params.merge! :action => 'new', :category_id => category.id
|
||||
CanCan::ControllerResource.new(@controller, :category, :load => true).process
|
||||
CanCan::ControllerResource.new(@controller, :project, :load => true, :through => :category, :singleton => true).process
|
||||
project = @controller.instance_variable_get(:@project)
|
||||
project.category_id.should_not be_nil
|
||||
project.category.should eq(category)
|
||||
end
|
||||
|
||||
it "authorizes nested resource through parent association on index action" do
|
||||
pending
|
||||
@params.merge!(:action => "index")
|
||||
category = Object.new
|
||||
@controller.instance_variable_set(:@category, category)
|
||||
@controller.stub(:authorize!).with(:index, category => :projects) { raise CanCan::Unauthorized }
|
||||
resource = CanCan::ControllerResource.new(@controller, :authorize => true, :through => :category)
|
||||
lambda { resource.process }.should raise_error(CanCan::Unauthorized)
|
||||
end
|
||||
|
||||
it "loads through first matching if multiple are given" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
category = double("category", :projects => double("projects"))
|
||||
category.projects.stub(:find).with(123) { :some_project }
|
||||
@controller.instance_variable_set(:@category, category)
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :through => [:category, :user]).process
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "finds 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)
|
||||
category.stub(:project) { :some_project }
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :through => :category, :singleton => true).process
|
||||
@controller.instance_variable_get(:@project).should == :some_project
|
||||
end
|
||||
|
||||
it "does 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)
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :through => :category, :singleton => true).process
|
||||
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||
@controller.instance_variable_get(:@project).category.should == category
|
||||
end
|
||||
|
||||
it "finds record through has_one association with :singleton and :shallow options" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :through => :category, :singleton => true, :shallow => true).process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "builds record through has_one association with :singleton and :shallow options" do
|
||||
@params.merge!(:action => "create", :project => {:name => "foobar"})
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :through => :category, :singleton => true, :shallow => true).process
|
||||
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||
end
|
||||
|
||||
it "only authorizes :show action on parent resource" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "new", :project_id => project.id)
|
||||
@controller.stub(:authorize!).with(:show, project) { raise CanCan::Unauthorized }
|
||||
resource = CanCan::ControllerResource.new(@controller, :project, :load => true, :authorize => true, :parent => true)
|
||||
lambda { resource.process }.should raise_error(CanCan::Unauthorized)
|
||||
end
|
||||
|
||||
it "authorizes update action before setting attributes" do
|
||||
@ability.can :update, :projects, :name => "bar"
|
||||
project = Project.create!(:name => "foo")
|
||||
@params.merge!(:action => "update", :id => project.id, :project => {:name => "bar"})
|
||||
resource = CanCan::ControllerResource.new(@controller, :project, :load => true, :authorize => true)
|
||||
lambda { resource.process }.should raise_error(CanCan::Unauthorized)
|
||||
end
|
||||
|
||||
it "authorizes update action after setting attributes" do
|
||||
@ability.can :update, :projects, :name => "foo"
|
||||
project = Project.create!(:name => "foo")
|
||||
@params.merge!(:action => "update", :id => project.id, :project => {:name => "bar"})
|
||||
resource = CanCan::ControllerResource.new(@controller, :project, :load => true, :authorize => true)
|
||||
lambda { resource.process }.should raise_error(CanCan::Unauthorized)
|
||||
end
|
||||
|
||||
it "loads the model using a custom class" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :class => Project).process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "loads the model using a custom namespaced class" do
|
||||
module SomeEngine
|
||||
class Project < ::Project; end
|
||||
end
|
||||
project = SomeEngine::Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :class => SomeEngine::Project).process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "does not authorize based on resource name if class is false because we don't do class level authorization anymore" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
@controller.stub(:authorize!).with(:show, :projects) { raise CanCan::Unauthorized }
|
||||
resource = CanCan::ControllerResource.new(@controller, :authorize => true, :class => false)
|
||||
lambda { resource.process }.should_not raise_error(CanCan::Unauthorized)
|
||||
end
|
||||
|
||||
it "loads and authorize using custom instance name" do
|
||||
project = Project.create!
|
||||
@params.merge!(:action => "show", :id => project.id)
|
||||
@controller.stub(:authorize!).with(:show, project) { raise CanCan::Unauthorized }
|
||||
resource = CanCan::ControllerResource.new(@controller, :load => true, :authorize => true, :instance_name => :custom_project)
|
||||
lambda { resource.process }.should raise_error(CanCan::Unauthorized)
|
||||
@controller.instance_variable_get(:@custom_project).should == project
|
||||
end
|
||||
|
||||
it "loads 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, :load => true)
|
||||
resource.process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "loads resource using custom find_by attribute" do
|
||||
project = Project.create!(:name => "foo")
|
||||
@params.merge!(:action => "show", :id => "foo")
|
||||
CanCan::ControllerResource.new(@controller, :load => true, :find_by => :name).process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "authorizes each new attribute in the create action" do
|
||||
@params.merge!(:action => "create", :project => {:name => "foo"})
|
||||
@controller.instance_variable_set(:@project, :some_project)
|
||||
@ability.should_receive(:authorize!).with(:create, :some_project, :name)
|
||||
CanCan::ControllerResource.new(@controller, :authorize => true).process
|
||||
end
|
||||
|
||||
it "allows full find method to be passed into find_by option" do
|
||||
project = Project.create!(:name => "foo")
|
||||
@params.merge!(:action => "show", :id => "foo")
|
||||
CanCan::ControllerResource.new(@controller, :find_by => :find_by_name, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
it "authorizes each new attribute in the update action" do
|
||||
@params.merge!(:action => "update", :id => 123, :project => {:name => "foo"})
|
||||
@controller.instance_variable_set(:@project, :some_project)
|
||||
@ability.should_receive(:authorize!).with(:update, :some_project, :name)
|
||||
CanCan::ControllerResource.new(@controller, :authorize => true).process
|
||||
end
|
||||
|
||||
it "fetches member through method when instance variable is not provided" do
|
||||
@controller.stub(:project) { :some_project }
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
@controller.stub(:authorize!).with(:show, :some_project) { raise CanCan::Unauthorized }
|
||||
resource = CanCan::ControllerResource.new(@controller, :authorize => true)
|
||||
lambda { resource.process }.should raise_error(CanCan::Unauthorized)
|
||||
end
|
||||
|
||||
it "attempts to load a resource with the same namespace as the controller when using :: for namespace" do
|
||||
module Namespaced
|
||||
class Project < ::Project; end
|
||||
end
|
||||
project = Namespaced::Project.create!
|
||||
@params.merge!(:controller => "Namespaced::ProjectsController", :action => "show", :id => project.id)
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should == project
|
||||
end
|
||||
|
||||
# Rails includes namespace in params, see issue #349
|
||||
it "creates through namespaced params" do
|
||||
module Namespaced
|
||||
class Project < ::Project; end
|
||||
end
|
||||
@params.merge!(:controller => "Namespaced::ProjectsController", :action => "create", :namespaced_project => {:name => "foobar"})
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).name.should == "foobar"
|
||||
end
|
||||
|
||||
it "should properly authorize resource for namespaced controller" do
|
||||
@ability.can(:index, "admin/dashboard")
|
||||
@params.merge!(:controller => "admin/dashboard", :action => "index")
|
||||
@controller.authorize!(:index, "admin/dashboard")
|
||||
resource = CanCan::ControllerResource.new(@controller, :authorize => true).process
|
||||
lambda { resource.process }.should_not raise_error(CanCan::Unauthorized)
|
||||
end
|
||||
|
||||
# it "raises ImplementationRemoved when adding :name option" do
|
||||
# lambda {
|
||||
# CanCan::ControllerResource.new(@controller, :name => :foo)
|
||||
# }.should raise_error(CanCan::ImplementationRemoved)
|
||||
# end
|
||||
#
|
||||
# it "raises 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 "raises ImplementationRemoved exception when passing :nested option" do
|
||||
# lambda {
|
||||
# CanCan::ControllerResource.new(@controller, :nested => :project)
|
||||
# }.should raise_error(CanCan::ImplementationRemoved)
|
||||
# end
|
||||
|
||||
# it "skips resource behavior for :only actions in array" do
|
||||
# @controller_class.stub(: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 "skips resource behavior for :only one action on resource" do
|
||||
# @controller_class.stub(: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 "skips resource behavior :except actions in array" do
|
||||
# @controller_class.stub(: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 "skips resource behavior :except one action on resource" do
|
||||
# @controller_class.stub(: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 "skips loading and authorization" do
|
||||
# @controller_class.stub(: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
|
||||
|
||||
@@ -1,35 +1,58 @@
|
||||
require "spec_helper"
|
||||
|
||||
describe CanCan::AccessDenied do
|
||||
describe CanCan::Unauthorized do
|
||||
describe "with action and subject" do
|
||||
before(:each) do
|
||||
@exception = CanCan::AccessDenied.new(nil, :some_action, :some_subject)
|
||||
@exception = CanCan::Unauthorized.new(nil, :some_action, :some_subject)
|
||||
end
|
||||
|
||||
it "should have action and subject accessors" do
|
||||
|
||||
it "has action and subject accessors" do
|
||||
@exception.action.should == :some_action
|
||||
@exception.subject.should == :some_subject
|
||||
end
|
||||
|
||||
it "should have a changable default message" do
|
||||
|
||||
it "has 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!")
|
||||
@exception = CanCan::Unauthorized.new("Access denied!")
|
||||
end
|
||||
|
||||
it "should have nil action and subject" do
|
||||
|
||||
it "has nil action and subject" do
|
||||
@exception.action.should be_nil
|
||||
@exception.subject.should be_nil
|
||||
end
|
||||
|
||||
it "should have passed message" do
|
||||
|
||||
it "has 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::Unauthorized.new
|
||||
@exception.message.should == "This is a different message"
|
||||
end
|
||||
|
||||
it "defaults to a nice message" do
|
||||
@exception = CanCan::Unauthorized.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::Unauthorized.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
|
||||
|
||||
58
spec/cancan/inherited_resource_spec.rb
Normal file
58
spec/cancan/inherited_resource_spec.rb
Normal file
@@ -0,0 +1,58 @@
|
||||
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)
|
||||
@controller.stub(:params) { @params }
|
||||
@controller.stub(:current_ability) { @ability }
|
||||
# @controller_class.stub(:cancan_skipper) { {:authorize => {}, :load => {}} }
|
||||
end
|
||||
|
||||
it "show should load resource through @controller.resource" do
|
||||
@params.merge!(:action => "show", :id => 123)
|
||||
@controller.stub(:resource) { :project_resource }
|
||||
CanCan::InheritedResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should == :project_resource
|
||||
end
|
||||
|
||||
it "new should load through @controller.build_resource" do
|
||||
@params[:action] = "new"
|
||||
@controller.stub(:build_resource) { :project_resource }
|
||||
CanCan::InheritedResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).should == :project_resource
|
||||
end
|
||||
|
||||
it "index should load through @controller.association_chain when parent" do
|
||||
@params[:action] = "index"
|
||||
@controller.stub(:association_chain) { @controller.instance_variable_set(:@project, :project_resource) }
|
||||
CanCan::InheritedResource.new(@controller, :load => true, :parent => true).process
|
||||
@controller.instance_variable_get(:@project).should == :project_resource
|
||||
end
|
||||
|
||||
it "index should load through @controller.end_of_association_chain" do
|
||||
@params[:action] = "index"
|
||||
Project.stub(:accessible_by).with(@ability, :index) { :projects }
|
||||
@controller.stub(:end_of_association_chain) { Project }
|
||||
CanCan::InheritedResource.new(@controller, :load => true).process
|
||||
@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, :projects, :name => "from conditions")
|
||||
@controller.stub(:build_resource) { Struct.new(:name).new }
|
||||
CanCan::InheritedResource.new(@controller, :load => true).process
|
||||
@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, :projects, :name => "from conditions")
|
||||
@controller.stub(:build_resource) { Struct.new(:name).new }
|
||||
CanCan::ControllerResource.new(@controller, :load => true).process
|
||||
@controller.instance_variable_get(:@project).name.should == "from params"
|
||||
end
|
||||
end
|
||||
@@ -3,13 +3,13 @@ require "spec_helper"
|
||||
describe "be_able_to" do
|
||||
it "delegates to can?" do
|
||||
object = Object.new
|
||||
mock(object).can?(:read, 123) { true }
|
||||
object.should_receive(:can?).with(: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 }
|
||||
object.should_receive(:can?).with(:read, 123) { false }
|
||||
expect do
|
||||
object.should be_able_to(:read, 123)
|
||||
end.should raise_error('expected to be able to :read 123')
|
||||
@@ -17,7 +17,7 @@ describe "be_able_to" do
|
||||
|
||||
it "reports a nice failure message for should not" do
|
||||
object = Object.new
|
||||
mock(object).can?(:read, 123) { true }
|
||||
object.should_receive(:can?).with(: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')
|
||||
@@ -25,7 +25,7 @@ describe "be_able_to" do
|
||||
|
||||
it "delegates additional arguments to can? and reports in failure message" do
|
||||
object = Object.new
|
||||
mock(object).can?(:read, 123, 456) { false }
|
||||
object.should_receive(:can?).with(: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')
|
||||
|
||||
278
spec/cancan/model_adapters/active_record_adapter_spec.rb
Normal file
278
spec/cancan/model_adapters/active_record_adapter_spec.rb
Normal file
@@ -0,0 +1,278 @@
|
||||
if ENV["MODEL_ADAPTER"].nil? || ENV["MODEL_ADAPTER"] == "active_record"
|
||||
require "spec_helper"
|
||||
|
||||
class Category
|
||||
has_many :articles
|
||||
end
|
||||
|
||||
class Article < ActiveRecord::Base
|
||||
connection.create_table(table_name) do |t|
|
||||
t.integer :category_id
|
||||
t.string :name
|
||||
t.boolean :published
|
||||
t.boolean :secret
|
||||
t.integer :priority
|
||||
end
|
||||
belongs_to :category
|
||||
has_many :comments
|
||||
end
|
||||
|
||||
class Comment < ActiveRecord::Base
|
||||
connection.create_table(table_name) do |t|
|
||||
t.integer :article_id
|
||||
t.boolean :spam
|
||||
end
|
||||
belongs_to :article
|
||||
end
|
||||
|
||||
describe CanCan::ModelAdapters::ActiveRecordAdapter do
|
||||
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 "is 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 "finds record" do
|
||||
article = Article.create!
|
||||
CanCan::ModelAdapters::ActiveRecordAdapter.find(Article, article.id).should == article
|
||||
end
|
||||
|
||||
it "does not fetch any records when no abilities are defined" do
|
||||
Article.create!
|
||||
Article.accessible_by(@ability).should be_empty
|
||||
end
|
||||
|
||||
it "fetches all articles when one can read all" do
|
||||
@ability.can :read, :articles
|
||||
article = Article.create!
|
||||
Article.accessible_by(@ability).should == [article]
|
||||
end
|
||||
|
||||
it "fetches only the articles that are published" do
|
||||
@ability.can :read, :articles, :published => true
|
||||
article1 = Article.create!(:published => true)
|
||||
article2 = Article.create!(:published => false)
|
||||
Article.accessible_by(@ability).should == [article1]
|
||||
end
|
||||
|
||||
it "fetches any articles which are published or secret" do
|
||||
@ability.can :read, :articles, :published => true
|
||||
@ability.can :read, :articles, :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 "fetches only the articles that are published and not secret" do
|
||||
@ability.can :read, :articles, :published => true
|
||||
@ability.cannot :read, :articles, :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 "only reads comments for articles which are published" do
|
||||
@ability.can :read, :comments, :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 "only reads comments for visible categories through articles" do
|
||||
pending "does ActiveRecord no longer support a deep nested hash of conditions?"
|
||||
@ability.can :read, :comments, :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 "allows conditions in SQL and merge with hash conditions" do
|
||||
@ability.can :read, :articles, :published => true
|
||||
@ability.can :read, :articles, ["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 "allows a scope for conditions" do
|
||||
@ability.can :read, :articles, Article.where(:secret => true)
|
||||
article1 = Article.create!(:secret => true)
|
||||
article2 = Article.create!(:secret => false)
|
||||
Article.accessible_by(@ability).should == [article1]
|
||||
end
|
||||
|
||||
it "fetches only associated records when using with a scope for conditions" do
|
||||
@ability.can :read, :articles, 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)
|
||||
# for some reason the objects aren't comparing equally here so it's necessary to compare by id
|
||||
category1.articles.accessible_by(@ability).map(&:id).should == [article1.id]
|
||||
end
|
||||
|
||||
it "raises an exception when trying to merge scope with other conditions" do
|
||||
@ability.can :read, :articles, :published => true
|
||||
@ability.can :read, :articles, 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 articles ability.")
|
||||
end
|
||||
|
||||
it "does not allow to fetch records when ability with just block present" do
|
||||
@ability.can :read, :articles do
|
||||
false
|
||||
end
|
||||
lambda { Article.accessible_by(@ability) }.should raise_error(CanCan::Error)
|
||||
end
|
||||
|
||||
it "does not allow to check ability on object against SQL conditions without block" do
|
||||
@ability.can :read, :articles, ["secret=?", true]
|
||||
lambda { @ability.can? :read, Article.new }.should raise_error(CanCan::Error)
|
||||
end
|
||||
|
||||
it "has false conditions if no abilities match" do
|
||||
@ability.model_adapter(Article, :read).conditions.should == "'t'='f'"
|
||||
end
|
||||
|
||||
it "returns false conditions for cannot clause" do
|
||||
@ability.cannot :read, :articles
|
||||
@ability.model_adapter(Article, :read).conditions.should == "'t'='f'"
|
||||
end
|
||||
|
||||
it "returns SQL for single `can` definition in front of default `cannot` condition" do
|
||||
@ability.cannot :read, :articles
|
||||
@ability.can :read, :articles, :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 "returns true condition for single `can` definition in front of default `can` condition" do
|
||||
@ability.can :read, :articles
|
||||
@ability.can :read, :articles, :published => false, :secret => true
|
||||
@ability.model_adapter(Article, :read).conditions.should eq(:secret => true, :published => false)
|
||||
end
|
||||
|
||||
it "returns `false condition` for single `cannot` definition in front of default `cannot` condition" do
|
||||
@ability.cannot :read, :articles
|
||||
@ability.cannot :read, :articles, :published => false, :secret => true
|
||||
@ability.model_adapter(Article, :read).conditions.should == "'t'='f'"
|
||||
end
|
||||
|
||||
it "returns `not (sql)` for single `cannot` definition in front of default `can` condition" do
|
||||
@ability.can :read, :articles
|
||||
@ability.cannot :read, :articles, :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 "returns appropriate sql conditions in complex case" do
|
||||
@ability.can :read, :articles
|
||||
@ability.can :access, :articles, :id => 1
|
||||
@ability.can :update, :articles, :published => true
|
||||
@ability.cannot :update, :articles, :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, :access).conditions.should == {:id => 1}
|
||||
@ability.model_adapter(Article, :read).conditions.should == {:id => 1} # used to be "t=t" but changed with new specificity rule (issue #321)
|
||||
end
|
||||
|
||||
it "does not forget conditions when calling with SQL string" do
|
||||
@ability.can :read, :articles, :published => true
|
||||
@ability.can :read, :articles, ['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 "has nil joins if no rules" do
|
||||
@ability.model_adapter(Article, :read).joins.should be_nil
|
||||
end
|
||||
|
||||
it "has nil joins if no nested hashes specified in conditions" do
|
||||
@ability.can :read, :articles, :published => false
|
||||
@ability.can :read, :articles, :secret => true
|
||||
@ability.model_adapter(Article, :read).joins.should be_nil
|
||||
end
|
||||
|
||||
it "merges separate joins into a single array" do
|
||||
@ability.can :read, :articles, :project => { :blocked => false }
|
||||
@ability.can :read, :articles, :company => { :admin => true }
|
||||
@ability.model_adapter(Article, :read).joins.inspect.should orderlessly_match([:company, :project].inspect)
|
||||
end
|
||||
|
||||
it "merges same joins into a single array" do
|
||||
@ability.can :read, :articles, :project => { :blocked => false }
|
||||
@ability.can :read, :articles, :project => { :admin => true }
|
||||
@ability.model_adapter(Article, :read).joins.should == [:project]
|
||||
end
|
||||
|
||||
it "restricts articles given a MetaWhere condition" do
|
||||
pending
|
||||
@ability.can :read, :articles, :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
|
||||
pending
|
||||
@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 "matches any MetaWhere condition" do
|
||||
pending
|
||||
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
|
||||
120
spec/cancan/model_adapters/data_mapper_adapter_spec.rb
Normal file
120
spec/cancan/model_adapters/data_mapper_adapter_spec.rb
Normal file
@@ -0,0 +1,120 @@
|
||||
if ENV["MODEL_ADAPTER"] == "data_mapper"
|
||||
require "spec_helper"
|
||||
|
||||
DataMapper.setup(:default, 'sqlite::memory:')
|
||||
|
||||
class DataMapperArticle
|
||||
include DataMapper::Resource
|
||||
property :id, Serial
|
||||
property :published, Boolean, :default => false
|
||||
property :secret, Boolean, :default => false
|
||||
property :priority, Integer
|
||||
has n, :data_mapper_comments
|
||||
end
|
||||
|
||||
class DataMapperComment
|
||||
include DataMapper::Resource
|
||||
property :id, Serial
|
||||
property :spam, Boolean, :default => false
|
||||
belongs_to :data_mapper_article
|
||||
end
|
||||
|
||||
DataMapper.finalize
|
||||
DataMapper.auto_migrate!
|
||||
|
||||
describe CanCan::ModelAdapters::DataMapperAdapter do
|
||||
before(:each) do
|
||||
DataMapperArticle.destroy
|
||||
DataMapperComment.destroy
|
||||
@ability = Object.new
|
||||
@ability.extend(CanCan::Ability)
|
||||
end
|
||||
|
||||
it "is for only data mapper classes" do
|
||||
CanCan::ModelAdapters::DataMapperAdapter.should_not be_for_class(Object)
|
||||
CanCan::ModelAdapters::DataMapperAdapter.should be_for_class(DataMapperArticle)
|
||||
CanCan::ModelAdapters::AbstractAdapter.adapter_class(DataMapperArticle).should == CanCan::ModelAdapters::DataMapperAdapter
|
||||
end
|
||||
|
||||
it "finds record" do
|
||||
article = DataMapperArticle.create
|
||||
CanCan::ModelAdapters::DataMapperAdapter.find(DataMapperArticle, article.id).should == article
|
||||
end
|
||||
|
||||
it "does not fetch any records when no abilities are defined" do
|
||||
DataMapperArticle.create
|
||||
DataMapperArticle.accessible_by(@ability).should be_empty
|
||||
end
|
||||
|
||||
it "fetches all articles when one can read all" do
|
||||
@ability.can :read, :data_mapper_articles
|
||||
article = DataMapperArticle.create
|
||||
DataMapperArticle.accessible_by(@ability).should == [article]
|
||||
end
|
||||
|
||||
it "fetches only the articles that are published" do
|
||||
@ability.can :read, :data_mapper_articles, :published => true
|
||||
article1 = DataMapperArticle.create(:published => true)
|
||||
article2 = DataMapperArticle.create(:published => false)
|
||||
DataMapperArticle.accessible_by(@ability).should == [article1]
|
||||
end
|
||||
|
||||
it "fetches any articles which are published or secret" do
|
||||
@ability.can :read, :data_mapper_articles, :published => true
|
||||
@ability.can :read, :data_mapper_articles, :secret => true
|
||||
article1 = DataMapperArticle.create(:published => true, :secret => false)
|
||||
article2 = DataMapperArticle.create(:published => true, :secret => true)
|
||||
article3 = DataMapperArticle.create(:published => false, :secret => true)
|
||||
article4 = DataMapperArticle.create(:published => false, :secret => false)
|
||||
DataMapperArticle.accessible_by(@ability).should == [article1, article2, article3]
|
||||
end
|
||||
|
||||
it "fetches 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, :data_mapper_articles, :published => true
|
||||
@ability.cannot :read, :data_mapper_articles, :secret => true
|
||||
article1 = DataMapperArticle.create(:published => true, :secret => false)
|
||||
article2 = DataMapperArticle.create(:published => true, :secret => true)
|
||||
article3 = DataMapperArticle.create(:published => false, :secret => true)
|
||||
article4 = DataMapperArticle.create(:published => false, :secret => false)
|
||||
DataMapperArticle.accessible_by(@ability).should == [article1]
|
||||
end
|
||||
|
||||
it "only reads comments for articles which are published" do
|
||||
@ability.can :read, :data_mapper_comments, :data_mapper_article => { :published => true }
|
||||
comment1 = DataMapperComment.create(:data_mapper_article => DataMapperArticle.create!(:published => true))
|
||||
comment2 = DataMapperComment.create(:data_mapper_article => DataMapperArticle.create!(:published => false))
|
||||
DataMapperComment.accessible_by(@ability).should == [comment1]
|
||||
end
|
||||
|
||||
it "allows conditions in SQL and merge with hash conditions" do
|
||||
@ability.can :read, :data_mapper_articles, :published => true
|
||||
@ability.can :read, :data_mapper_articles, ["secret=?", true]
|
||||
article1 = DataMapperArticle.create(:published => true, :secret => false)
|
||||
article4 = DataMapperArticle.create(:published => false, :secret => false)
|
||||
DataMapperArticle.accessible_by(@ability).should == [article1]
|
||||
end
|
||||
|
||||
it "matches gt comparison" do
|
||||
@ability.can :read, :data_mapper_articles, :priority.gt => 3
|
||||
article1 = DataMapperArticle.create(:priority => 4)
|
||||
article2 = DataMapperArticle.create(:priority => 3)
|
||||
DataMapperArticle.accessible_by(@ability).should == [article1]
|
||||
@ability.should be_able_to(:read, article1)
|
||||
@ability.should_not be_able_to(:read, article2)
|
||||
end
|
||||
|
||||
it "matches gte comparison" do
|
||||
@ability.can :read, :data_mapper_articles, :priority.gte => 3
|
||||
article1 = DataMapperArticle.create(:priority => 4)
|
||||
article2 = DataMapperArticle.create(:priority => 3)
|
||||
article3 = DataMapperArticle.create(:priority => 2)
|
||||
DataMapperArticle.accessible_by(@ability).should == [article1, article2]
|
||||
@ability.should be_able_to(:read, article1)
|
||||
@ability.should be_able_to(:read, article2)
|
||||
@ability.should_not be_able_to(:read, article3)
|
||||
end
|
||||
|
||||
# TODO: add more comparison specs
|
||||
end
|
||||
end
|
||||
7
spec/cancan/model_adapters/default_adapter_spec.rb
Normal file
7
spec/cancan/model_adapters/default_adapter_spec.rb
Normal file
@@ -0,0 +1,7 @@
|
||||
require "spec_helper"
|
||||
|
||||
describe CanCan::ModelAdapters::DefaultAdapter do
|
||||
it "is default for generic classes" do
|
||||
CanCan::ModelAdapters::AbstractAdapter.adapter_class(Object).should == CanCan::ModelAdapters::DefaultAdapter
|
||||
end
|
||||
end
|
||||
226
spec/cancan/model_adapters/mongoid_adapter_spec.rb
Normal file
226
spec/cancan/model_adapters/mongoid_adapter_spec.rb
Normal file
@@ -0,0 +1,226 @@
|
||||
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 "is 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 "finds record" do
|
||||
project = MongoidProject.create
|
||||
CanCan::ModelAdapters::MongoidAdapter.find(MongoidProject, project.id).should == project
|
||||
end
|
||||
|
||||
it "compares properties on mongoid documents with the conditions hash" do
|
||||
model = MongoidProject.new
|
||||
@ability.can :read, :mongoid_projects, :id => model.id
|
||||
@ability.should be_able_to(:read, model)
|
||||
end
|
||||
|
||||
it "is 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, :mongoid_projects, :numbers => 'one'
|
||||
@ability.should be_able_to(:foo, one_to_three)
|
||||
@ability.should_not be_able_to(:foo, two_to_five)
|
||||
end
|
||||
|
||||
it "returns [] 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 "returns the correct records based on the defined ability" do
|
||||
@ability.can :read, :mongoid_projects, :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 "returns the correct records when a mix of can and cannot rules in defined ability" do
|
||||
pending "TODO figure out why this isn't working"
|
||||
@ability.can :manage, :mongoid_projects, :title => 'Sir'
|
||||
@ability.cannot :destroy, :mongoid_projects
|
||||
|
||||
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 "takes presedence over rule defined without a condition" do
|
||||
@ability.can :read, :mongoid_projects
|
||||
@ability.can :read, :mongoid_projects, :title => 'Sir'
|
||||
sir = MongoidProject.create(:title => 'Sir')
|
||||
lord = MongoidProject.create(:title => 'Lord')
|
||||
|
||||
MongoidProject.accessible_by(@ability, :read).entries.should == [sir]
|
||||
end
|
||||
|
||||
it "returns everything when the defined ability is access all" do
|
||||
@ability.can :access, :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 "allows a scope for conditions" do
|
||||
@ability.can :read, :mongoid_projects, 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 "handles :field.in" do
|
||||
obj = MongoidProject.create(:title => 'Sir')
|
||||
@ability.can :read, :mongoid_projects, :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, :mongoid_projects, @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, :mongoid_projects, @conditions
|
||||
@ability.should be_able_to(:read, obj)
|
||||
end
|
||||
end
|
||||
|
||||
it "handles :field.nin" do
|
||||
obj = MongoidProject.create(:title => 'Sir')
|
||||
@ability.can :read, :mongoid_projects, :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 "handles :field.size" do
|
||||
obj = MongoidProject.create(:titles => ['Palatin', 'Margrave'])
|
||||
@ability.can :read, :mongoid_projects, :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 "handles :field.exists" do
|
||||
obj = MongoidProject.create(:titles => ['Palatin', 'Margrave'])
|
||||
@ability.can :read, :mongoid_projects, :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 "handles :field.gt" do
|
||||
obj = MongoidProject.create(:age => 50)
|
||||
@ability.can :read, :mongoid_projects, :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 "handles instance not saved to database" do
|
||||
obj = MongoidProject.new(:title => 'Sir')
|
||||
@ability.can :read, :mongoid_projects, :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 "calls where with matching ability conditions" do
|
||||
obj = MongoidProject.create(:foo => {:bar => 1})
|
||||
@ability.can :read, :mongoid_projects, :foo => {:bar => 1}
|
||||
MongoidProject.accessible_by(@ability, :read).entries.first.should == obj
|
||||
end
|
||||
|
||||
it "excludes from the result if set to cannot" do
|
||||
obj = MongoidProject.create(:bar => 1)
|
||||
obj2 = MongoidProject.create(:bar => 2)
|
||||
@ability.can :read, :mongoid_projects
|
||||
@ability.cannot :read, :mongoid_projects, :bar => 2
|
||||
MongoidProject.accessible_by(@ability, :read).entries.should == [obj]
|
||||
end
|
||||
|
||||
it "combines the rules" do
|
||||
obj = MongoidProject.create(:bar => 1)
|
||||
obj2 = MongoidProject.create(:bar => 2)
|
||||
obj3 = MongoidProject.create(:bar => 3)
|
||||
@ability.can :read, :mongoid_projects, :bar => 1
|
||||
@ability.can :read, :mongoid_projects, :bar => 2
|
||||
MongoidProject.accessible_by(@ability, :read).entries.should =~ [obj, obj2]
|
||||
end
|
||||
|
||||
it "does not allow to fetch records when ability with just block present" do
|
||||
@ability.can :read, :mongoid_projects do
|
||||
false
|
||||
end
|
||||
lambda {
|
||||
MongoidProject.accessible_by(@ability)
|
||||
}.should raise_error(CanCan::Error)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,117 +0,0 @@
|
||||
require "spec_helper"
|
||||
|
||||
describe CanCan::ResourceAuthorization do
|
||||
before(:each) do
|
||||
@controller = Object.new # simple stub for now
|
||||
end
|
||||
|
||||
it "should load the resource into an instance variable if params[:id] is specified" do
|
||||
stub(Ability).find(123) { :some_resource }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "show", :id => 123)
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||
end
|
||||
|
||||
it "should properly load resource for namespaced controller" do
|
||||
stub(Ability).find(123) { :some_resource }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "admin/abilities", :action => "show", :id => 123)
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||
end
|
||||
|
||||
it "should properly load resource for namespaced controller when using '::' for namespace" do
|
||||
stub(Ability).find(123) { :some_resource }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "Admin::AbilitiesController", :action => "show", :id => 123)
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||
end
|
||||
|
||||
it "should build a new resource with hash if params[:id] is not specified" do
|
||||
stub(Ability).new(:foo => "bar") { :some_resource }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "create", :ability => {:foo => "bar"})
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||
end
|
||||
|
||||
it "should build a new resource even if attribute hash isn't specified" do
|
||||
stub(Ability).new(nil) { :some_resource }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "new")
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||
end
|
||||
|
||||
it "should not build a resource when on index action" do
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "index")
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should be_nil
|
||||
end
|
||||
|
||||
it "should perform authorization using controller action and loaded model" do
|
||||
@controller.instance_variable_set(:@ability, :some_resource)
|
||||
stub(@controller).authorize!(:show, :some_resource) { raise CanCan::AccessDenied }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "show")
|
||||
lambda { authorization.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||
end
|
||||
|
||||
it "should perform authorization using controller action and non loaded model" do
|
||||
stub(@controller).authorize!(:show, Ability) { raise CanCan::AccessDenied }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "show")
|
||||
lambda { authorization.authorize_resource }.should raise_error(CanCan::AccessDenied)
|
||||
end
|
||||
|
||||
it "should call load_resource and authorize_resource for load_and_authorize_resource" do
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "show")
|
||||
mock(authorization).load_resource
|
||||
mock(authorization).authorize_resource
|
||||
authorization.load_and_authorize_resource
|
||||
end
|
||||
|
||||
it "should not build a resource when on custom collection action" do
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "sort"}, {:collection => [:sort, :list]})
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should be_nil
|
||||
end
|
||||
|
||||
it "should build a resource when on custom new action even when params[:id] exists" do
|
||||
stub(Ability).new(nil) { :some_resource }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "build", :id => 123}, {:new => :build})
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||
end
|
||||
|
||||
it "should not try to load resource for other action if params[:id] is undefined" do
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, :controller => "abilities", :action => "list")
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should be_nil
|
||||
end
|
||||
|
||||
it "should load nested resource and fetch other resource through the association" do
|
||||
stub(Person).find(456).stub!.abilities.stub!.find(123) { :some_ability }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "show", :id => 123, :person_id => 456}, {:nested => :person})
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
||||
end
|
||||
|
||||
it "should load nested resource and build resource through a deep association" do
|
||||
stub(Person).find(456).stub!.behaviors.stub!.find(789).stub!.abilities.stub!.build(nil) { :some_ability }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "new", :person_id => 456, :behavior_id => 789}, {:nested => [:person, :behavior]})
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
||||
end
|
||||
|
||||
it "should not load nested resource and build through this if *_id param isn't specified" do
|
||||
stub(Person).find(456) { :some_person }
|
||||
stub(Ability).new(nil) { :some_ability }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "new", :person_id => 456}, {:nested => [:person, :behavior]})
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@person).should == :some_person
|
||||
@controller.instance_variable_get(:@ability).should == :some_ability
|
||||
end
|
||||
|
||||
it "should load the model using a custom class" do
|
||||
stub(Person).find(123) { :some_resource }
|
||||
authorization = CanCan::ResourceAuthorization.new(@controller, {:controller => "abilities", :action => "show", :id => 123}, {:resource => Person})
|
||||
authorization.load_resource
|
||||
@controller.instance_variable_get(:@ability).should == :some_resource
|
||||
end
|
||||
end
|
||||
55
spec/cancan/rule_spec.rb
Normal file
55
spec/cancan/rule_spec.rb
Normal file
@@ -0,0 +1,55 @@
|
||||
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, :integers, @conditions)
|
||||
end
|
||||
|
||||
it "returns no association joins if none exist" do
|
||||
@rule.associations_hash.should == {}
|
||||
end
|
||||
|
||||
it "returns no association for joins if just attributes" do
|
||||
@conditions[:foo] = :bar
|
||||
@rule.associations_hash.should == {}
|
||||
end
|
||||
|
||||
it "returns single association for joins" do
|
||||
@conditions[:foo] = {:bar => 1}
|
||||
@rule.associations_hash.should == {:foo => {}}
|
||||
end
|
||||
|
||||
it "returns multiple associations for joins" do
|
||||
@conditions[:foo] = {:bar => 1}
|
||||
@conditions[:test] = {1 => 2}
|
||||
@rule.associations_hash.should == {:foo => {}, :test => {}}
|
||||
end
|
||||
|
||||
it "returns nested associations for joins" do
|
||||
@conditions[:foo] = {:bar => {1 => 2}}
|
||||
@rule.associations_hash.should == {:foo => {:bar => {}}}
|
||||
end
|
||||
|
||||
it "returns no association joins if conditions is nil" do
|
||||
rule = CanCan::Rule.new(true, :read, :integers)
|
||||
rule.associations_hash.should == {}
|
||||
end
|
||||
|
||||
it "has higher specificity for attributes/conditions" do
|
||||
CanCan::Rule.new(true, :read, :integers).specificity.should eq(1)
|
||||
CanCan::Rule.new(true, :read, :integers, :foo => :bar).specificity.should eq(2)
|
||||
CanCan::Rule.new(true, :read, :integers, :foo).specificity.should eq(2)
|
||||
CanCan::Rule.new(false, :read, :integers).specificity.should eq(3)
|
||||
CanCan::Rule.new(false, :read, :integers, :foo => :bar).specificity.should eq(4)
|
||||
CanCan::Rule.new(false, :read, :integers, :foo).specificity.should eq(4)
|
||||
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
|
||||
end
|
||||
13
spec/matchers.rb
Normal file
13
spec/matchers.rb
Normal file
@@ -0,0 +1,13 @@
|
||||
RSpec::Matchers.define :orderlessly_match do |original_string|
|
||||
match do |given_string|
|
||||
original_string.split('').sort == given_string.split('').sort
|
||||
end
|
||||
|
||||
failure_message_for_should do |given_string|
|
||||
"expected \"#{given_string}\" to have the same characters as \"#{original_string}\""
|
||||
end
|
||||
|
||||
failure_message_for_should_not do |given_string|
|
||||
"expected \"#{given_string}\" not to have the same characters as \"#{original_string}\""
|
||||
end
|
||||
end
|
||||
@@ -1,23 +1,49 @@
|
||||
require 'rubygems'
|
||||
require 'spec'
|
||||
require 'active_support'
|
||||
require 'active_record'
|
||||
require 'action_controller'
|
||||
require 'action_view'
|
||||
require 'bundler/setup'
|
||||
|
||||
require "sqlite3"
|
||||
require "active_record"
|
||||
|
||||
case ENV["MODEL_ADAPTER"]
|
||||
when "data_mapper"
|
||||
require "dm-core"
|
||||
require "dm-sqlite-adapter"
|
||||
require "dm-migrations"
|
||||
when "mongoid"
|
||||
require "mongoid"
|
||||
end
|
||||
|
||||
require 'active_support/all'
|
||||
require 'matchers'
|
||||
require 'cancan'
|
||||
require 'cancan/matchers'
|
||||
|
||||
Spec::Runner.configure do |config|
|
||||
config.mock_with :rr
|
||||
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
|
||||
end
|
||||
|
||||
class Ability
|
||||
include CanCan::Ability
|
||||
|
||||
|
||||
def initialize(user)
|
||||
end
|
||||
end
|
||||
|
||||
# this class helps out in testing nesting
|
||||
class Person
|
||||
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
|
||||
|
||||
class Category < ActiveRecord::Base
|
||||
connection.create_table(table_name) do |t|
|
||||
t.boolean :visible
|
||||
end
|
||||
has_many :projects
|
||||
end
|
||||
|
||||
class Project < ActiveRecord::Base
|
||||
connection.create_table(table_name) do |t|
|
||||
t.integer :category_id
|
||||
t.string :name
|
||||
end
|
||||
belongs_to :category
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user