Compare commits

...

171 Commits

Author SHA1 Message Date
Carlos Antonio da Silva
39c1a2c7d0 Release 3.0.0.rc with Rails 4 support 2013-05-07 13:32:03 -03:00
Carlos Antonio da Silva
270e2ece19 Merge pull request #2376 from plataformatec/rails4
Support Rails 4

Keep compatibility with Rails 3.2. Drop support to Ruby 1.8.
2013-05-07 09:22:23 -07:00
Carlos Antonio da Silva
6b5988d756 Add changelog note about Rails 4 and Strong Params support
Plus dropping support for Rails < 3.2 and Ruby < 1.9.3
[ci skip]
2013-05-07 13:12:58 -03:00
Carlos Antonio da Silva
a4efbb9ad6 Update mongo revision 2013-05-07 13:05:02 -03:00
Carlos Antonio da Silva
eb0ad1c21a Merge branch 'master' into rails4 2013-05-07 13:01:34 -03:00
Carlos Antonio da Silva
f5e33089a0 Release 2.2.4 2013-05-07 12:51:46 -03:00
José Valim
e499fadf52 Use persisted? in order to check if the record was destoryed or not 2013-05-07 08:55:30 -06:00
Carlos Antonio da Silva
70199ed039 Bump webrat to 0.7.3 on 3.1 as well 2013-05-07 11:48:03 -03:00
Carlos Antonio da Silva
fb07558082 Update changelog with latest fixes [ci skip] 2013-05-07 11:48:03 -03:00
José Valim
5ad122b928 Fix build for mongoid 2013-05-07 08:47:18 -06:00
José Valim
c78b4b40c1 Remove warning since webrat is emitting tons of them 2013-05-07 08:22:06 -06:00
José Valim
ef2a2280a3 Update examples to be compatible with Rails 4 2013-05-07 08:18:12 -06:00
Carlos Antonio da Silva
42fca4dbe5 Update 3.1 lock file 2013-05-07 11:12:58 -03:00
José Valim
03f2a6a5e4 Merge pull request #2392 from michiel3/master
Add destroy_with_password method
2013-05-07 07:11:47 -07:00
José Valim
cc2fea8276 Merge pull request #2402 from xtream/master
Avoid duplication on param filter
2013-05-07 07:09:47 -07:00
José Valim
bb4cc2428f Merge pull request #2407 from sebastianwr/master
No redirect when accessing devise API via JSON
2013-05-07 07:08:53 -07:00
Sebastian Wramba
43f7cf0f12 No redirect when Devise API is accessed via JSON 2013-05-07 10:18:23 +02:00
Carlos Antonio da Silva
bb5d65209a Change rubygems source to use https [ci skip] 2013-05-06 23:04:49 -03:00
Carlos Antonio da Silva
69f79ad446 Let Devise play with both Rails 3.2 and Rails 4 for now 2013-05-05 19:55:06 -03:00
Victor Cruz Dueñas
75fdd2944d Avoid hash mutation 2013-05-05 10:12:57 +02:00
Victor Cruz Dueñas
ae48fc8419 Refactor to avoid duplication on param filter 2013-05-05 01:19:37 +02:00
Victor Cruz Dueñas
d6d61fc5be Adding tests for case_insensitive_keys and strip_whitespace_keys to param filter 2013-05-05 01:02:48 +02:00
Victor Cruz Dueñas
19c8f0c0ad Merge remote-tracking branch 'upstream/master'
Conflicts:
	app/controllers/devise/registrations_controller.rb
	test/integration/registerable_test.rb
2013-05-05 00:20:34 +02:00
Rafael Mendonça França
63627d1439 Refactoring the code a little bit
* Rename #get_constraints_given_method to #constraints_for to make the
  method clear.

* The method name now is required.

* Use symbols instead of strings.

* Make #constraints_for a protected method.
2013-05-04 14:33:55 -03:00
José Valim
662f0e76d8 Merge pull request #2401 from jd-erreape/master
Refactor to avoid repeated code
2013-05-04 09:06:16 -07:00
DI2uNk
eadce2fef6 Refactored rails/routes.rb to avoid repeated code 2013-05-04 11:56:56 +02:00
Carlos Antonio da Silva
0fe0373144 Fix location of parameter sanitizer in docs [ci skip] 2013-05-03 22:52:26 -03:00
Carlos Antonio da Silva
1f9ebbd9f4 Update gemspec dependency to Rails 4 rc1 as well 2013-05-03 22:04:27 -03:00
Carlos Antonio da Silva
a0058d5fbf Add some spaces, remove comment 2013-05-03 21:52:00 -03:00
Carlos Antonio da Silva
e8d1c9ca23 Bump rails version to 4.0.0.rc1, closes #2399 2013-05-03 10:00:39 -03:00
Carlos Antonio da Silva
d9d5ae3d58 Correct OrderedHash initialization to ensure keys order in 1.8.7
This should hopefully fix the build with 1.8.7 🙏
2013-05-01 21:35:03 -03:00
Rafael Mendonça França
b51c7fe59b Merge pull request #2396 from nickborromeo/show_license_in_gemspec
Fix gemspec so that MIT license will be visible when running the -d flag

Closes #2390
2013-04-30 10:34:54 -07:00
Nick Borromeo
a6b754b697 Fix gemspec so that MIT license will be visible when running the -d flag 2013-04-30 10:23:50 -07:00
Michiel Prins
92218e9ecc Remove unnecessary code 2013-04-29 15:21:31 +02:00
Michiel Prins
60e933df73 Add destroy_with_password method 2013-04-29 15:06:13 +02:00
José Valim
b451fc0aad Merge pull request #2391 from stereoscott/patch-1
Fix spelling error in doc block
2013-04-28 22:20:59 -07:00
Scott M
2f28e48f54 Fix spelling error in doc block 2013-04-29 01:52:37 -03:00
Carlos Antonio da Silva
76e4967ca1 Update travis-ci link in README [ci skip] 2013-04-28 13:06:08 -03:00
Vasiliy Ermolovich
dceb788c6b fix OrderedHash initialization 2013-04-23 10:37:10 +03:00
Vasiliy Ermolovich
fae8e977e8 use ordered hash to fix tests on ruby 1.8 2013-04-22 22:42:49 +03:00
Vasiliy Ermolovich
0a588fab3a update CHANGELOG [ci skip] 2013-04-22 17:51:54 +03:00
Vasiliy Ermolovich
bbf57214ac Merge pull request #2384 from worker8/after_reset_password_redirect_path
Add ability to override the redirect path after user has reset their password
2013-04-22 07:36:41 -07:00
Tan Jun Rong
804fbdf6d5 Fix spelling error, 'reseting' to 'resetting' 2013-04-22 22:25:40 +08:00
Tan Jun Rong
e4987e8bb7 Fix resource_name to resource 2013-04-22 21:40:52 +08:00
Tan Jun Rong
9d5a9c8a61 Add ability to override the redirect path after user has reset their password 2013-04-22 20:22:53 +08:00
Carlos Antonio da Silva
c8aa5f3e62 Bump webrat to 0.7.3 2013-04-19 20:38:39 -03:00
Carlos Antonio da Silva
df4b282566 Set variable to false instead of nil 2013-04-19 19:59:08 -03:00
Carlos Antonio da Silva
b8c5d76c5a Merge pull request #2380 from vipulnsward/fix_warnings
fix some warnings
2013-04-19 15:53:43 -07:00
Vipul A M
b871bd5036 fix some warning 2013-04-19 19:08:20 +05:30
José Valim
c439b80524 Merge pull request #2381 from vipulnsward/enable_warinings
enable warnings by default
2013-04-18 13:40:01 -07:00
Rafael Mendonça França
704221d48f Merge pull request #2379 from vipulnsward/remove_unused_vars
Remove unused variables and fix typos
2013-04-18 06:38:32 -07:00
Vipul A M
da70348662 enable warnings by default 2013-04-18 11:07:36 +05:30
Vipul A M
2e6457006e Remove unused variables and fix typos 2013-04-18 10:24:38 +05:30
Carlos Antonio da Silva
1f68309c47 ✂️ changelog [ci skip] 2013-04-15 15:50:06 -03:00
José Valim
c618969677 Update README.md 2013-04-14 08:49:30 -07:00
Lucas Mazza
93013c2e89 Merge pull request #2366 from hauleth/extract-lookup-for-i18n
Extract get_message
2013-04-14 08:21:19 -07:00
José Valim
8ec89bf659 Update README.md 2013-04-13 23:39:32 -07:00
José Valim
b3edfeab73 Update README.md 2013-04-13 23:35:58 -07:00
José Valim
c63483ae24 Merge branch 'latortuga-rails4-sp' into rails4 2013-04-13 23:34:25 -07:00
José Valim
3ed0dc5d9f Update README 2013-04-13 23:34:07 -07:00
José Valim
8a93c34080 Clean up Devise parameter sanitizer 2013-04-13 23:21:46 -07:00
José Valim
2dfa7e1761 Update CHANGELOG 2013-04-13 22:10:48 -07:00
José Valim
5bf4f57fcf Tidy up devise configuration 2013-04-13 22:07:54 -07:00
José Valim
1b8fd7c2ff Merge pull request #2271 from robhurring/master
Allowing http token auth to set the token_authentication_key if missing from params
2013-04-13 21:39:36 -07:00
Carlos Antonio da Silva
f75352a373 Merge branch 'master' into rails4 2013-04-13 11:37:48 -03:00
Carlos Antonio da Silva
fa5ae57ce4 Use instance_eval instead of Proc#bind
Keep the implementation more similar to how it works in Action Mailer,
and avoid deprecation warnings with Proc#bind being raised in rails4
branch.
2013-04-13 11:35:51 -03:00
Carlos Antonio da Silva
ac2ebdfb11 Fix session store changed in Rails master
There's no encrypted cookie store anymore, by default the cookie store
will be encrypted.
2013-04-13 11:16:11 -03:00
Carlos Antonio da Silva
ea94e199ce Bundle update 2013-04-13 11:14:13 -03:00
Carlos Antonio da Silva
d89dad5728 Bundle update for both Rails 3.1 and 3.2, update mocha, fix failing tests 2013-04-13 11:08:27 -03:00
Carlos Antonio da Silva
32a141d2a9 Fix typo in test descriptions 2013-04-13 10:54:52 -03:00
Carlos Antonio da Silva
36557ef641 ✂️ [ci skip] 2013-04-13 10:53:49 -03:00
José Valim
aa24335656 Merge pull request #2371 from tomasv/custom-devise-mailer-default-proc-fix
Fix devise sender bug with custom devise mailers.
2013-04-12 08:37:31 -07:00
Tomas Varneckas
1acd3d1790 Fix devise sender bug with custom devise mailers.
The devise sender detection must take into account that the default
sender set in the custom devise mailer can be a proc.
2013-04-12 16:48:48 +03:00
Drew Ulmer
d20fdf87b6 Introduce BaseSanitizer null sanitizer and controller-specific callbacks
This updates Devise's StrongParameter support to feature:

- A Null base sanitizer to support existing Rails 3.x installations that
  don't want to use StrongParameters yet
- A new, simpler API for ParameterSanitizer: #permit, #permit!, and #forbid
- Overrideable callbacks on a controller-basis, e.g. #create_sessions_params
  for passing the current scope's parameters through StrongParameters and
  a helper method, whitelisted_params, for rolling your own implementations
  of #create_x_params in your own controllers.
- Lots of tests!
2013-04-10 10:33:50 -05:00
Łukasz Niemier
95f56258d7 Rename get_message to find_message and fix set_flash_message 2013-04-07 08:52:11 +02:00
Łukasz Niemier
8e9ad4626e Extract get_message 2013-04-06 18:46:21 +02:00
José Valim
2de7cbae25 Merge pull request #2363 from eloyesp/documenting_protected_methods
Generate documentation for protected methods.
2013-04-04 06:52:08 -07:00
Eloy Espinaco
37473cdaf7 Add config to customize documentation. 2013-04-04 09:48:33 -03:00
Lucas Mazza
bf30d79aca Update rubygems url inside Gemfile.lock 2013-04-03 10:22:46 -03:00
José Valim
148fa99dce Merge pull request #2330 from pungoyal/master
Language copy changes
2013-04-01 12:20:02 -07:00
Drew Ulmer
77203e3d97 Change parameter sanitizer instance method to scope to devise
This way it's very explicit that this method is for devise and it won't
run into any naming collisions with user code.
2013-04-01 09:46:46 -05:00
Drew Ulmer
b151d2cfe2 Remove MassAssignment security from Mongoid test shim 2013-04-01 09:00:36 -05:00
Drew Ulmer
e0ffe8f85f Fix internal helper test referencing resource_params 2013-03-31 21:31:54 -05:00
Drew Ulmer
78f137368c Add support for Rails 4 strong_parameters
This brings support for Rails 4 StrongParameters changes.

- Parameter sanitizing is setup for Devise controllers via
  resource_params except Omniauth Callbacks which doesn't use
  resource_params.

- Change #build_resource to not call resource_params for get requests.
  Parameter sanitizing is only needed when params are posted to the
  server so there's no need to try to construct resource params on get
  requests (new, edit).
2013-03-31 21:31:48 -05:00
Drew Ulmer
af4a582300 Remove mass-assignment role-based tests, no longer supported in Rails 4
Mass-assignment security roles are removed in Rails 4 so there's no need
to test :as => :role behavior.
2013-03-31 15:21:49 -05:00
Drew Ulmer
2f88f7c0ed Remove protected_attributes gem and all whitelisting 2013-03-31 15:21:49 -05:00
Lucas Mazza
ce37c301ff Update Rails dependency 2013-03-31 17:19:10 -03:00
Lucas Mazza
bd14589fe4 Ensure that include_root_in_json is true since our test suite depends on that. 2013-03-31 17:18:41 -03:00
Lucas Mazza
c07bc69fad Install Mongoid in Ruby 2.0 2013-03-31 17:18:02 -03:00
Rafael Mendonça França
9a8cb011d7 Use the latests Rails version 2013-03-28 14:00:55 -03:00
Rafael Mendonça França
335a6af861 Merge branch 'master' into rails4 2013-03-28 13:51:12 -03:00
Vasiliy Ermolovich
72cbafa322 Merge pull request #2340 from scottjacobsen/master
s/reseting/resetting

[ci skip]
2013-03-22 00:17:20 -07:00
Scott Jacobsen
4549d8c65f Update recoverable.rb
Fix type-o.
2013-03-21 18:49:19 -06:00
Vasiliy Ermolovich
6c566c1ca4 Merge pull request #2331 from yxhuvud/master
License information to gemspec.
[ci skip]
2013-03-16 09:06:04 -07:00
linus
41aed807fc Add license to gemspec. 2013-03-16 09:29:46 +01:00
Puneet Goyal
ddea9359a6 Removing an extra full stop 2013-03-15 15:19:52 +05:30
Puneet Goyal
5d87e150f7 removing an extra full stop 2013-03-15 15:18:45 +05:30
José Valim
d90e365636 Merge pull request #2315 from neo/http_auth_key
Allow explicit configuration of http auth key
2013-03-07 09:43:08 -08:00
Lucas Mazza
22442907af Fix send_devise_notification arity in the documentation.
[ci skip]
2013-03-05 15:55:19 -03:00
robhurring
10f58b636f update devise config template with new allow_token_authenticatable_via_headers options 2013-03-04 17:38:36 -05:00
robhurring
2d14bd2826 removing params hash merging of token and mimicking http basic auth flow 2013-03-04 17:33:27 -05:00
Matt Jones + Tony Schneider
f4ceecece4 Allow explicit configuration of http auth key
- Fix basic auth case in which authorized_keys is configured as hash
- Duplicate existing functionality when http_auth_key is not explicitly
  set
2013-03-04 12:23:05 -05:00
José Valim
359fdd840c Merge pull request #2311 from pixeltrix/improve-delayed-email-documentation
Improve documentation on sending delayed emails
2013-03-01 06:49:39 -08:00
Andrew White
c6578250d2 Improve documentation on sending delayed emails
There are a couple of gotchas in the existing documentation
about the `send_devise_notification` hook.

1.  The `after_commit` callback can be called multiple times
    so you should clear the array otherwise any additional
    invocations will trigger extra copies of the email.

2.  The `after_commit` callback is only called when a record
    is created or updated so you need to check for `new_record?`
    or `changed?` before adding it to `pending_notifications`
    otherwise it's okay to send it immediately.

The `new_record? || changed?` condition is necessary because
the latter isn't always true for new records, e.g:

    >> User.new.changed?
    => false

[ci skip]
2013-03-01 14:32:15 +00:00
José Valim
dc14c76ff6 Merge pull request #2308 from vfrride/patch-1
updates source url to use https
2013-02-27 18:59:31 -08:00
vfrride
5e74fd406b updates source url to use https 2013-02-27 21:39:45 -05:00
José Valim
ebeee33429 Run image optimizer on the logo (i'm done) 2013-02-26 11:36:25 -07:00
José Valim
e449c3b6d2 Update badges 2013-02-26 11:27:58 -07:00
José Valim
58871172ab Crop the logo a bit more 💣 2013-02-26 11:25:26 -07:00
José Valim
41a2d65ade Reduce logo dimentions 2013-02-26 11:23:11 -07:00
José Valim
e6dc425abb Add Devise logo 2013-02-26 11:19:48 -07:00
Carlos Antonio da Silva
d29b744d92 Enable Ruby 2.0 in travis 2013-02-25 22:13:48 -03:00
Carlos Antonio da Silva
e79ebe8aec Fix last mongoid tests since it does not have the order method 2013-02-25 22:13:36 -03:00
Santiago Pastorino
10f93129c3 Rails 4 now raises ActionController::UrlGenerationError
This is the commit in Rails
https://github.com/rails/rails/commit/db06d128
2013-02-25 22:12:21 -03:00
Santiago Pastorino
04d9512f30 We need to do match via [get, post] 2013-02-25 22:12:20 -03:00
Santiago Pastorino
135c8da390 To be able to post to root via is now needed 2013-02-25 22:12:20 -03:00
Carlos Antonio da Silva
aca7e5d162 Run tests with mongoid 2013-02-25 22:12:20 -03:00
Carlos Antonio da Silva
02298117a0 Do not remove app/mailers from autoloaded paths 2013-02-25 22:12:06 -03:00
Carlos Antonio da Silva
7998d6f878 Match full template name 2013-02-25 22:12:06 -03:00
Vasiliy Ermolovich
ed6e232756 assert_recognizes rises Assertion instead of RoutingError 2013-02-25 22:12:06 -03:00
Carlos Antonio da Silva
567fabbbc6 Disable forcing whitelist attributes from protected attributes
This was the previous functionality since we didn't set anything in the
application configuration. Now when using protected attributes gem, it
sets whitelist to true, forcing us to always declare the accessible
attributes, and this is not the case for the Admin model.
2013-02-25 22:12:06 -03:00
Carlos Antonio da Silva
d77a956276 Remove AR deprecated finder warnings 2013-02-25 22:12:06 -03:00
Carlos Antonio da Silva
3c885e043d Fix changed error messages from confirmation validation 2013-02-25 22:12:06 -03:00
Carlos Antonio da Silva
9ae013ae3c Updating test app running rake rails:update, tests running with failures 2013-02-25 22:12:06 -03:00
Carlos Antonio da Silva
1bae64d8c4 Update dependencies for Rails 4 2013-02-25 22:11:49 -03:00
Carlos Antonio da Silva
f8792c8cf0 Update to Rails 3-2-stable and fix failing tests 2013-02-25 22:06:10 -03:00
Lucas Mazza
198bfff2de Merge pull request #2300 from fphilipe/scoped-serialization
Make use of warden's scoped serialization
2013-02-25 15:32:43 -08:00
Lucas Mazza
d3f0665105 Merge pull request #2305 from gregates/feature/skip_confirmation_notice!
Changelog for #2296
2013-02-25 15:31:56 -08:00
Greg Gates
77b960f14a Changelog for #2296 2013-02-25 18:23:43 -05:00
José Valim
b388aae473 Merge pull request #2302 from islandr/master
Mention devise-encryptable requirement in initializer template
2013-02-25 14:05:15 -08:00
José Valim
81c6d70b7c Merge pull request #2296 from gregates/feature/skip_confirmation_notice!
Add #skip_confirmation_notification! to Confirmable
2013-02-25 14:01:54 -08:00
Ryan Mohr
f3928d8462 Mention devise-encryptable requirement for anything but bcrypt. 2013-02-25 10:42:06 -10:00
Philipe Fatio
c22d755cf4 Make use of warden's scoped serialization 2013-02-25 07:38:42 +01:00
Greg Gates
72cfaad618 Add #skip_confirmation_notification to Confirmable 2013-02-22 12:43:01 -05:00
José Valim
22897150d8 Merge pull request #2278 from plataformatec/issue-2275
allow_unconfirmed_access_for set to nil means unconfirmed access for unlimited time
2013-02-14 11:30:51 -08:00
Vasiliy Ermolovich
395a69b4ef allow_unconfirmed_access_for set to nil means unconfirmed access for unlimited time
closes #2275
2013-02-13 21:17:38 +03:00
Rob
547439d94c renaming devise option "allow_authorization_to_set_auth_token" to "allow_token_authenticatable_via_headers" 2013-02-10 12:50:52 -05:00
Rob
84f743c4ef adding http token auth options to env[devise.token_options] 2013-02-10 12:48:02 -05:00
Rob
22a8cfe6d3 fix hanging line on method call 2013-02-09 15:19:42 -05:00
Rob
3025b7e2f7 Allow http token authorization to set token_authentication_key in place of passing it in via params
It will not override existing token_authentication_key params if they are present.
2013-02-09 15:12:36 -05:00
Vasiliy Ermolovich
1b2460171e Merge pull request #2261 from plataformatec/issue-2253
use scoped path to shared views if scope is present
2013-02-08 15:43:39 -08:00
Vasiliy Ermolovich
f822f92321 use scoped path to shared views if scope is present
closes #2253
2013-02-09 02:35:06 +03:00
Lucas Mazza
042ba76480 Merge pull request #2263 from sboesen/patch-1
Typo - Update lib/generators/templates/devise.rb
2013-02-06 17:08:36 -08:00
Stefan Boesen
3458e12274 Update lib/generators/templates/devise.rb
Typo in template comment.
2013-02-06 16:30:00 -08:00
José Valim
d9364f7a4a Update CHANGELOG.rdoc
Close #2254
2013-02-01 09:30:43 -07:00
José Valim
fd0db0b188 Merge pull request #2251 from latortuga/2190-test-case
Add test for Issue #2190
2013-02-01 07:58:00 -08:00
Drew Ulmer
c9c1e13743 Add test for Issue #2190
Seems to be passing for me.
2013-01-31 10:05:53 -06:00
José Valim
25296d8c6f Add tests for sign out with redirect, related to #2249 2013-01-30 08:28:51 -07:00
José Valim
34c7981f69 Merge pull request #2248 from bvsatyaram/patch-1
Update README.md
2013-01-30 07:11:43 -08:00
B V Satyaram
f7a658e13d Update README.md
Devise is composed of 11 modules instead of 12.
2013-01-30 15:17:36 +05:30
José Valim
1d639bd0c5 Merge pull request #2247 from waldyr/patch-1
correcting tiny typo
2013-01-29 17:01:04 -08:00
Waldyr Guimarães Araújo de Souza
5ee07390b7 correcting tiny typo 2013-01-29 22:45:23 -02:00
Carlos Antonio da Silva
83ad67bd51 Fix inheriting mailer templates from Devise::Mailer
Previously inheriting from Devise::Mailer would not render default views
from devise when the inheriting mailer didn't have the view. Now it'll
correctly pick the default one from Devise::Mailer.
2013-01-29 00:08:26 -02:00
Carlos Antonio da Silva
72be1f1289 Match against string value, no need to create regexps 2013-01-28 23:59:15 -02:00
Carlos Antonio da Silva
0285565322 Actually fix this test by forcing to_s on the id 2013-01-28 21:40:11 -02:00
Carlos Antonio da Silva
acc3adb2c1 Use #next instead of calculating id + 1
The id attribute is not Integer in Mongo, so it fails with something like:

    NoMethodError: undefined method `+' for "5106fc06ee6da1ee44000002":Moped::BSON::ObjectId'`

With #next, it will work with both Integer and String ids, for both AR
and Mongo, returning a different id to test for filtered conditions.
2013-01-28 20:46:21 -02:00
Carlos Antonio da Silva
af37800c1d Change match routes to get / post
match without a verb is deprecated in Rails master.
2013-01-28 20:23:13 -02:00
Carlos Antonio da Silva
86eecc6606 Change "ActionController::IntegrationTest" to "ActionDispatch::IntegrationTest" 2013-01-28 19:58:21 -02:00
Rafael Mendonça França
349aab72f0 No need to test against ree since we are testing with 1.8.7 2013-01-28 13:50:08 -02:00
Rafael Mendonça França
bfa65dde70 Use the Ruby 1.8 hash syntax.
Yes we still support Ruby 1.8 😢
2013-01-28 13:21:44 -02:00
José Valim
d099d8f0ac Release v2.2.3 2013-01-26 11:43:17 -07:00
José Valim
5190f52857 Require string conversion for all values 2013-01-26 11:42:42 -07:00
José Valim
5790107f49 Merge pull request #2235 from camelmasa/sorted_locale_file
sorted locale file
2013-01-22 19:11:38 -08:00
camelmasa
6fd21ae37e sorted locale file 2013-01-23 10:39:58 +09:00
Vasiliy Ermolovich
b95c321660 update Gemfile.lock 2013-01-21 20:14:59 +03:00
Carlos Antonio da Silva
0061f113db Fix indent [ci skip] 2013-01-20 21:49:45 -02:00
José Valim
1fb3fbbd88 Merge pull request #2230 from nashby/issue-2218
add key option to rememberable_options
2013-01-20 12:23:21 -08:00
Vasiliy Ermolovich
d3f8bd6cae add key option to rememberable_options
closes #2218
2013-01-20 23:16:25 +03:00
José Valim
0642e2fc9b Merge pull request #2223 from jayshepherd/master
Allow parent_mailer to be customizable via Devise.parent_mailer ... (#2219)
2013-01-18 05:35:55 -08:00
Jay Shepherd
cc017b1f0d Allow parent_mailer to be customizable via Devise.parent_mailer, useful for engines 2013-01-18 02:26:41 -06:00
Víctor Manuel Cruz Dueñas
3511f8ac00 Checking if unconfirmed_email has changed before to set update_needs_confirmation flash message. 2012-07-05 19:10:34 +02:00
95 changed files with 1351 additions and 759 deletions

View File

@@ -1,35 +1,13 @@
language: ruby
script: "bundle exec rake test"
rvm:
- 1.8.7
- 1.9.2
- 1.9.3
- ree
- 2.0.0
env:
- DEVISE_ORM=mongoid
- DEVISE_ORM=active_record
matrix:
exclude:
- rvm: ree
env: DEVISE_ORM=mongoid
gemfile: Gemfile
- rvm: ree
env: DEVISE_ORM=mongoid
gemfile: gemfiles/Gemfile.rails-3.1.x
- rvm: 1.8.7
env: DEVISE_ORM=mongoid
gemfile: Gemfile
- rvm: 1.8.7
env: DEVISE_ORM=mongoid
gemfile: gemfiles/Gemfile.rails-3.1.x
- rvm: 1.9.2
env: DEVISE_ORM=mongoid
gemfile: Gemfile
- rvm: 1.9.2
env: DEVISE_ORM=mongoid
gemfile: gemfiles/Gemfile.rails-3.1.x
gemfile:
- gemfiles/Gemfile.rails-3.1.x
- gemfiles/Gemfile.rails-3.2.x
- Gemfile
services:
- mongodb

9
.yardopts Normal file
View File

@@ -0,0 +1,9 @@
--protected
--no-private
--embed-mixin ClassMethods
-
README.md
CHANGELOG.rdoc
CONTRIBUTING.md
MIT-LICENSE

View File

@@ -1,3 +1,32 @@
== 3.0.0.rc
* enhancements
* Rails 4 and Strong Parameters compatibility. (@carlosantoniodasilva, @josevalim, @latortuga, @lucasmazza, @nashby, @rafaelfranca, @spastorino)
* Drop support for Rails < 3.2 and Ruby < 1.9.3.
== 2.2.4
* enhancements
* Add `destroy_with_password` to `DatabaseAuthenticatable`. Allows destroying a record when `:current_password` matches, similarly to how `update_with_password` works. (by @michiel3)
* Allow to override path after password resetting (by @worker8)
* Add `#skip_confirmation_notification!` method to `Confirmable`. Allows skipping confirmation email without auto-confirming. (by @gregates)
* allow_unconfirmed_access_for config from `:confirmable` module can be set to `nil` that means unconfirmed access for unlimited time. (by @nashby)
* Support Rails' token strategy on authentication (by @robhurring)
* Support explicitly setting the http authentication key via `config.http_authentication_key` (by @neo)
* bug fix
* Do not redirect when accessing devise API via JSON. (by @sebastianwr)
* Generating scoped devise views now uses the correct scoped shared links partial instead of the default devise one (by @nashby)
* Fix inheriting mailer templates from `Devise::Mailer`
* Fix a bug when procs are used as default mailer in Devise (by @tomasv)
== 2.2.3
Security announcement: http://blog.plataformatec.com.br/2013/01/security-announcement-devise-v2-2-3-v2-1-3-v2-0-5-and-v1-5-3-released/
* bug fix
* Require string conversion for all values
== 2.2.2
* bug fix

15
Gemfile
View File

@@ -1,8 +1,8 @@
source "http://rubygems.org"
source "https://rubygems.org"
gemspec
gem "rails", "~> 3.2.6"
gem "rails", "~> 4.0.0.rc1"
gem "omniauth", "~> 1.0.0"
gem "omniauth-oauth2", "~> 1.0.0"
gem "rdoc"
@@ -10,8 +10,8 @@ gem "rdoc"
group :test do
gem "omniauth-facebook"
gem "omniauth-openid", "~> 1.0.1"
gem "webrat", "0.7.2", :require => false
gem "mocha", "0.10.0", :require => false
gem "webrat", "0.7.3", :require => false
gem "mocha", "~> 0.13.1", :require => false
end
platforms :jruby do
@@ -24,9 +24,8 @@ platforms :ruby do
gem "sqlite3"
end
platforms :mri_19 do
platforms :mri_19, :mri_20 do
group :mongoid do
gem "mongoid", "~> 3.0"
gem "mongoid", github: "mongoid/mongoid", branch: "master"
end
end
end

View File

@@ -1,74 +1,78 @@
GIT
remote: git://github.com/mongoid/mongoid.git
revision: fe7f43430580860db6d1d89cea27eda24ab60ab1
branch: master
specs:
mongoid (4.0.0)
activemodel (~> 4.0.0.rc1)
moped (~> 1.4.2)
origin (~> 1.0)
tzinfo (~> 0.3.22)
PATH
remote: .
specs:
devise (2.2.1)
devise (3.0.0.rc)
bcrypt-ruby (~> 3.0)
orm_adapter (~> 0.1)
railties (~> 3.1)
railties (>= 3.2.6, < 5)
warden (~> 1.2.1)
GEM
remote: http://rubygems.org/
remote: https://rubygems.org/
specs:
actionmailer (3.2.11)
actionpack (= 3.2.11)
mail (~> 2.4.4)
actionpack (3.2.11)
activemodel (= 3.2.11)
activesupport (= 3.2.11)
builder (~> 3.0.0)
actionmailer (4.0.0.rc1)
actionpack (= 4.0.0.rc1)
mail (~> 2.5.3)
actionpack (4.0.0.rc1)
activesupport (= 4.0.0.rc1)
builder (~> 3.1.0)
erubis (~> 2.7.0)
journey (~> 1.0.4)
rack (~> 1.4.0)
rack-cache (~> 1.2)
rack-test (~> 0.6.1)
sprockets (~> 2.2.1)
activemodel (3.2.11)
activesupport (= 3.2.11)
builder (~> 3.0.0)
activerecord (3.2.11)
activemodel (= 3.2.11)
activesupport (= 3.2.11)
arel (~> 3.0.2)
tzinfo (~> 0.3.29)
activeresource (3.2.11)
activemodel (= 3.2.11)
activesupport (= 3.2.11)
activesupport (3.2.11)
i18n (~> 0.6)
multi_json (~> 1.0)
arel (3.0.2)
rack (~> 1.5.2)
rack-test (~> 0.6.2)
activemodel (4.0.0.rc1)
activesupport (= 4.0.0.rc1)
builder (~> 3.1.0)
activerecord (4.0.0.rc1)
activemodel (= 4.0.0.rc1)
activerecord-deprecated_finders (~> 1.0.2)
activesupport (= 4.0.0.rc1)
arel (~> 4.0.0)
activerecord-deprecated_finders (1.0.2)
activesupport (4.0.0.rc1)
i18n (~> 0.6, >= 0.6.4)
minitest (~> 4.2)
multi_json (~> 1.3)
thread_safe (~> 0.1)
tzinfo (~> 0.3.37)
arel (4.0.0)
atomic (1.1.8)
bcrypt-ruby (3.0.1)
builder (3.0.4)
builder (3.1.4)
erubis (2.7.0)
faraday (0.8.4)
faraday (0.8.7)
multipart-post (~> 1.1)
hashie (1.2.0)
hike (1.2.1)
hike (1.2.2)
httpauth (0.2.0)
i18n (0.6.1)
journey (1.0.4)
json (1.7.6)
jwt (0.1.5)
multi_json (>= 1.0)
mail (2.4.4)
i18n (0.6.4)
json (1.7.7)
jwt (0.1.8)
multi_json (>= 1.5)
mail (2.5.3)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
metaclass (0.0.1)
mime-types (1.19)
mocha (0.10.0)
mime-types (1.23)
minitest (4.7.4)
mocha (0.13.3)
metaclass (~> 0.0.1)
mongoid (3.0.16)
activemodel (~> 3.1)
moped (~> 1.1)
origin (~> 1.0)
tzinfo (~> 0.3.22)
moped (1.3.2)
multi_json (1.5.0)
multipart-post (1.1.5)
nokogiri (1.5.5)
oauth2 (0.8.0)
moped (1.4.5)
multi_json (1.7.2)
multipart-post (1.2.0)
nokogiri (1.5.9)
oauth2 (0.8.1)
faraday (~> 0.8)
httpauth (~> 0.1)
jwt (~> 0.1.4)
@@ -85,53 +89,53 @@ GEM
omniauth-openid (1.0.1)
omniauth (~> 1.0)
rack-openid (~> 1.3.1)
origin (1.0.11)
origin (1.1.0)
orm_adapter (0.4.0)
polyglot (0.3.3)
rack (1.4.3)
rack-cache (1.2)
rack (>= 0.4)
rack (1.5.2)
rack-openid (1.3.1)
rack (>= 1.1.0)
ruby-openid (>= 2.1.8)
rack-ssl (1.3.2)
rack
rack-test (0.6.2)
rack (>= 1.0)
rails (3.2.11)
actionmailer (= 3.2.11)
actionpack (= 3.2.11)
activerecord (= 3.2.11)
activeresource (= 3.2.11)
activesupport (= 3.2.11)
bundler (~> 1.0)
railties (= 3.2.11)
railties (3.2.11)
actionpack (= 3.2.11)
activesupport (= 3.2.11)
rack-ssl (~> 1.3.2)
rails (4.0.0.rc1)
actionmailer (= 4.0.0.rc1)
actionpack (= 4.0.0.rc1)
activerecord (= 4.0.0.rc1)
activesupport (= 4.0.0.rc1)
bundler (>= 1.3.0, < 2.0)
railties (= 4.0.0.rc1)
sprockets-rails (~> 2.0.0.rc4)
railties (4.0.0.rc1)
actionpack (= 4.0.0.rc1)
activesupport (= 4.0.0.rc1)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (>= 0.14.6, < 2.0)
rake (10.0.3)
rdoc (3.12)
thor (>= 0.18.1, < 2.0)
rake (10.0.4)
rdoc (4.0.1)
json (~> 1.4)
ruby-openid (2.2.2)
sprockets (2.2.2)
ruby-openid (2.2.3)
sprockets (2.9.3)
hike (~> 1.2)
multi_json (~> 1.0)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sqlite3 (1.3.6)
thor (0.16.0)
tilt (1.3.3)
sprockets-rails (2.0.0.rc4)
actionpack (>= 3.0)
activesupport (>= 3.0)
sprockets (~> 2.8)
sqlite3 (1.3.7)
thor (0.18.1)
thread_safe (0.1.0)
atomic
tilt (1.4.0)
treetop (1.4.12)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.35)
tzinfo (0.3.37)
warden (1.2.1)
rack (>= 1.0)
webrat (0.7.2)
webrat (0.7.3)
nokogiri (>= 1.2.0)
rack (>= 1.0)
rack-test (>= 0.5.3)
@@ -144,13 +148,13 @@ DEPENDENCIES
activerecord-jdbcsqlite3-adapter
devise!
jruby-openssl
mocha (= 0.10.0)
mongoid (~> 3.0)
mocha (~> 0.13.1)
mongoid!
omniauth (~> 1.0.0)
omniauth-facebook
omniauth-oauth2 (~> 1.0.0)
omniauth-openid (~> 1.0.1)
rails (~> 3.2.6)
rails (~> 4.0.0.rc1)
rdoc
sqlite3
webrat (= 0.7.2)
webrat (= 0.7.3)

View File

@@ -1,8 +1,10 @@
## Devise
![Devise Logo](https://raw.github.com/plataformatec/devise/master/devise.png)
By [Plataformatec](http://plataformatec.com.br/).
[![Build Status](https://secure.travis-ci.org/plataformatec/devise.png?branch=master)](http://travis-ci.org/plataformatec/devise)
[![Code Climate](https://codeclimate.com/badge.png)](https://codeclimate.com/github/plataformatec/devise)
[![Gem Version](https://fury-badge.herokuapp.com/rb/devise.png)](http://badge.fury.io/rb/devise)
[![Build Status](https://api.travis-ci.org/plataformatec/devise.png?branch=master)](http://travis-ci.org/plataformatec/devise)
[![Code Climate](https://codeclimate.com/github/plataformatec/devise.png)](https://codeclimate.com/github/plataformatec/devise)
This README is [also available in a friendly navigable format](http://devise.plataformatec.com.br/).
@@ -13,7 +15,7 @@ Devise is a flexible authentication solution for Rails based on Warden. It:
* Allows you to have multiple roles (or models/scopes) signed in at the same time;
* Is based on a modularity concept: use just what you really need.
It's composed of 12 modules:
It's composed of 11 modules:
* [Database Authenticatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/DatabaseAuthenticatable): encrypts and stores a password in the database to validate the authenticity of a user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.
* [Token Authenticatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/TokenAuthenticatable): signs in a user based on an authentication token (also known as "single access token"). The token can be given both through query string or HTTP Basic Authentication.
@@ -55,7 +57,7 @@ You can view the Devise documentation in RDoc format here:
http://rubydoc.info/github/plataformatec/devise/master/frames
If you need to use Devise with Rails 2.3, you can always run "gem server" from the command line after you install the gem to access the old documentation.
If you need to use Devise with previous versions of Rails, you can always run "gem server" from the command line after you install the gem to access the old documentation.
### Example applications
@@ -88,7 +90,7 @@ Once you have solidified your understanding of Rails and authentication mechanis
## Getting started
Devise 2.0 works with Rails 3.1 onwards. You can add it to your Gemfile with:
Devise 3.0 works with Rails 3.2 onwards. You can add it to your Gemfile with:
```ruby
gem 'devise'
@@ -141,7 +143,7 @@ user_session
After signing in a user, confirming the account or updating the password, Devise will look for a scoped root path to redirect. Example: For a :user resource, it will use `user_root_path` if it exists, otherwise default `root_path` will be used. This means that you need to set the root inside your routes:
```ruby
root :to => "home#index"
root to: "home#index"
```
You can also overwrite `after_sign_in_path_for` and `after_sign_out_path_for` to customize your redirect hooks.
@@ -174,34 +176,31 @@ devise :database_authenticatable, :registerable, :confirmable, :recoverable, :st
Besides :stretches, you can define :pepper, :encryptor, :confirm_within, :remember_for, :timeout_in, :unlock_in and other values. For details, see the initializer file that was created when you invoked the "devise:install" generator described above.
### Configuring multiple models
### Strong Parameters
Devise allows you to set up as many roles as you want. For example, you may have a User model and also want an Admin model with just authentication and timeoutable features. If so, just follow these steps:
When you customize your own views, you may end up adding new attributes to forms. Rails 4 moved the parameter sanitization from the model to the controller, causing Devise to handle this concern at the controller as well.
There are just three actions in Devise that allows any set of parameters to be passed down to the model, therefore requiring sanitization. Their names and the permited parameters by default are:
* `sign_in` (`Devise::SessionsController#new`) - Permits only the authentication keys (like `email`)
* `sign_up` (`Devise::RegistrationsController#create`) - Permits authentication keys plus `password` and `password_confirmation`
* `account_update` (`Devise::RegistrationsController#update`) - Permits authentication keys plus `password`, `password_confirmation` and `current_password`
In case you want to customize the permitted parameters (the lazy way™) you can do with a simple before filter in your `ApplicationController`:
```ruby
# Create a migration with the required fields
create_table :admins do |t|
t.string :email
t.string :encrypted_password
t.timestamps
class ApplicationController < ActionController::Base
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email) }
end
end
# Inside your Admin model
devise :database_authenticatable, :timeoutable
# Inside your routes
devise_for :admins
# Inside your protected controller
before_filter :authenticate_admin!
# Inside your controllers and views
admin_signed_in?
current_admin
admin_session
```
On the other hand, you can simply run the generator!
The example above overrides the permitted parameters for the user to be both `:username` and `:email`. The non-lazy way to configure parameters would be by defining the before filter above in a custom controller. We detail how to configure and customize controllers in some sections below.
### Configuring views
@@ -351,15 +350,40 @@ You can read more about Omniauth support in the wiki:
* https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview
### Configuring multiple models
Devise allows you to set up as many roles as you want. For example, you may have a User model and also want an Admin model with just authentication and timeoutable features. If so, just follow these steps:
```ruby
# Create a migration with the required fields
create_table :admins do |t|
t.string :email
t.string :encrypted_password
t.timestamps
end
# Inside your Admin model
devise :database_authenticatable, :timeoutable
# Inside your routes
devise_for :admins
# Inside your protected controller
before_filter :authenticate_admin!
# Inside your controllers and views
admin_signed_in?
current_admin
admin_session
```
On the other hand, you can simply run the generator!
### Other ORMs
Devise supports ActiveRecord (default) and Mongoid. To choose other ORM, you just need to require it in the initializer file.
### Migrating from other solutions
Devise implements encryption strategies for Clearance, Authlogic and Restful-Authentication. To make use of these strategies, you need set the desired encryptor in the encryptor initializer config option and add :encryptable to your model. You might also need to rename your encrypted password and salt columns to match Devise's fields (encrypted_password and password_salt).
## Troubleshooting
## Additional information
### Heroku
@@ -371,8 +395,6 @@ config.assets.initialize_on_precompile = false
Read more about the potential issues at http://guides.rubyonrails.org/asset_pipeline.html
## Additional information
### Warden
Devise is based on Warden, which is a general Rack authentication framework created by Daniel Neighman. We encourage you to read more about Warden here:
@@ -394,3 +416,5 @@ https://github.com/plataformatec/devise/contributors
## License
MIT License. Copyright 2009-2013 Plataformatec. http://plataformatec.com.br
You are not granted rights or licenses to the trademarks of the Plataformatec, including without limitation the Devise name or logo.

View File

@@ -22,6 +22,7 @@ Rake::TestTask.new(:test) do |t|
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
t.verbose = true
t.warning = false
end
desc 'Generate documentation for Devise.'

View File

@@ -1,7 +1,7 @@
class Devise::ConfirmationsController < DeviseController
# GET /resource/confirmation/new
def new
build_resource({})
self.resource = resource_class.new
end
# POST /resource/confirmation
@@ -32,12 +32,11 @@ class Devise::ConfirmationsController < DeviseController
# The path used after resending confirmation instructions.
def after_resending_confirmation_instructions_path_for(resource_name)
new_session_path(resource_name)
new_session_path(resource_name) if is_navigational_format?
end
# The path used after confirmation.
def after_confirmation_path_for(resource_name, resource)
after_sign_in_path_for(resource)
end
end

View File

@@ -5,7 +5,7 @@ class Devise::PasswordsController < DeviseController
# GET /resource/password/new
def new
build_resource({})
self.resource = resource_class.new
end
# POST /resource/password
@@ -34,17 +34,20 @@ class Devise::PasswordsController < DeviseController
flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
set_flash_message(:notice, flash_message) if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => after_sign_in_path_for(resource)
respond_with resource, :location => after_resetting_password_path_for(resource)
else
respond_with resource
end
end
protected
def after_resetting_password_path_for(resource)
after_sign_in_path_for(resource)
end
# The path used after sending reset password instructions
def after_sending_reset_password_instructions_path_for(resource_name)
new_session_path(resource_name)
new_session_path(resource_name) if is_navigational_format?
end
# Check if a reset_password_token is provided in the request

View File

@@ -4,13 +4,13 @@ class Devise::RegistrationsController < DeviseController
# GET /resource/sign_up
def new
resource = build_resource({})
respond_with resource
build_resource({})
respond_with self.resource
end
# POST /resource
def create
build_resource
self.resource = build_resource(sign_up_params)
if resource.save
if resource.active_for_authentication?
@@ -40,7 +40,7 @@ class Devise::RegistrationsController < DeviseController
self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)
if resource.update_with_password(resource_params)
if resource.update_with_password(account_update_params)
if is_navigational_format?
flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
:update_needs_confirmation : :updated
@@ -83,8 +83,7 @@ class Devise::RegistrationsController < DeviseController
# Build a devise resource passing in the session. Useful to move
# temporary session data to the newly created user.
def build_resource(hash=nil)
hash ||= resource_params || {}
self.resource = resource_class.new_with_session(hash, session)
self.resource = resource_class.new_with_session(hash || {}, session)
end
# Signs in a user on sign up. You can overwrite this method in your own
@@ -116,4 +115,12 @@ class Devise::RegistrationsController < DeviseController
send(:"authenticate_#{resource_name}!", :force => true)
self.resource = send(:"current_#{resource_name}")
end
def sign_up_params
devise_parameter_sanitizer.for(:sign_up)
end
def account_update_params
devise_parameter_sanitizer.for(:account_update)
end
end

View File

@@ -5,7 +5,7 @@ class Devise::SessionsController < DeviseController
# GET /resource/sign_in
def new
self.resource = build_resource(nil, :unsafe => true)
self.resource = resource_class.new(sign_in_params)
clean_up_passwords(resource)
respond_with(resource, serialize_options(resource))
end
@@ -34,6 +34,10 @@ class Devise::SessionsController < DeviseController
protected
def sign_in_params
devise_parameter_sanitizer.for(:sign_in)
end
def serialize_options(resource)
methods = resource_class.authentication_keys.dup
methods = methods.keys if methods.is_a?(Hash)
@@ -45,4 +49,3 @@ class Devise::SessionsController < DeviseController
{ :scope => resource_name, :recall => "#{controller_path}#new" }
end
end

View File

@@ -3,7 +3,7 @@ class Devise::UnlocksController < DeviseController
# GET /resource/unlock/new
def new
build_resource({})
self.resource = resource_class.new
end
# POST /resource/unlock
@@ -33,12 +33,12 @@ class Devise::UnlocksController < DeviseController
# The path used after sending unlock password instructions
def after_sending_unlock_instructions_path_for(resource)
new_session_path(resource)
new_session_path(resource) if is_navigational_format?
end
# The path used after unlocking the resource
def after_unlock_path_for(resource)
new_session_path(resource)
new_session_path(resource) if is_navigational_format?
end
end

View File

@@ -28,10 +28,6 @@ class DeviseController < Devise.parent_controller.constantize
devise_mapping.to
end
def resource_params
params[resource_name]
end
# Returns a signed in resource from session (if one exists)
def signed_in_resource
warden.authenticate(:scope => resource_name)
@@ -67,7 +63,7 @@ This may happen for two reasons:
1) You forgot to wrap your route inside the scope block. For example:
devise_scope :user do
match "/some/route" => "some_devise_controller"
get "/some/route" => "some_devise_controller"
end
2) You are testing a Devise controller bypassing the router.
@@ -93,23 +89,6 @@ MESSAGE
instance_variable_set(:"@#{resource_name}", new_resource)
end
# Build a devise resource.
# Assignment bypasses attribute protection when :unsafe option is passed
def build_resource(hash = nil, options = {})
hash ||= resource_params || {}
if options[:unsafe]
self.resource = resource_class.new.tap do |resource|
hash.each do |key, value|
setter = :"#{key}="
resource.send(setter, value) if resource.respond_to?(setter)
end
end
else
self.resource = resource_class.new(hash)
end
end
# Helper for use in before_filters where no authentication is required.
#
# Example:
@@ -163,13 +142,18 @@ MESSAGE
#
# Please refer to README or en.yml locale file to check what messages are
# available.
def set_flash_message(key, kind, options={})
def set_flash_message(key, kind, options = {})
message = find_message(kind, options)
flash[key] = message if message.present?
end
# Get message for given
def find_message(kind, options = {})
options[:scope] = "devise.#{controller_name}"
options[:default] = Array(options[:default]).unshift(kind.to_sym)
options[:resource_name] = resource_name
options = devise_i18n_options(options) if respond_to?(:devise_i18n_options, true)
message = I18n.t("#{options[:resource_name]}.#{kind}", options)
flash[key] = message if message.present?
I18n.t("#{options[:resource_name]}.#{kind}", options)
end
def clean_up_passwords(object)
@@ -181,4 +165,8 @@ MESSAGE
format.any(*navigational_formats, &block)
end
end
def resource_params
params.fetch(resource_name, {})
end
end

View File

@@ -1,4 +1,4 @@
class Devise::Mailer < ::ActionMailer::Base
class Devise::Mailer < Devise.parent_mailer.constantize
include Devise::Mailers::Helpers
def confirmation_instructions(record, opts={})

View File

@@ -24,6 +24,6 @@
<h3>Cancel my account</h3>
<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), :data => { :confirm => "Are you sure?" }, :method => :delete %>.</p>
<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), :data => { :confirm => "Are you sure?" }, :method => :delete %></p>
<%= link_to "Back", :back %>

View File

@@ -1,60 +1,59 @@
# Additional translations at https://github.com/plataformatec/devise/wiki/I18n
en:
devise:
confirmations:
confirmed: "Your account was successfully confirmed. You are now signed in."
send_instructions: "You will receive an email with instructions about how to confirm your account in a few minutes."
send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes."
failure:
already_authenticated: "You are already signed in."
inactive: "Your account was not activated yet."
invalid: "Invalid email or password."
invalid_token: "Invalid authentication token."
locked: "Your account is locked."
not_found_in_database: "Invalid email or password."
timeout: "Your session expired, please sign in again to continue."
unauthenticated: "You need to sign in or sign up before continuing."
unconfirmed: "You have to confirm your account before continuing."
mailer:
confirmation_instructions:
subject: "Confirmation instructions"
reset_password_instructions:
subject: "Reset password instructions"
unlock_instructions:
subject: "Unlock Instructions"
omniauth_callbacks:
failure: "Could not authenticate you from %{kind} because \"%{reason}\"."
success: "Successfully authenticated from %{kind} account."
passwords:
no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided."
send_instructions: "You will receive an email with instructions about how to reset your password in a few minutes."
send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes."
updated: "Your password was changed successfully. You are now signed in."
updated_not_active: "Your password was changed successfully."
registrations:
destroyed: "Bye! Your account was successfully cancelled. We hope to see you again soon."
signed_up: "Welcome! You have signed up successfully."
signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated."
signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked."
signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please open the link to activate your account."
update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address."
updated: "You updated your account successfully."
sessions:
signed_in: "Signed in successfully."
signed_out: "Signed out successfully."
unlocks:
send_instructions: "You will receive an email with instructions about how to unlock your account in a few minutes."
send_paranoid_instructions: "If your account exists, you will receive an email with instructions about how to unlock it in a few minutes."
unlocked: "Your account has been unlocked successfully. Please sign in to continue."
errors:
messages:
already_confirmed: "was already confirmed, please try signing in"
confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one"
expired: "has expired, please request a new one"
not_found: "not found"
already_confirmed: "was already confirmed, please try signing in"
not_locked: "was not locked"
not_saved:
one: "1 error prohibited this %{resource} from being saved:"
other: "%{count} errors prohibited this %{resource} from being saved:"
confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one"
devise:
failure:
already_authenticated: 'You are already signed in.'
unauthenticated: 'You need to sign in or sign up before continuing.'
unconfirmed: 'You have to confirm your account before continuing.'
locked: 'Your account is locked.'
not_found_in_database: 'Invalid email or password.'
invalid: 'Invalid email or password.'
invalid_token: 'Invalid authentication token.'
timeout: 'Your session expired, please sign in again to continue.'
inactive: 'Your account was not activated yet.'
sessions:
signed_in: 'Signed in successfully.'
signed_out: 'Signed out successfully.'
passwords:
send_instructions: 'You will receive an email with instructions about how to reset your password in a few minutes.'
updated: 'Your password was changed successfully. You are now signed in.'
updated_not_active: 'Your password was changed successfully.'
send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes."
no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided."
confirmations:
send_instructions: 'You will receive an email with instructions about how to confirm your account in a few minutes.'
send_paranoid_instructions: 'If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes.'
confirmed: 'Your account was successfully confirmed. You are now signed in.'
registrations:
signed_up: 'Welcome! You have signed up successfully.'
signed_up_but_unconfirmed: 'A message with a confirmation link has been sent to your email address. Please open the link to activate your account.'
signed_up_but_inactive: 'You have signed up successfully. However, we could not sign you in because your account is not yet activated.'
signed_up_but_locked: 'You have signed up successfully. However, we could not sign you in because your account is locked.'
updated: 'You updated your account successfully.'
update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address."
destroyed: 'Bye! Your account was successfully cancelled. We hope to see you again soon.'
unlocks:
send_instructions: 'You will receive an email with instructions about how to unlock your account in a few minutes.'
unlocked: 'Your account has been unlocked successfully. Please sign in to continue.'
send_paranoid_instructions: 'If your account exists, you will receive an email with instructions about how to unlock it in a few minutes.'
omniauth_callbacks:
success: 'Successfully authenticated from %{kind} account.'
failure: 'Could not authenticate you from %{kind} because "%{reason}".'
mailer:
confirmation_instructions:
subject: 'Confirmation instructions'
reset_password_instructions:
subject: 'Reset password instructions'
unlock_instructions:
subject: 'Unlock Instructions'

View File

@@ -6,6 +6,7 @@ Gem::Specification.new do |s|
s.name = "devise"
s.version = Devise::VERSION.dup
s.platform = Gem::Platform::RUBY
s.licenses = ["MIT"]
s.summary = "Flexible authentication solution for Rails with Warden"
s.email = "contact@plataformatec.com.br"
s.homepage = "http://github.com/plataformatec/devise"
@@ -21,5 +22,5 @@ Gem::Specification.new do |s|
s.add_dependency("warden", "~> 1.2.1")
s.add_dependency("orm_adapter", "~> 0.1")
s.add_dependency("bcrypt-ruby", "~> 3.0")
s.add_dependency("railties", "~> 3.1")
s.add_dependency("railties", ">= 3.2.6", "< 5")
end

BIN
devise.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -1,167 +0,0 @@
PATH
remote: ..
specs:
devise (2.2.0)
bcrypt-ruby (~> 3.0)
orm_adapter (~> 0.1)
railties (~> 3.1)
warden (~> 1.2.1)
GEM
remote: http://rubygems.org/
specs:
actionmailer (3.1.10)
actionpack (= 3.1.10)
mail (~> 2.3.3)
actionpack (3.1.10)
activemodel (= 3.1.10)
activesupport (= 3.1.10)
builder (~> 3.0.0)
erubis (~> 2.7.0)
i18n (~> 0.6)
rack (~> 1.3.6)
rack-cache (~> 1.2)
rack-mount (~> 0.8.2)
rack-test (~> 0.6.1)
sprockets (~> 2.0.4)
activemodel (3.1.10)
activesupport (= 3.1.10)
builder (~> 3.0.0)
i18n (~> 0.6)
activerecord (3.1.10)
activemodel (= 3.1.10)
activesupport (= 3.1.10)
arel (~> 2.2.3)
tzinfo (~> 0.3.29)
activeresource (3.1.10)
activemodel (= 3.1.10)
activesupport (= 3.1.10)
activesupport (3.1.10)
multi_json (>= 1.0, < 1.3)
arel (2.2.3)
bcrypt-ruby (3.0.1)
builder (3.0.4)
columnize (0.3.6)
erubis (2.7.0)
faraday (0.8.4)
multipart-post (~> 1.1)
hashie (1.2.0)
hike (1.2.1)
httpauth (0.2.0)
i18n (0.6.1)
json (1.7.6)
jwt (0.1.5)
multi_json (>= 1.0)
linecache (0.46)
rbx-require-relative (> 0.0.4)
mail (2.3.3)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
metaclass (0.0.1)
mime-types (1.19)
mocha (0.10.0)
metaclass (~> 0.0.1)
mongoid (3.0.16)
activemodel (~> 3.1)
moped (~> 1.1)
origin (~> 1.0)
tzinfo (~> 0.3.22)
moped (1.3.2)
multi_json (1.2.0)
multipart-post (1.1.5)
nokogiri (1.5.6)
oauth2 (0.8.0)
faraday (~> 0.8)
httpauth (~> 0.1)
jwt (~> 0.1.4)
multi_json (~> 1.0)
rack (~> 1.2)
omniauth (1.0.3)
hashie (~> 1.2)
rack
omniauth-facebook (1.4.0)
omniauth-oauth2 (~> 1.0.2)
omniauth-oauth2 (1.0.3)
oauth2 (~> 0.8.0)
omniauth (~> 1.0)
omniauth-openid (1.0.1)
omniauth (~> 1.0)
rack-openid (~> 1.3.1)
origin (1.0.11)
orm_adapter (0.4.0)
polyglot (0.3.3)
rack (1.3.8)
rack-cache (1.2)
rack (>= 0.4)
rack-mount (0.8.3)
rack (>= 1.0.0)
rack-openid (1.3.1)
rack (>= 1.1.0)
ruby-openid (>= 2.1.8)
rack-ssl (1.3.2)
rack
rack-test (0.6.2)
rack (>= 1.0)
rails (3.1.10)
actionmailer (= 3.1.10)
actionpack (= 3.1.10)
activerecord (= 3.1.10)
activeresource (= 3.1.10)
activesupport (= 3.1.10)
bundler (~> 1.0)
railties (= 3.1.10)
railties (3.1.10)
actionpack (= 3.1.10)
activesupport (= 3.1.10)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (~> 0.14.6)
rake (10.0.3)
rbx-require-relative (0.0.9)
rdoc (3.12)
json (~> 1.4)
ruby-debug (0.10.4)
columnize (>= 0.1)
ruby-debug-base (~> 0.10.4.0)
ruby-debug-base (0.10.4)
linecache (>= 0.3)
ruby-openid (2.2.2)
sprockets (2.0.4)
hike (~> 1.2)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sqlite3 (1.3.6)
thor (0.14.6)
tilt (1.3.3)
treetop (1.4.12)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.35)
warden (1.2.1)
rack (>= 1.0)
webrat (0.7.2)
nokogiri (>= 1.2.0)
rack (>= 1.0)
rack-test (>= 0.5.3)
PLATFORMS
ruby
DEPENDENCIES
activerecord-jdbc-adapter
activerecord-jdbcsqlite3-adapter
devise!
jruby-openssl
mocha (= 0.10.0)
mongoid (~> 3.0)
omniauth (~> 1.0.0)
omniauth-facebook
omniauth-oauth2 (~> 1.0.0)
omniauth-openid (~> 1.0.1)
rails (~> 3.1.0)
rdoc
ruby-debug (>= 0.10.3)
sqlite3
webrat (= 0.7.2)

View File

@@ -1,8 +1,8 @@
source "http://rubygems.org"
source "https://rubygems.org"
gem "devise", :path => ".."
gemspec :path => '..'
gem "rails", "~> 3.1.0"
gem "rails", "~> 3.2.6"
gem "omniauth", "~> 1.0.0"
gem "omniauth-oauth2", "~> 1.0.0"
gem "rdoc"
@@ -10,12 +10,8 @@ gem "rdoc"
group :test do
gem "omniauth-facebook"
gem "omniauth-openid", "~> 1.0.1"
gem "webrat", "0.7.2", :require => false
gem "mocha", "0.10.0", :require => false
platforms :mri_18 do
gem "ruby-debug", ">= 0.10.3"
end
gem "webrat", "0.7.3", :require => false
gem "mocha", "~> 0.13.1", :require => false
end
platforms :jruby do
@@ -28,8 +24,8 @@ platforms :ruby do
gem "sqlite3"
end
platforms :mri_19 do
platforms :mri_19, :mri_20 do
group :mongoid do
gem "mongoid", "~> 3.0"
end
end
end

View File

@@ -0,0 +1,156 @@
PATH
remote: ..
specs:
devise (3.0.0.rc)
bcrypt-ruby (~> 3.0)
orm_adapter (~> 0.1)
railties (>= 3.2.6, < 5)
warden (~> 1.2.1)
GEM
remote: https://rubygems.org/
specs:
actionmailer (3.2.13)
actionpack (= 3.2.13)
mail (~> 2.5.3)
actionpack (3.2.13)
activemodel (= 3.2.13)
activesupport (= 3.2.13)
builder (~> 3.0.0)
erubis (~> 2.7.0)
journey (~> 1.0.4)
rack (~> 1.4.5)
rack-cache (~> 1.2)
rack-test (~> 0.6.1)
sprockets (~> 2.2.1)
activemodel (3.2.13)
activesupport (= 3.2.13)
builder (~> 3.0.0)
activerecord (3.2.13)
activemodel (= 3.2.13)
activesupport (= 3.2.13)
arel (~> 3.0.2)
tzinfo (~> 0.3.29)
activeresource (3.2.13)
activemodel (= 3.2.13)
activesupport (= 3.2.13)
activesupport (3.2.13)
i18n (= 0.6.1)
multi_json (~> 1.0)
arel (3.0.2)
bcrypt-ruby (3.0.1)
builder (3.0.4)
erubis (2.7.0)
faraday (0.8.7)
multipart-post (~> 1.1)
hashie (1.2.0)
hike (1.2.2)
httpauth (0.2.0)
i18n (0.6.1)
journey (1.0.4)
json (1.7.7)
jwt (0.1.8)
multi_json (>= 1.5)
mail (2.5.3)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
metaclass (0.0.1)
mime-types (1.23)
mocha (0.13.3)
metaclass (~> 0.0.1)
mongoid (3.1.3)
activemodel (~> 3.2)
moped (~> 1.4.2)
origin (~> 1.0)
tzinfo (~> 0.3.22)
moped (1.4.5)
multi_json (1.7.3)
multipart-post (1.2.0)
nokogiri (1.5.9)
oauth2 (0.8.1)
faraday (~> 0.8)
httpauth (~> 0.1)
jwt (~> 0.1.4)
multi_json (~> 1.0)
rack (~> 1.2)
omniauth (1.0.3)
hashie (~> 1.2)
rack
omniauth-facebook (1.4.0)
omniauth-oauth2 (~> 1.0.2)
omniauth-oauth2 (1.0.3)
oauth2 (~> 0.8.0)
omniauth (~> 1.0)
omniauth-openid (1.0.1)
omniauth (~> 1.0)
rack-openid (~> 1.3.1)
origin (1.1.0)
orm_adapter (0.4.0)
polyglot (0.3.3)
rack (1.4.5)
rack-cache (1.2)
rack (>= 0.4)
rack-openid (1.3.1)
rack (>= 1.1.0)
ruby-openid (>= 2.1.8)
rack-ssl (1.3.3)
rack
rack-test (0.6.2)
rack (>= 1.0)
rails (3.2.13)
actionmailer (= 3.2.13)
actionpack (= 3.2.13)
activerecord (= 3.2.13)
activeresource (= 3.2.13)
activesupport (= 3.2.13)
bundler (~> 1.0)
railties (= 3.2.13)
railties (3.2.13)
actionpack (= 3.2.13)
activesupport (= 3.2.13)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (>= 0.14.6, < 2.0)
rake (10.0.4)
rdoc (3.12.2)
json (~> 1.4)
ruby-openid (2.2.3)
sprockets (2.2.2)
hike (~> 1.2)
multi_json (~> 1.0)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sqlite3 (1.3.7)
thor (0.18.1)
tilt (1.4.0)
treetop (1.4.12)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.37)
warden (1.2.1)
rack (>= 1.0)
webrat (0.7.3)
nokogiri (>= 1.2.0)
rack (>= 1.0)
rack-test (>= 0.5.3)
PLATFORMS
ruby
DEPENDENCIES
activerecord-jdbc-adapter
activerecord-jdbcsqlite3-adapter
devise!
jruby-openssl
mocha (~> 0.13.1)
mongoid (~> 3.0)
omniauth (~> 1.0.0)
omniauth-facebook
omniauth-oauth2 (~> 1.0.0)
omniauth-openid (~> 1.0.1)
rails (~> 3.2.6)
rdoc
sqlite3
webrat (= 0.7.3)

View File

@@ -6,12 +6,14 @@ require 'set'
require 'securerandom'
module Devise
autoload :Delegator, 'devise/delegator'
autoload :FailureApp, 'devise/failure_app'
autoload :OmniAuth, 'devise/omniauth'
autoload :ParamFilter, 'devise/param_filter'
autoload :TestHelpers, 'devise/test_helpers'
autoload :TimeInflector, 'devise/time_inflector'
autoload :Delegator, 'devise/delegator'
autoload :FailureApp, 'devise/failure_app'
autoload :OmniAuth, 'devise/omniauth'
autoload :ParamFilter, 'devise/param_filter'
autoload :BaseSanitizer, 'devise/parameter_sanitizer'
autoload :ParameterSanitizer, 'devise/parameter_sanitizer'
autoload :TestHelpers, 'devise/test_helpers'
autoload :TimeInflector, 'devise/time_inflector'
module Controllers
autoload :Helpers, 'devise/controllers/helpers'
@@ -43,7 +45,7 @@ module Devise
# True values used to check params
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE']
# Custom domain for cookies. Not set by default
# Custom domain or key for cookies. Not set by default
mattr_accessor :rememberable_options
@@rememberable_options = {}
@@ -51,6 +53,10 @@ module Devise
mattr_accessor :stretches
@@stretches = 10
# The default key used when authenticating over http auth.
mattr_accessor :http_authentication_key
@@http_authentication_key = nil
# Keys used when authenticating a user.
mattr_accessor :authentication_keys
@@authentication_keys = [ :email ]
@@ -102,6 +108,7 @@ module Devise
@@extend_remember_period = false
# Time interval you can access your account before confirming your account.
# nil - allows unconfirmed access for unlimited time
mattr_accessor :allow_unconfirmed_access_for
@@allow_unconfirmed_access_for = 0.days
@@ -199,6 +206,12 @@ module Devise
mattr_accessor :parent_controller
@@parent_controller = "ApplicationController"
# The parent mailer all Devise mailers inherit from.
# Defaults to ActionMailer::Base. This should be set early
# in the initialization process and should be set to a string.
mattr_accessor :parent_mailer
@@parent_mailer = "ActionMailer::Base"
# The router Devise should use to generate routes. Defaults
# to :main_app. Should be overriden by engines in order
# to provide custom routes.
@@ -304,7 +317,7 @@ module Devise
# == Options:
#
# +model+ - String representing the load path to a custom *model* for this module (to autoload.)
# +controller+ - Symbol representing the name of an exisiting or custom *controller* for this module.
# +controller+ - Symbol representing the name of an existing or custom *controller* for this module.
# +route+ - Symbol representing the named *route* helper for this module.
# +strategy+ - Symbol representing if this module got a custom *strategy*.
#
@@ -414,6 +427,17 @@ module Devise
Devise.mappings.each_value do |mapping|
warden_config.scope_defaults mapping.name, :strategies => mapping.strategies
warden_config.serialize_into_session(mapping.name) do |record|
mapping.to.serialize_into_session(record)
end
warden_config.serialize_from_session(mapping.name) do |key|
# Previous versions contained an additional entry at the beginning of
# key with the record's class name.
args = key[-2, 2]
mapping.to.serialize_from_session(*args)
end
end
@@warden_config_block.try :call, Devise.warden_config
@@ -421,7 +445,7 @@ module Devise
end
end
# Generate a friendly string randomically to be used as token.
# Generate a friendly string randomly to be used as token.
def self.friendly_token
SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')
end

View File

@@ -80,6 +80,17 @@ module Devise
is_a?(DeviseController)
end
# Setup a param sanitizer to filter parameters using strong_parameters. See
# lib/devise/parameter_sanitizer.rb for more info. Override this
# method in your application controller to use your own parameter sanitizer.
def devise_parameter_sanitizer
@devise_parameter_sanitizer ||= if defined?(ActionController::StrongParameters)
Devise::ParameterSanitizer.new(resource_class, resource_name, params)
else
Devise::BaseSanitizer.new(resource_class, resource_name, params)
end
end
# Tell warden that params authentication is allowed for that specific page.
def allow_params_authentication!
request.env["devise.allow_params_authentication"] = true

View File

@@ -23,14 +23,14 @@ module Devise
def remember_me(resource)
scope = Devise::Mapping.find_scope!(resource)
resource.remember_me!(resource.extend_remember_period)
cookies.signed["remember_#{scope}_token"] = remember_cookie_values(resource)
cookies.signed[remember_key(resource, scope)] = remember_cookie_values(resource)
end
# Forgets the given resource by deleting a cookie
def forget_me(resource)
scope = Devise::Mapping.find_scope!(resource)
resource.forget_me!
cookies.delete("remember_#{scope}_token", forget_cookie_values(resource))
cookies.delete(remember_key(resource, scope), forget_cookie_values(resource))
end
protected
@@ -47,6 +47,10 @@ module Devise
:expires => resource.remember_expires_at
)
end
def remember_key(resource, scope)
resource.rememberable_options.fetch(:key, "remember_#{scope}_token")
end
end
end
end
end

View File

@@ -54,8 +54,9 @@ module Devise
end
def mailer_sender(mapping, sender = :from)
if default_params[sender].present?
default_params[sender]
default_sender = default_params[sender]
if default_sender.present?
default_sender.respond_to?(:to_proc) ? instance_eval(&default_sender) : default_sender
elsif Devise.mailer_sender.is_a?(Proc)
Devise.mailer_sender.call(mapping.name)
else
@@ -64,12 +65,12 @@ module Devise
end
def template_paths
template_path = [self.class.mailer_name]
template_path = _prefixes.dup
template_path.unshift "#{@devise_mapping.scoped_path}/mailer" if self.class.scoped_views?
template_path
end
# Setup a subject doing an I18n lookup. At first, it attemps to set a subject
# Setup a subject doing an I18n lookup. At first, it attempts to set a subject
# based on the current mapping:
#
# en:

View File

@@ -10,12 +10,15 @@ module Devise
#
# * +authentication_keys+: parameters used for authentication. By default [:email].
#
# * +http_authentication_key+: map the username passed via HTTP Auth to this parameter. Defaults to
# the first element in +authentication_keys+.
#
# * +request_keys+: parameters from the request object used for authentication.
# By specifying a symbol (which should be a request method), it will automatically be
# passed to find_for_authentication method and considered in your model lookup.
#
# For instance, if you set :request_keys to [:subdomain], :subdomain will be considered
# as key on authentication. This can also be a hash where the value is a boolean expliciting
# as key on authentication. This can also be a hash where the value is a boolean specifying
# if the value is required or not.
#
# * +http_authenticatable+: if this model allows http authentication. By default true.
@@ -32,7 +35,7 @@ module Devise
# == active_for_authentication?
#
# After authenticating a user and in each request, Devise checks if your model is active by
# calling model.active_for_authentication?. This method is overwriten by other devise modules. For instance,
# calling model.active_for_authentication?. This method is overwritten by other devise modules. For instance,
# :confirmable overwrites .active_for_authentication? to only return true if your model was confirmed.
#
# You overwrite this method yourself, but if you do, don't forget to call super:
@@ -140,14 +143,26 @@ module Devise
#
# protected
#
# def send_devise_notification(notification)
# pending_notifications << notification
# def send_devise_notification(notification, opts = {})
# # if the record is new or changed then delay the
# # delivery until the after_commit callback otherwise
# # send now because after_commit will not be called.
# if new_record? || changed?
# pending_notifications << [notification, opts]
# else
# devise_mailer.send(notification, self, opts).deliver
# end
# end
#
# def send_pending_notifications
# pending_notifications.each do |n|
# devise_mailer.send(n, self).deliver
# pending_notifications.each do |n, opts|
# devise_mailer.send(n, self, opts).deliver
# end
#
# # Empty the pending notifications array because the
# # after_commit hook can be called multiple times which
# # could cause multiple emails to be sent.
# pending_notifications.clear
# end
#
# def pending_notifications
@@ -182,7 +197,8 @@ module Devise
module ClassMethods
Devise::Models.config(self, :authentication_keys, :request_keys, :strip_whitespace_keys,
:case_insensitive_keys, :http_authenticatable, :params_authenticatable, :skip_session_storage)
:case_insensitive_keys, :http_authenticatable, :params_authenticatable, :skip_session_storage,
:http_authentication_key)
def serialize_into_session(record)
[record.to_key, record.authenticatable_salt]
@@ -214,21 +230,20 @@ module Devise
# namedscope to filter records while authenticating.
# Example:
#
# def self.find_for_authentication(conditions={})
# conditions[:active] = true
# super
# def self.find_for_authentication(tainted_conditions)
# find_first_by_auth_conditions(tainted_conditions, :active => true)
# end
#
# Finally, notice that Devise also queries for users in other scenarios
# besides authentication, for example when retrieving an user to send
# an e-mail for password reset. In such cases, find_for_authentication
# is not called.
def find_for_authentication(conditions)
find_first_by_auth_conditions(conditions)
def find_for_authentication(tainted_conditions)
find_first_by_auth_conditions(tainted_conditions)
end
def find_first_by_auth_conditions(conditions)
to_adapter.find_first devise_param_filter.filter(conditions)
def find_first_by_auth_conditions(tainted_conditions, opts={})
to_adapter.find_first(devise_param_filter.filter(tainted_conditions).merge(opts))
end
# Find an initialize a record setting an error if it can't be found.

View File

@@ -34,11 +34,18 @@ module Devise
included do
before_create :generate_confirmation_token, :if => :confirmation_required?
after_create :send_on_create_confirmation_instructions, :if => :confirmation_required?
after_create :send_on_create_confirmation_instructions, :if => :send_confirmation_notification?
before_update :postpone_email_change_until_confirmation, :if => :postpone_email_change?
after_update :send_confirmation_instructions, :if => :reconfirmation_required?
end
def initialize(*args, &block)
@bypass_postpone = false
@reconfirmation_required = false
@skip_confirmation_notification = false
super
end
def self.required_fields(klass)
required_methods = [:confirmation_token, :confirmed_at, :confirmation_sent_at]
required_methods << :unconfirmed_email if klass.reconfirmable
@@ -119,6 +126,12 @@ module Devise
self.confirmed_at = Time.now.utc
end
# Skips sending the confirmation notification email after_create. Unlike
# #skip_confirmation!, record still requires confirmation.
def skip_confirmation_notification!
@skip_confirmation_notification = true
end
# If you don't want reconfirmation to be sent, neither a code
# to be generated, call skip_reconfirmation!
def skip_reconfirmation!
@@ -158,8 +171,11 @@ module Devise
# # allow_unconfirmed_access_for = 0.days
# confirmation_period_valid? # will always return false
#
# # allow_unconfirmed_access_for = nil
# confirmation_period_valid? # will always return true
#
def confirmation_period_valid?
confirmation_sent_at && confirmation_sent_at.utc >= self.class.allow_unconfirmed_access_for.ago
self.class.allow_unconfirmed_access_for.nil? || (confirmation_sent_at && confirmation_sent_at.utc >= self.class.allow_unconfirmed_access_for.ago)
end
# Checks if the user confirmation happens before the token becomes invalid
@@ -212,7 +228,7 @@ module Devise
def postpone_email_change?
postpone = self.class.reconfirmable && email_changed? && !@bypass_postpone
@bypass_postpone = nil
@bypass_postpone = false
postpone
end
@@ -220,6 +236,10 @@ module Devise
self.class.reconfirmable && @reconfirmation_required
end
def send_confirmation_notification?
confirmation_required? && !@skip_confirmation_notification
end
module ClassMethods
# Attempt to find a user by its email. If a record is found, send new
# confirmation instructions to it. If not, try searching for a user by unconfirmed_email

View File

@@ -95,6 +95,21 @@ module Devise
result
end
# Destroy record when :current_password matches, otherwise returns
# error on :current_password. It also automatically rejects
# :current_password if it is blank.
def destroy_with_password(current_password)
result = if valid_password?(current_password)
destroy
else
self.valid?
self.errors.add(:current_password, current_password.blank? ? :blank : :invalid)
false
end
result
end
def after_database_authentication
end

View File

@@ -8,7 +8,7 @@ module Devise
#
# Oauthable adds the following options to devise_for:
#
# * +omniauth_providers+: Which providers are avaialble to this model. It expects an array:
# * +omniauth_providers+: Which providers are available to this model. It expects an array:
#
# devise_for :database_authenticatable, :omniauthable, :omniauth_providers => [:twitter]
#
@@ -24,4 +24,4 @@ module Devise
end
end
end
end
end

View File

@@ -1,7 +1,7 @@
module Devise
module Models
# Recoverable takes care of reseting the user password and send reset instructions.
# Recoverable takes care of resetting the user password and send reset instructions.
#
# ==Options
#

View File

@@ -2,7 +2,7 @@ require 'devise/hooks/timeoutable'
module Devise
module Models
# Timeoutable takes care of veryfing whether a user session has already
# Timeoutable takes care of verifyng whether a user session has already
# expired or not. When a session expires after the configured time, the user
# will be asked for credentials again, it means, he/she will be redirected
# to the sign in page.

View File

@@ -8,16 +8,16 @@ module Devise
def filter(conditions)
conditions = stringify_params(conditions.dup)
@case_insensitive_keys.each do |k|
value = conditions[k]
next unless value.respond_to?(:downcase)
conditions[k] = value.downcase
end
conditions.merge!(filtered_hash_by_method_for_given_keys(conditions.dup, :downcase, @case_insensitive_keys))
conditions.merge!(filtered_hash_by_method_for_given_keys(conditions.dup, :strip, @strip_whitespace_keys))
@strip_whitespace_keys.each do |k|
conditions
end
def filtered_hash_by_method_for_given_keys(conditions, method, condition_keys)
condition_keys.each do |k|
value = conditions[k]
next unless value.respond_to?(:strip)
conditions[k] = value.strip
conditions[k] = value.send(method) if value.respond_to?(method)
end
conditions
@@ -33,9 +33,8 @@ module Devise
private
# Determine which values should be transformed to string or passed as-is to the query builder underneath
def param_requires_string_conversion?(value)
[Fixnum, TrueClass, FalseClass, Regexp].none? {|clz| value.is_a? clz }
true
end
end
end

View File

@@ -0,0 +1,59 @@
module Devise
class BaseSanitizer
attr_reader :params, :resource_name, :resource_class
def initialize(resource_class, resource_name, params)
@resource_class = resource_class
@resource_name = resource_name
@params = params
@blocks = Hash.new
end
def for(kind, &block)
if block_given?
@blocks[kind] = block
else
block = @blocks[kind]
block ? block.call(default_params) : fallback_for(kind)
end
end
private
def fallback_for(kind)
default_params
end
def default_params
params.fetch(resource_name, {})
end
end
class ParameterSanitizer < BaseSanitizer
private
def fallback_for(kind)
if respond_to?(kind, true)
send(kind)
else
raise NotImplementedError, "Devise Parameter Sanitizer doesn't know how to sanitize parameters for #{kind}"
end
end
def sign_in
default_params.permit(auth_keys)
end
def sign_up
default_params.permit(auth_keys + [:password, :password_confirmation])
end
def account_update
default_params.permit(auth_keys + [:password, :password_confirmation, :current_password])
end
def auth_keys
resource_class.authentication_keys
end
end
end

View File

@@ -250,15 +250,11 @@ module ActionDispatch::Routing
# end
#
# authenticate :user, lambda {|u| u.role == "admin"} do
# root :to => "admin/dashboard#show"
# root :to => "admin/dashboard#show", :as => :user_root
# end
#
def authenticate(scope=nil, block=nil)
constraint = lambda do |request|
request.env["warden"].authenticate!(:scope => scope) && (block.nil? || block.call(request.env["warden"].user(scope)))
end
constraints(constraint) do
constraints_for(:authenticate!, scope, block) do
yield
end
end
@@ -268,25 +264,21 @@ module ActionDispatch::Routing
# a model and allows extra constraints to be done on the instance.
#
# authenticated :admin do
# root :to => 'admin/dashboard#show'
# root :to => 'admin/dashboard#show', :as => :admin_root
# end
#
# authenticated do
# root :to => 'dashboard#show'
# root :to => 'dashboard#show', :as => :authenticated_root
# end
#
# authenticated :user, lambda {|u| u.role == "admin"} do
# root :to => "admin/dashboard#show"
# root :to => "admin/dashboard#show", :as => :user_root
# end
#
# root :to => 'landing#show'
#
def authenticated(scope=nil, block=nil)
constraint = lambda do |request|
request.env["warden"].authenticate?(:scope => scope) && (block.nil? || block.call(request.env["warden"].user(scope)))
end
constraints(constraint) do
constraints_for(:authenticate?, scope, block) do
yield
end
end
@@ -329,7 +321,7 @@ module ActionDispatch::Routing
# good and working example.
#
# devise_scope :user do
# match "/some/route" => "some_devise_controller"
# get "/some/route" => "some_devise_controller"
# end
# devise_for :users
#
@@ -401,12 +393,14 @@ module ActionDispatch::Routing
match "#{path_prefix}/:provider",
:constraints => { :provider => providers },
:to => "#{controllers[:omniauth_callbacks]}#passthru",
:as => :omniauth_authorize
:as => :omniauth_authorize,
:via => [:get, :post]
match "#{path_prefix}/:action/callback",
:constraints => { :action => providers },
:to => controllers[:omniauth_callbacks],
:as => :omniauth_callback
:as => :omniauth_callback,
:via => [:get, :post]
ensure
@scope[:path] = path
end
@@ -426,6 +420,17 @@ module ActionDispatch::Routing
@scope.merge!(old)
end
def constraints_for(method_to_apply, scope=nil, block=nil)
constraint = lambda do |request|
request.env['warden'].send(method_to_apply, :scope => scope) &&
(block.nil? || block.call(request.env["warden"].user(scope)))
end
constraints(constraint) do
yield
end
end
def set_omniauth_path_prefix!(path_prefix) #:nodoc:
if ::OmniAuth.config.path_prefix && ::OmniAuth.config.path_prefix != path_prefix
raise "Wrong OmniAuth configuration. If you are getting this exception, it means that either:\n\n" \

View File

@@ -12,32 +12,3 @@ module Warden::Mixins::Common
request.cookie_jar
end
end
class Warden::SessionSerializer
def serialize(record)
klass = record.class
array = klass.serialize_into_session(record)
array.unshift(klass.name)
end
def deserialize(keys)
klass_name, *args = keys
begin
klass = ActiveSupport::Inflector.constantize(klass_name)
if klass.respond_to? :serialize_from_session
klass.serialize_from_session(*args)
else
Rails.logger.warn "[Devise] Stored serialized class #{klass_name} seems not to be Devise enabled anymore. Did you do that on purpose?"
nil
end
rescue NameError => e
if e.message =~ /uninitialized constant/
Rails.logger.debug "[Devise] Trying to deserialize invalid class #{klass_name}"
nil
else
raise
end
end
end
end

View File

@@ -100,7 +100,7 @@ module Devise
# Extract a hash with attributes:values from the http params.
def http_auth_hash
keys = [authentication_keys.first, :password]
keys = [http_authentication_key, :password]
Hash[*keys.zip(decode_credentials).flatten]
end
@@ -134,24 +134,27 @@ module Devise
parse_authentication_key_values(request_values, request_keys)
end
# Holds the authentication keys.
def authentication_keys
@authentication_keys ||= mapping.to.authentication_keys
end
# Holds request keys.
def http_authentication_key
@http_authentication_key ||= mapping.to.http_authentication_key || case authentication_keys
when Array then authentication_keys.first
when Hash then authentication_keys.keys.first
end
end
def request_keys
@request_keys ||= mapping.to.request_keys
end
# Returns values from the request object.
def request_values
keys = request_keys.respond_to?(:keys) ? request_keys.keys : request_keys
values = keys.map { |k| self.request.send(k) }
Hash[keys.zip(values)]
end
# Parse authentication keys considering if they should be enforced or not.
def parse_authentication_key_values(hash, keys)
keys.each do |key, enforce|
value = hash[key].presence

View File

@@ -41,7 +41,7 @@ module Devise
end
def remember_key
"remember_#{scope}_token"
mapping.to.rememberable_options.fetch(:key, "remember_#{scope}_token")
end
def remember_cookie
@@ -52,4 +52,4 @@ module Devise
end
end
Warden::Strategies.add(:rememberable, Devise::Strategies::Rememberable)
Warden::Strategies.add(:rememberable, Devise::Strategies::Rememberable)

View File

@@ -7,13 +7,22 @@ module Devise
#
# http://myapp.example.com/?user_token=SECRET
#
# For HTTP, you can pass the token as username and blank password. Since some clients may require
# a password, you can pass "X" as password and it will simply be ignored.
# For headers, you can use basic authentication passing the token as username and
# blank password. Since some clients may require a password, you can pass "X" as
# password and it will simply be ignored.
#
# You may also pass the token using the Token authentication mechanism provided
# by Rails: http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html
# The token options are stored in request.env['devise.token_options']
class TokenAuthenticatable < Authenticatable
def store?
super && !mapping.to.skip_session_storage.include?(:token_auth)
end
def valid?
super || valid_for_token_auth?
end
def authenticate!
resource = mapping.to.find_for_token_authentication(authentication_hash)
return fail(:invalid_token) unless resource
@@ -36,7 +45,33 @@ module Devise
false
end
# Try both scoped and non scoped keys.
# Check if the model accepts this strategy as token authenticatable.
def token_authenticatable?
mapping.to.http_authenticatable?(:token_options)
end
# Check if this is strategy is valid for token authentication by:
#
# * Validating if the model allows http token authentication;
# * If the http auth token exists;
# * If all authentication keys are present;
#
def valid_for_token_auth?
token_authenticatable? && auth_token.present? && with_authentication_hash(:token_auth, token_auth_hash)
end
# Extract the auth token from the request
def auth_token
@auth_token ||= ActionController::HttpAuthentication::Token.token_and_options(request)
end
# Extract a hash with attributes:values from the auth_token
def token_auth_hash
request.env['devise.token_options'] = auth_token.last
{ authentication_keys.first => auth_token.first }
end
# Try both scoped and non scoped keys
def params_auth_hash
if params[scope].kind_of?(Hash) && params[scope].has_key?(authentication_keys.first)
params[scope]

View File

@@ -1,3 +1,3 @@
module Devise
VERSION = "2.2.2".freeze
VERSION = "3.0.0.rc".freeze
end

View File

@@ -22,10 +22,7 @@ module ActiveRecord
end
def inject_devise_content
content = model_contents + <<CONTENT
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
CONTENT
content = model_contents
class_path = if namespaced?
class_name.to_s.split("::")

View File

@@ -18,7 +18,7 @@ module Devise
public_task :copy_views
end
# TODO: Add this to Rails itslef
# TODO: Add this to Rails itself
module ClassMethods
def hide!
Rails::Generators.hide_namespace self.namespace
@@ -36,7 +36,13 @@ module Devise
protected
def view_directory(name, _target_path = nil)
directory name.to_s, _target_path || "#{target_path}/#{name}"
directory name.to_s, _target_path || "#{target_path}/#{name}" do |content|
if scope
content.gsub "devise/shared/links", "#{scope}/shared/links"
else
content
end
end
end
def target_path

View File

@@ -48,10 +48,14 @@ Devise.setup do |config|
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Basic Auth is enabled. False by default.
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:token]` will
# enable it only for token authentication.
# enable it only for token authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# :token = Support basic authentication with token authentication key
# :token_options = Support token authentication with options as defined in
# http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
@@ -125,7 +129,7 @@ Devise.setup do |config|
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# an one (and only one) @ exists in the given string. This is mainly
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
@@ -175,7 +179,9 @@ Devise.setup do |config|
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper)
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable

View File

@@ -22,6 +22,6 @@
<h3>Cancel my account</h3>
<p>Unhappy? <%= link_to "Cancel my account", registration_path(resource_name), :data => { :confirm => "Are you sure?" }, :method => :delete %>.</p>
<p>Unhappy? <%= link_to "Cancel my account", registration_path(resource_name), :data => { :confirm => "Are you sure?" }, :method => :delete %></p>
<%= link_to "Back", :back %>

View File

@@ -34,10 +34,20 @@ class HelpersTest < ActionController::TestCase
end
test 'get resource params from request params using resource name as key' do
user_params = {'name' => 'Shirley Templar'}
@controller.stubs(:params).returns(HashWithIndifferentAccess.new({'user' => user_params}))
user_params = {'email' => 'shirley@templar.com'}
assert_equal user_params, @controller.resource_params
params = if Devise.rails4?
# Stub controller name so strong parameters can filter properly.
# DeviseController does not allow any parameters by default.
@controller.stubs(:controller_name).returns(:sessions_controller)
ActionController::Parameters.new({'user' => user_params})
else
HashWithIndifferentAccess.new({'user' => user_params})
end
@controller.stubs(:params).returns(params)
assert_equal user_params, @controller.send(:resource_params)
end
test 'resources methods are not controller actions' do

View File

@@ -0,0 +1,32 @@
require 'test_helper'
class PasswordsControllerTest < ActionController::TestCase
tests Devise::PasswordsController
include Devise::TestHelpers
def setup
request.env["devise.mapping"] = Devise.mappings[:user]
@user = create_user
@user.send_reset_password_instructions
end
def put_update_with_params
put :update, "user" => {
"reset_password_token" => @user.reset_password_token, "password" => "123456", "password_confirmation" => "123456"
}
end
test 'redirect to after_sign_in_path_for if after_resetting_password_path_for is not overridden' do
put_update_with_params
assert_redirected_to "http://test.host/"
end
test 'redirect accordingly if after_resetting_password_path_for is overridden' do
custom_path = "http://custom.path/"
Devise::PasswordsController.any_instance.stubs(:after_resetting_password_path_for).with(@user).returns(custom_path)
put_update_with_params
assert_redirected_to custom_path
end
end

View File

@@ -80,9 +80,9 @@ class FailureTest < ActiveSupport::TestCase
test 'setup a default message' do
call_failure
assert_match /You are being/, @response.last.body
assert_match /redirected/, @response.last.body
assert_match /users\/sign_in/, @response.last.body
assert_match(/You are being/, @response.last.body)
assert_match(/redirected/, @response.last.body)
assert_match(/users\/sign_in/, @response.last.body)
end
test 'works for any navigational format' do

View File

@@ -10,13 +10,11 @@ if DEVISE_ORM == :active_record
test "all files are properly created with rails31 migration syntax" do
run_generator %w(monster)
assert_file "app/models/monster.rb", /devise/, /attr_accessible (:[a-z_]+(, )?)+/
assert_migration "db/migrate/devise_create_monsters.rb", /def change/
end
test "all files for namespaced model are properly created" do
run_generator %w(admin/monster)
assert_file "app/models/admin/monster.rb", /devise/, /attr_accessible (:[a-z_]+(, )?)+/
assert_migration "db/migrate/devise_create_admin_monsters.rb", /def change/
end
@@ -68,7 +66,7 @@ if DEVISE_ORM == :active_record
simulate_inside_engine(RailsEngine::Engine, RailsEngine) do
run_generator ["monster"]
assert_file "app/models/rails_engine/monster.rb", /devise/,/attr_accessible (:[a-z_]+(, )?)+/
assert_file "app/models/rails_engine/monster.rb", /devise/
end
end
end

View File

@@ -8,14 +8,17 @@ class ViewsGeneratorTest < Rails::Generators::TestCase
test "Assert all views are properly created with no params" do
run_generator
assert_files
assert_shared_links
end
test "Assert all views are properly created with scope param param" do
test "Assert all views are properly created with scope param" do
run_generator %w(users)
assert_files "users"
assert_shared_links "users"
run_generator %w(admins)
assert_files "admins"
assert_shared_links "admins"
end
test "Assert views with simple form" do
@@ -49,4 +52,16 @@ class ViewsGeneratorTest < Rails::Generators::TestCase
assert_file "app/views/#{scope}/shared/_links.erb"
assert_file "app/views/#{scope}/unlocks/new.html.erb"
end
def assert_shared_links(scope = nil)
scope = "devise" if scope.nil?
link = /<%= render \"#{scope}\/shared\/links\" %>/
assert_file "app/views/#{scope}/passwords/edit.html.erb", link
assert_file "app/views/#{scope}/passwords/new.html.erb", link
assert_file "app/views/#{scope}/confirmations/new.html.erb", link
assert_file "app/views/#{scope}/registrations/new.html.erb", link
assert_file "app/views/#{scope}/sessions/new.html.erb", link
assert_file "app/views/#{scope}/unlocks/new.html.erb", link
end
end

View File

@@ -1,6 +1,6 @@
require 'test_helper'
class DeviseHelperTest < ActionController::IntegrationTest
class DeviseHelperTest < ActionDispatch::IntegrationTest
setup do
model_labels = { :models => { :user => "utilisateur" } }

View File

@@ -1,6 +1,6 @@
require 'test_helper'
class AuthenticationSanityTest < ActionController::IntegrationTest
class AuthenticationSanityTest < ActionDispatch::IntegrationTest
test 'home should be accessible without sign in' do
visit '/'
assert_response :success
@@ -134,7 +134,7 @@ class AuthenticationSanityTest < ActionController::IntegrationTest
end
end
class AuthenticationRoutesRestrictions < ActionController::IntegrationTest
class AuthenticationRoutesRestrictions < ActionDispatch::IntegrationTest
test 'not signed in should not be able to access private route (authenticate denied)' do
get private_path
assert_redirected_to new_admin_session_path
@@ -191,7 +191,7 @@ class AuthenticationRoutesRestrictions < ActionController::IntegrationTest
get dashboard_path
assert_response :success
assert_template 'home/admin'
assert_template 'home/admin_dashboard'
assert_contain 'Admin dashboard'
end
@@ -203,7 +203,7 @@ class AuthenticationRoutesRestrictions < ActionController::IntegrationTest
get dashboard_path
assert_response :success
assert_template 'home/user'
assert_template 'home/user_dashboard'
assert_contain 'User dashboard'
end
@@ -254,7 +254,7 @@ class AuthenticationRoutesRestrictions < ActionController::IntegrationTest
end
end
class AuthenticationRedirectTest < ActionController::IntegrationTest
class AuthenticationRedirectTest < ActionDispatch::IntegrationTest
test 'redirect from warden shows sign in or sign up message' do
get admins_path
@@ -317,7 +317,7 @@ class AuthenticationRedirectTest < ActionController::IntegrationTest
end
end
class AuthenticationSessionTest < ActionController::IntegrationTest
class AuthenticationSessionTest < ActionDispatch::IntegrationTest
test 'destroyed account is signed out' do
sign_in_as_user
get '/users'
@@ -333,22 +333,34 @@ class AuthenticationSessionTest < ActionController::IntegrationTest
assert_equal "Cart", @controller.user_session[:cart]
end
test 'does not explode when invalid user class is stored in session' do
klass = User
paths = ActiveSupport::Dependencies.autoload_paths.dup
test 'does not explode when class name is still stored in session' do
# In order to test that old sessions do not break with the new scoped
# deserialization, we need to serialize the session the old way. This is
# done by removing the newly used scoped serialization method
# (#user_serialize) and bringing back the old uncsoped #serialize method
# that includes the record's class name in the serialization.
begin
Warden::SessionSerializer.class_eval do
alias_method :original_serialize, :serialize
alias_method :original_user_serialize, :user_serialize
remove_method :user_serialize
def serialize(record)
klass = record.class
array = klass.serialize_into_session(record)
array.unshift(klass.name)
end
end
sign_in_as_user
assert warden.authenticated?(:user)
Object.send :remove_const, :User
ActiveSupport::Dependencies.autoload_paths.clear
visit "/users"
assert_not warden.authenticated?(:user)
ensure
Object.const_set(:User, klass)
ActiveSupport::Dependencies.autoload_paths.replace(paths)
Warden::SessionSerializer.class_eval do
alias_method :serialize, :original_serialize
remove_method :original_serialize
alias_method :user_serialize, :original_user_serialize
remove_method :original_user_serialize
end
end
end
@@ -364,7 +376,7 @@ class AuthenticationSessionTest < ActionController::IntegrationTest
end
end
class AuthenticationWithScopedViewsTest < ActionController::IntegrationTest
class AuthenticationWithScopedViewsTest < ActionDispatch::IntegrationTest
test 'renders the scoped view if turned on and view is available' do
swap Devise, :scoped_views => true do
assert_raise Webrat::NotFoundError do
@@ -405,7 +417,7 @@ class AuthenticationWithScopedViewsTest < ActionController::IntegrationTest
end
end
class AuthenticationOthersTest < ActionController::IntegrationTest
class AuthenticationOthersTest < ActionDispatch::IntegrationTest
test 'handles unverified requests gets rid of caches' do
swap UsersController, :allow_forgery_protection => true do
post exhibit_user_url(1)
@@ -504,14 +516,26 @@ class AuthenticationOthersTest < ActionController::IntegrationTest
assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<user>)
end
test 'sign out with xml format returns ok response' do
test 'sign out with html redirects' do
sign_in_as_user
get destroy_user_session_path
assert_response :redirect
assert_current_url '/'
sign_in_as_user
get destroy_user_session_path(:format => 'html')
assert_response :redirect
assert_current_url '/'
end
test 'sign out with xml format returns no content' do
sign_in_as_user
get destroy_user_session_path(:format => 'xml')
assert_response :no_content
assert_not warden.authenticated?(:user)
end
test 'sign out with json format returns empty json response' do
test 'sign out with json format returns no content' do
sign_in_as_user
get destroy_user_session_path(:format => 'json')
assert_response :no_content
@@ -519,7 +543,7 @@ class AuthenticationOthersTest < ActionController::IntegrationTest
end
test 'sign out with non-navigational format via XHR does not redirect' do
swap Devise, :navigational_formats => ['*/*', :html] do
swap Devise, :navigational_formats => ['*/*', :html] do
sign_in_as_user
xml_http_request :get, destroy_user_session_path, {}, { "HTTP_ACCEPT" => "application/json,text/javascript,*/*" } # NOTE: Bug is triggered by combination of XHR and */*.
assert_response :no_content
@@ -529,7 +553,7 @@ class AuthenticationOthersTest < ActionController::IntegrationTest
# Belt and braces ... Perhaps this test is not necessary?
test 'sign out with navigational format via XHR does redirect' do
swap Devise, :navigational_formats => ['*/*', :html] do
swap Devise, :navigational_formats => ['*/*', :html] do
sign_in_as_user
xml_http_request :get, destroy_user_session_path, {}, { "HTTP_ACCEPT" => "text/html,*/*" }
assert_response :redirect
@@ -538,7 +562,7 @@ class AuthenticationOthersTest < ActionController::IntegrationTest
end
end
class AuthenticationKeysTest < ActionController::IntegrationTest
class AuthenticationKeysTest < ActionDispatch::IntegrationTest
test 'missing authentication keys cause authentication to abort' do
swap Devise, :authentication_keys => [:subdomain] do
sign_in_as_user
@@ -555,7 +579,7 @@ class AuthenticationKeysTest < ActionController::IntegrationTest
end
end
class AuthenticationRequestKeysTest < ActionController::IntegrationTest
class AuthenticationRequestKeysTest < ActionDispatch::IntegrationTest
test 'request keys are used on authentication' do
host! 'foo.bar.baz'
@@ -596,7 +620,7 @@ class AuthenticationRequestKeysTest < ActionController::IntegrationTest
end
end
class AuthenticationSignOutViaTest < ActionController::IntegrationTest
class AuthenticationSignOutViaTest < ActionDispatch::IntegrationTest
def sign_in!(scope)
sign_in_as_admin(:visit => send("new_#{scope}_session_path"))
assert warden.authenticated?(scope)
@@ -650,3 +674,26 @@ class AuthenticationSignOutViaTest < ActionController::IntegrationTest
assert warden.authenticated?(:sign_out_via_delete_or_post)
end
end
class DoubleAuthenticationRedirectTest < ActionDispatch::IntegrationTest
test 'signed in as user redirects when visiting user sign in page' do
sign_in_as_user
get new_user_session_path(:format => :html)
assert_redirected_to '/'
end
test 'signed in as admin redirects when visiting admin sign in page' do
sign_in_as_admin
get new_admin_session_path(:format => :html)
assert_redirected_to '/admin_area/home'
end
test 'signed in as both user and admin redirects when visiting admin sign in page' do
sign_in_as_user
sign_in_as_admin
get new_user_session_path(:format => :html)
assert_redirected_to '/'
get new_admin_session_path(:format => :html)
assert_redirected_to '/admin_area/home'
end
end

View File

@@ -1,6 +1,6 @@
require 'test_helper'
class ConfirmationTest < ActionController::IntegrationTest
class ConfirmationTest < ActionDispatch::IntegrationTest
def visit_user_confirmation_with_token(confirmation_token)
visit user_confirmation_path(:confirmation_token => confirmation_token)
@@ -167,7 +167,7 @@ class ConfirmationTest < ActionController::IntegrationTest
end
test 'resent confirmation token with invalid E-Mail in XML format should return invalid response' do
user = create_user(:confirm => false)
create_user(:confirm => false)
post user_confirmation_path(:format => 'xml'), :user => { :email => 'invalid.test@test.com' }
assert_response :unprocessable_entity
assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>)
@@ -181,7 +181,7 @@ class ConfirmationTest < ActionController::IntegrationTest
end
test 'confirm account with invalid confirmation token in XML format should return invalid response' do
user = create_user(:confirm => false)
create_user(:confirm => false)
get user_confirmation_path(:confirmation_token => 'invalid_confirmation', :format => 'xml')
assert_response :unprocessable_entity
assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>)
@@ -226,7 +226,7 @@ class ConfirmationTest < ActionController::IntegrationTest
end
end
class ConfirmationOnChangeTest < ActionController::IntegrationTest
class ConfirmationOnChangeTest < ActionDispatch::IntegrationTest
def create_second_admin(options={})
@admin = nil
create_admin(options)
@@ -275,7 +275,7 @@ class ConfirmationOnChangeTest < ActionController::IntegrationTest
visit_admin_confirmation_with_token(confirmation_token)
assert_have_selector '#error_explanation'
assert_contain /Confirmation token(.*)invalid/
assert_contain(/Confirmation token(.*)invalid/)
visit_admin_confirmation_with_token(admin.confirmation_token)
assert_contain 'Your account was successfully confirmed.'
@@ -293,7 +293,7 @@ class ConfirmationOnChangeTest < ActionController::IntegrationTest
visit_admin_confirmation_with_token(admin.confirmation_token)
assert_have_selector '#error_explanation'
assert_contain /Email.*already.*taken/
assert_contain(/Email.*already.*taken/)
assert admin.reload.pending_reconfirmation?
end
end

View File

@@ -1,6 +1,6 @@
require 'test_helper'
class DatabaseAuthenticationTest < ActionController::IntegrationTest
class DatabaseAuthenticationTest < ActionDispatch::IntegrationTest
test 'sign in with email of different case should succeed when email is in the list of case insensitive keys' do
create_user(:email => 'Foo@Bar.com')

View File

@@ -1,6 +1,6 @@
require 'test_helper'
class HttpAuthenticationTest < ActionController::IntegrationTest
class HttpAuthenticationTest < ActionDispatch::IntegrationTest
test 'handles unverified requests gets rid of caches but continues signed in' do
swap UsersController, :allow_forgery_protection => true do
create_user
@@ -62,6 +62,24 @@ class HttpAuthenticationTest < ActionController::IntegrationTest
end
end
test 'it uses appropriate authentication_keys when configured with hash' do
swap Devise, :authentication_keys => ActiveSupport::OrderedHash[:username, false, :email, false] do
sign_in_as_new_user_with_http("usertest")
assert_response :success
assert_match '<email>user@test.com</email>', response.body
assert warden.authenticated?(:user)
end
end
test 'it uses the appropriate key when configured explicitly' do
swap Devise, :authentication_keys => ActiveSupport::OrderedHash[:email, false, :username, false], :http_authentication_key => :username do
sign_in_as_new_user_with_http("usertest")
assert_response :success
assert_match '<email>user@test.com</email>', response.body
assert warden.authenticated?(:user)
end
end
test 'test request with oauth2 header doesnt get mistaken for basic authentication' do
swap Devise, :http_authenticatable => true do
add_oauth2_header

View File

@@ -1,6 +1,6 @@
require 'test_helper'
class LockTest < ActionController::IntegrationTest
class LockTest < ActionDispatch::IntegrationTest
def visit_user_unlock_with_token(unlock_token)
visit user_unlock_path(:unlock_token => unlock_token)

View File

@@ -1,7 +1,7 @@
require 'test_helper'
class OmniauthableIntegrationTest < ActionController::IntegrationTest
class OmniauthableIntegrationTest < ActionDispatch::IntegrationTest
FACEBOOK_INFO = {
"id" => '12345',
"link" => 'http://facebook.com/josevalim',
@@ -90,7 +90,7 @@ class OmniauthableIntegrationTest < ActionController::IntegrationTest
end
assert session["devise.facebook_data"]
user = sign_in_as_user
sign_in_as_user
assert !session["devise.facebook_data"]
end

View File

@@ -1,6 +1,6 @@
require 'test_helper'
class PasswordTest < ActionController::IntegrationTest
class PasswordTest < ActionDispatch::IntegrationTest
def visit_new_password_path
visit new_user_session_path
@@ -153,7 +153,8 @@ class PasswordTest < ActionController::IntegrationTest
assert_response :success
assert_current_url '/users/password'
assert_have_selector '#error_explanation'
assert_contain 'Password doesn\'t match confirmation'
assert_contain Devise.rails4? ?
"Password confirmation doesn't match Password" : "Password doesn't match confirmation"
assert_not user.reload.valid_password?('987654321')
end
@@ -270,7 +271,7 @@ class PasswordTest < ActionController::IntegrationTest
end
test 'change password with invalid token in XML format should return invalid response' do
user = create_user
create_user
request_forgot_password
put user_password_path(:format => 'xml'), :user => {:reset_password_token => 'invalid.token', :password => '987654321', :password_confirmation => '987654321'}
assert_response :unprocessable_entity

View File

@@ -1,6 +1,6 @@
require 'test_helper'
class RegistrationTest < ActionController::IntegrationTest
class RegistrationTest < ActionDispatch::IntegrationTest
test 'a guest admin should be able to sign in successfully' do
get new_admin_session_path
@@ -17,7 +17,7 @@ class RegistrationTest < ActionController::IntegrationTest
assert warden.authenticated?(:admin)
assert_current_url "/admin_area/home"
admin = Admin.last :order => "id"
admin = Admin.order(:id).last
assert_equal admin.email, 'new_user@test.com'
end
@@ -56,7 +56,7 @@ class RegistrationTest < ActionController::IntegrationTest
assert_not warden.authenticated?(:user)
user = User.last :order => "id"
user = User.order(:id).last
assert_equal user.email, 'new_user@test.com'
assert_not user.confirmed?
end
@@ -100,7 +100,8 @@ class RegistrationTest < ActionController::IntegrationTest
assert_template 'registrations/new'
assert_have_selector '#error_explanation'
assert_contain "Email is invalid"
assert_contain "Password doesn't match confirmation"
assert_contain Devise.rails4? ?
"Password confirmation doesn't match Password" : "Password doesn't match confirmation"
assert_contain "2 errors prohibited"
assert_nil User.first
@@ -112,7 +113,7 @@ class RegistrationTest < ActionController::IntegrationTest
# https://github.com/mongoid/mongoid/issues/756
(pending "Fails on Mongoid < 2.1"; break) if defined?(Mongoid) && Mongoid::VERSION.to_f < 2.1
user = create_user
create_user
get new_user_registration_path
fill_in 'email', :with => 'user@test.com'
@@ -206,7 +207,8 @@ class RegistrationTest < ActionController::IntegrationTest
fill_in 'current password', :with => '12345678'
click_button 'Update'
assert_contain "Password doesn't match confirmation"
assert_contain Devise.rails4? ?
"Password confirmation doesn't match Password" : "Password doesn't match confirmation"
assert_not User.first.valid_password?('pas123')
end
@@ -251,7 +253,7 @@ class RegistrationTest < ActionController::IntegrationTest
assert_response :success
assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<admin>)
admin = Admin.last :order => "id"
admin = Admin.order(:id).last
assert_equal admin.email, 'new_user@test.com'
end
@@ -260,7 +262,7 @@ class RegistrationTest < ActionController::IntegrationTest
assert_response :success
assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<user>)
user = User.last :order => "id"
user = User.order(:id).last
assert_equal user.email, 'new_user@test.com'
end
@@ -285,14 +287,14 @@ class RegistrationTest < ActionController::IntegrationTest
end
test 'a user cancel his account in XML format should return valid response' do
user = sign_in_as_user
sign_in_as_user
delete user_registration_path(:format => 'xml')
assert_response :success
assert_equal User.count, 0
end
end
class ReconfirmableRegistrationTest < ActionController::IntegrationTest
class ReconfirmableRegistrationTest < ActionDispatch::IntegrationTest
test 'a signed in admin should see a more appropriate flash message when editing his account if reconfirmable is enabled' do
sign_in_as_admin
get edit_admin_registration_path

View File

@@ -1,6 +1,6 @@
require 'test_helper'
class RememberMeTest < ActionController::IntegrationTest
class RememberMeTest < ActionDispatch::IntegrationTest
def create_user_and_remember(add_to_token='')
user = create_user
user.remember_me!
@@ -26,7 +26,7 @@ class RememberMeTest < ActionController::IntegrationTest
end
test 'do not remember the user if he has not checked remember me option' do
user = sign_in_as_user
sign_in_as_user
assert_nil request.cookies["remember_user_cookie"]
end
@@ -43,7 +43,7 @@ class RememberMeTest < ActionController::IntegrationTest
end
test 'generate remember token after sign in' do
user = sign_in_as_user :remember_me => true
sign_in_as_user :remember_me => true
assert request.cookies["remember_user_token"]
end
@@ -57,6 +57,13 @@ class RememberMeTest < ActionController::IntegrationTest
end
end
test 'generate remember token with a custom key' do
swap Devise, :rememberable_options => { :key => "v1lat_token" } do
user = sign_in_as_user :remember_me => true
assert request.cookies["v1lat_token"]
end
end
test 'generate remember token after sign in setting session options' do
begin
Rails.configuration.session_options[:domain] = "omg.somewhere.com"
@@ -77,7 +84,7 @@ class RememberMeTest < ActionController::IntegrationTest
end
test 'remember the user before sign up and redirect him to his home' do
user = create_user_and_remember
create_user_and_remember
get new_user_registration_path
assert warden.authenticated?(:user)
assert_redirected_to root_path
@@ -85,7 +92,7 @@ class RememberMeTest < ActionController::IntegrationTest
test 'cookies are destroyed on unverified requests' do
swap ApplicationController, :allow_forgery_protection => true do
user = create_user_and_remember
create_user_and_remember
get users_path
assert warden.authenticated?(:user)
post root_path, :authenticity_token => 'INVALID'
@@ -110,7 +117,7 @@ class RememberMeTest < ActionController::IntegrationTest
end
test 'do not remember other scopes' do
user = create_user_and_remember
create_user_and_remember
get root_path
assert_response :success
assert warden.authenticated?(:user)
@@ -118,14 +125,14 @@ class RememberMeTest < ActionController::IntegrationTest
end
test 'do not remember with invalid token' do
user = create_user_and_remember('add')
create_user_and_remember('add')
get users_path
assert_not warden.authenticated?(:user)
assert_redirected_to new_user_session_path
end
test 'do not remember with expired token' do
user = create_user_and_remember
create_user_and_remember
swap Devise, :remember_for => 0 do
get users_path
assert_not warden.authenticated?(:user)
@@ -134,7 +141,7 @@ class RememberMeTest < ActionController::IntegrationTest
end
test 'do not remember the user anymore after forget' do
user = create_user_and_remember
create_user_and_remember
get users_path
assert warden.authenticated?(:user)

View File

@@ -1,6 +1,6 @@
require 'test_helper'
class SessionTimeoutTest < ActionController::IntegrationTest
class SessionTimeoutTest < ActionDispatch::IntegrationTest
def last_request_at
@controller.user_session['last_request_at']

View File

@@ -1,6 +1,6 @@
require 'test_helper'
class TokenAuthenticationTest < ActionController::IntegrationTest
class TokenAuthenticationTest < ActionDispatch::IntegrationTest
test 'authenticate with valid authentication token key and value through params' do
swap Devise, :token_authentication_key => :secret_token do
@@ -129,6 +129,46 @@ class TokenAuthenticationTest < ActionController::IntegrationTest
end
end
test 'authenticate with valid authentication token key and value through http header' do
swap Devise, :token_authentication_key => :secret_token do
sign_in_as_new_user_with_token(:token_auth => true)
assert_response :success
assert_match '<email>user@test.com</email>', response.body
assert_equal request.env['devise.token_options'], {}
assert warden.authenticated?(:user)
end
end
test 'authenticate with valid authentication token key and value through http header, with options' do
swap Devise, :token_authentication_key => :secret_token, :http_authenticatable => [:token_options] do
signature = "**TESTSIGNATURE**"
sign_in_as_new_user_with_token(:token_auth => true, :token_options => {:signature => signature, :nonce => 'def'})
assert_response :success
assert_match '<email>user@test.com</email>', response.body
assert_equal request.env['devise.token_options'][:signature], signature
assert_equal request.env['devise.token_options'][:nonce], 'def'
assert warden.authenticated?(:user)
end
end
test 'authenticate with valid authentication token key and value through http header without allowing token authorization setting is denied' do
swap Devise, :token_authentication_key => :secret_token, :http_authenticatable => false do
sign_in_as_new_user_with_token(:token_auth => true)
assert_response :unauthorized
assert_nil warden.user(:user)
end
end
test 'does not authenticate with improper authentication token value in header' do
sign_in_as_new_user_with_token(:token_auth => true, :auth_token => '*** INVALID TOKEN ***')
assert_response :unauthorized
assert_nil warden.user(:user)
end
private
def sign_in_as_new_user_with_token(options = {})
@@ -140,6 +180,10 @@ class TokenAuthenticationTest < ActionController::IntegrationTest
if options[:http_auth]
header = "Basic #{Base64.encode64("#{VALID_AUTHENTICATION_TOKEN}:X")}"
get users_path(:format => :xml), {}, "HTTP_AUTHORIZATION" => header
elsif options[:token_auth]
token_options = options[:token_options] || {}
header = ActionController::HttpAuthentication::Token.encode_credentials(options[:auth_token], token_options)
get users_path(:format => :xml), {}, "HTTP_AUTHORIZATION" => header
else
visit users_path(options[:auth_token_key].to_sym => options[:auth_token])
end

View File

@@ -1,6 +1,6 @@
require 'test_helper'
class TrackableHooksTest < ActionController::IntegrationTest
class TrackableHooksTest < ActionDispatch::IntegrationTest
test "current and last sign in timestamps are updated on each sign in" do
user = create_user

View File

@@ -46,6 +46,16 @@ class ConfirmationInstructionsTest < ActionMailer::TestCase
assert_equal ['custom@example.com'], mail.from
end
test 'setup sender from custom mailer defaults with proc' do
Devise.mailer = 'Users::FromProcMailer'
assert_equal ['custom@example.com'], mail.from
end
test 'custom mailer renders parent mailer template' do
Devise.mailer = 'Users::Mailer'
assert_not_blank mail.body.encoded
end
test 'setup reply to as copy from sender' do
assert_equal ['test@example.com'], mail.reply_to
end
@@ -56,7 +66,6 @@ class ConfirmationInstructionsTest < ActionMailer::TestCase
assert_equal ['custom_reply_to@example.com'], mail.reply_to
end
test 'setup subject from I18n' do
store_translations :en, :devise => { :mailer => { :confirmation_instructions => { :subject => 'Account Confirmation' } } } do
assert_equal 'Account Confirmation', mail.subject
@@ -70,7 +79,7 @@ class ConfirmationInstructionsTest < ActionMailer::TestCase
end
test 'body should have user info' do
assert_match /#{user.email}/, mail.body.encoded
assert_match user.email, mail.body.encoded
end
test 'body should have link to confirm the account' do

View File

@@ -1,7 +1,6 @@
require 'test_helper'
class ResetPasswordInstructionsTest < ActionMailer::TestCase
def setup
setup_mailer
Devise.mailer = 'Devise::Mailer'
@@ -49,6 +48,16 @@ class ResetPasswordInstructionsTest < ActionMailer::TestCase
assert_equal ['custom@example.com'], mail.from
end
test 'setup sender from custom mailer defaults with proc' do
Devise.mailer = 'Users::FromProcMailer'
assert_equal ['custom@example.com'], mail.from
end
test 'custom mailer renders parent mailer template' do
Devise.mailer = 'Users::Mailer'
assert_not_blank mail.body.encoded
end
test 'setup reply to as copy from sender' do
assert_equal ['test@example.com'], mail.reply_to
end
@@ -66,7 +75,7 @@ class ResetPasswordInstructionsTest < ActionMailer::TestCase
end
test 'body should have user info' do
assert_match(/#{user.email}/, mail.body.encoded)
assert_match user.email, mail.body.encoded
end
test 'body should have link to confirm the account' do

View File

@@ -49,6 +49,16 @@ class UnlockInstructionsTest < ActionMailer::TestCase
assert_equal ['custom@example.com'], mail.from
end
test 'setup sender from custom mailer defaults with proc' do
Devise.mailer = 'Users::FromProcMailer'
assert_equal ['custom@example.com'], mail.from
end
test 'custom mailer renders parent mailer template' do
Devise.mailer = 'Users::Mailer'
assert_not_blank mail.body.encoded
end
test 'setup reply to as copy from sender' do
assert_equal ['test@example.com'], mail.reply_to
end
@@ -66,7 +76,7 @@ class UnlockInstructionsTest < ActionMailer::TestCase
end
test 'body should have user info' do
assert_match(/#{user.email}/, mail.body.encoded)
assert_match user.email, mail.body.encoded
end
test 'body should have link to unlock the account' do

View File

@@ -4,4 +4,10 @@ class AuthenticatableTest < ActiveSupport::TestCase
test 'required_fields should be an empty array' do
assert_equal Devise::Models::Validatable.required_fields(User), []
end
end
test 'find_first_by_auth_conditions allows custom filtering parameters' do
user = User.create!(:email => "example@example.com", :password => "123456")
assert_equal User.find_first_by_auth_conditions({ :email => "example@example.com" }), user
assert_nil User.find_first_by_auth_conditions({ :email => "example@example.com" }, :id => user.id.to_s.next)
end
end

View File

@@ -104,6 +104,16 @@ class ConfirmableTest < ActiveSupport::TestCase
end
end
test 'should skip confirmation e-mail without confirming if skip_confirmation_notification! is invoked' do
user = new_user
user.skip_confirmation_notification!
assert_email_not_sent do
user.save!
assert !user.confirmed?
end
end
test 'should find a user to send confirmation instructions' do
user = create_user
confirmation_user = User.send_confirmation_instructions(:email => user.email)
@@ -204,6 +214,13 @@ class ConfirmableTest < ActiveSupport::TestCase
assert_not user.active_for_authentication?
end
test 'should be active when we set allow_unconfirmed_access_for to nil' do
Devise.allow_unconfirmed_access_for = nil
user = create_user
user.confirmation_sent_at = Date.today
assert user.active_for_authentication?
end
test 'should not be active without confirmation' do
user = create_user
user.confirmation_sent_at = nil

View File

@@ -47,15 +47,21 @@ class DatabaseAuthenticatableTest < ActiveSupport::TestCase
end
test "param filter should not convert booleans and integer to strings" do
conditions = { 'login' => 'foo@bar.com', "bool1" => true, "bool2" => false, "fixnum" => 123, "will_be_converted" => (1..10) }
conditions = { "login" => "foo@bar.com", "bool1" => true, "bool2" => false, "fixnum" => 123, "will_be_converted" => (1..10) }
conditions = Devise::ParamFilter.new([], []).filter(conditions)
assert_equal( { 'login' => 'foo@bar.com', "bool1" => true, "bool2" => false, "fixnum" => 123, "will_be_converted" => "1..10" }, conditions)
assert_equal( { "login" => "foo@bar.com", "bool1" => "true", "bool2" => "false", "fixnum" => "123", "will_be_converted" => "1..10" }, conditions)
end
test "param filter should not convert regular expressions to strings" do
conditions = { "regexp" => /expression/ }
conditions = Devise::ParamFilter.new([], []).filter(conditions)
assert_equal( { "regexp" => /expression/ }, conditions)
test 'param filter should filter case_insensitive_keys as insensitive' do
conditions = {'insensitive' => 'insensitive_VAL', 'sensitive' => 'sensitive_VAL'}
conditions = Devise::ParamFilter.new(['insensitive'], []).filter(conditions)
assert_equal( {'insensitive' => 'insensitive_val', 'sensitive' => 'sensitive_VAL'}, conditions )
end
test 'param filter should filter strip_whitespace_keys stripping whitespaces' do
conditions = {'strip_whitespace' => ' strip_whitespace_val ', 'do_not_strip_whitespace' => ' do_not_strip_whitespace_val '}
conditions = Devise::ParamFilter.new([], ['strip_whitespace']).filter(conditions)
assert_equal( {'strip_whitespace' => 'strip_whitespace_val', 'do_not_strip_whitespace' => ' do_not_strip_whitespace_val '}, conditions )
end
test 'should respond to password and password confirmation' do
@@ -117,13 +123,6 @@ class DatabaseAuthenticatableTest < ActiveSupport::TestCase
assert user.reload.valid_password?('pass4321')
end
test 'should update password with valid current password and :as option' do
user = create_user
assert user.update_with_password(:current_password => '12345678',
:password => 'pass4321', :password_confirmation => 'pass4321', :as => :admin)
assert user.reload.valid_password?('pass4321')
end
test 'should add an error to current password when it is invalid' do
user = create_user
assert_not user.update_with_password(:current_password => 'other',
@@ -176,12 +175,6 @@ class DatabaseAuthenticatableTest < ActiveSupport::TestCase
assert_equal 'new@example.com', user.email
end
test 'should update the user without password with :as option' do
user = create_user
user.update_without_password(:email => 'new@example.com', :as => :admin)
assert_equal 'new@example.com', user.email
end
test 'should not update password without password' do
user = create_user
user.update_without_password(:password => 'pass4321', :password_confirmation => 'pass4321')
@@ -189,6 +182,26 @@ class DatabaseAuthenticatableTest < ActiveSupport::TestCase
assert user.valid_password?('12345678')
end
test 'should destroy user if current password is valid' do
user = create_user
assert user.destroy_with_password('12345678')
assert !user.persisted?
end
test 'should not destroy user with invalid password' do
user = create_user
assert_not user.destroy_with_password('other')
assert user.persisted?
assert_match "is invalid", user.errors[:current_password].join
end
test 'should not destroy user with blank password' do
user = create_user
assert_not user.destroy_with_password(nil)
assert user.persisted?
assert_match "can't be blank", user.errors[:current_password].join
end
test 'downcase_keys with validation' do
user = User.create(:email => "HEllO@example.com", :password => "123456")
user = User.create(:email => "HEllO@example.com", :password => "123456")

View File

@@ -59,7 +59,7 @@ class LockableTest < ActiveSupport::TestCase
assert_not user.active_for_authentication?
end
test "should unlock a user by cleaning locked_at, falied_attempts and unlock_token" do
test "should unlock a user by cleaning locked_at, failed_attempts and unlock_token" do
user = create_user
user.lock_access!
assert_not_nil user.reload.locked_at

View File

@@ -57,9 +57,10 @@ class RememberableTest < ActiveSupport::TestCase
test 'forget_me should not try to update resource if it has been destroyed' do
resource = create_resource
resource.destroy
resource.expects(:remember_created_at).never
resource.expects(:save).never
resource.destroy
resource.forget_me!
end
@@ -114,7 +115,7 @@ class RememberableTest < ActiveSupport::TestCase
end
end
test 'remember should not be expired if it was created whitin the limit time' do
test 'remember should not be expired if it was created within the limit time' do
swap Devise, :remember_for => 30.days do
resource = create_resource
resource.remember_me!
@@ -166,7 +167,7 @@ class RememberableTest < ActiveSupport::TestCase
end
end
test 'should have the required_fiels array' do
test 'should have the required_fields array' do
assert_same_content Devise::Models::Rememberable.required_fields(User), [
:remember_created_at
]

View File

@@ -6,18 +6,18 @@ class SerializableTest < ActiveSupport::TestCase
end
test 'should not include unsafe keys on XML' do
assert_match /email/, @user.to_xml
assert_no_match /confirmation-token/, @user.to_xml
assert_match(/email/, @user.to_xml)
assert_no_match(/confirmation-token/, @user.to_xml)
end
test 'should not include unsafe keys on XML even if a new except is provided' do
assert_no_match /email/, @user.to_xml(:except => :email)
assert_no_match /confirmation-token/, @user.to_xml(:except => :email)
assert_no_match(/email/, @user.to_xml(:except => :email))
assert_no_match(/confirmation-token/, @user.to_xml(:except => :email))
end
test 'should include unsafe keys on XML if a force_except is provided' do
assert_no_match /<email/, @user.to_xml(:force_except => :email)
assert_match /confirmation-token/, @user.to_xml(:force_except => :email)
assert_no_match(/<email/, @user.to_xml(:force_except => :email))
assert_match(/confirmation-token/, @user.to_xml(:force_except => :email))
end
test 'should not include unsafe keys on JSON' do

View File

@@ -56,10 +56,15 @@ class ValidatableTest < ActiveSupport::TestCase
test 'should require confirmation to be set when creating a new record' do
user = new_user(:password => 'new_password', :password_confirmation => 'blabla')
assert user.invalid?
assert_equal 'doesn\'t match confirmation', user.errors[:password].join
if Devise.rails4?
assert_equal 'doesn\'t match Password', user.errors[:password_confirmation].join
else
assert_equal 'doesn\'t match confirmation', user.errors[:password].join
end
end
test 'should require password when updating/reseting password' do
test 'should require password when updating/resetting password' do
user = create_user
user.password = ''
@@ -69,11 +74,16 @@ class ValidatableTest < ActiveSupport::TestCase
assert_equal 'can\'t be blank', user.errors[:password].join
end
test 'should require confirmation when updating/reseting password' do
test 'should require confirmation when updating/resetting password' do
user = create_user
user.password_confirmation = 'another_password'
assert user.invalid?
assert_equal 'doesn\'t match confirmation', user.errors[:password].join
if Devise.rails4?
assert_equal 'doesn\'t match Password', user.errors[:password_confirmation].join
else
assert_equal 'doesn\'t match confirmation', user.errors[:password].join
end
end
test 'should require a password with minimum of 6 characters' do
@@ -98,7 +108,7 @@ class ValidatableTest < ActiveSupport::TestCase
assert_not (user.errors[:password].join =~ /is too long/)
end
test 'should complain about length even if possword is not required' do
test 'should complain about length even if password is not required' do
user = new_user(:password => 'x'*129, :password_confirmation => 'x'*129)
user.stubs(:password_required?).returns(false)
assert user.invalid?

View File

@@ -83,7 +83,12 @@ class ActiveRecordTest < ActiveSupport::TestCase
end
test 'set null fields on migrations' do
Admin.create!
# Ignore email sending since no email exists.
klass = Class.new(Admin) do
def send_devise_notification(*); end
end
klass.create!
end
end

View File

@@ -1,6 +1,9 @@
require 'test_helper'
class OmniAuthRoutesTest < ActionController::TestCase
ExpectedUrlGeneratiorError = Devise.rails4? ?
ActionController::UrlGenerationError : ActionController::RoutingError
tests ApplicationController
def assert_path(action, provider, with_param=true)
@@ -30,7 +33,7 @@ class OmniAuthRoutesTest < ActionController::TestCase
test 'should generate authorization path' do
assert_match "/users/auth/facebook", @controller.omniauth_authorize_path(:user, :facebook)
assert_raise ActionController::RoutingError do
assert_raise ExpectedUrlGeneratiorError do
@controller.omniauth_authorize_path(:user, :github)
end
end

View File

@@ -1,5 +1,6 @@
ActiveRecord::Migration.verbose = false
ActiveRecord::Base.logger = Logger.new(nil)
ActiveRecord::Base.include_root_in_json = true
ActiveRecord::Migrator.migrate(File.expand_path("../../rails_app/db/migrate/", __FILE__))

View File

@@ -0,0 +1,51 @@
require 'test_helper'
require 'devise/parameter_sanitizer'
class BaseSanitizerTest < ActiveSupport::TestCase
def sanitizer
Devise::BaseSanitizer.new(User, :user, { user: { "email" => "jose" } })
end
test 'returns chosen params' do
assert_equal({ "email" => "jose" }, sanitizer.for(:sign_in))
end
end
if defined?(ActionController::StrongParameters)
require 'active_model/forbidden_attributes_protection'
class ParameterSanitizerTest < ActiveSupport::TestCase
def sanitizer(params)
params = ActionController::Parameters.new(params)
Devise::ParameterSanitizer.new(User, :user, params)
end
test 'filters some parameters on sign in by default' do
sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid" })
assert_equal({ "email" => "jose" }, sanitizer.for(:sign_in))
end
test 'filters some parameters on sign up by default' do
sanitizer = sanitizer(user: { "email" => "jose", "role" => "invalid" })
assert_equal({ "email" => "jose" }, sanitizer.for(:sign_up))
end
test 'filters some parameters on account update by default' do
sanitizer = sanitizer(user: { "email" => "jose", "role" => "invalid" })
assert_equal({ "email" => "jose" }, sanitizer.for(:account_update))
end
test 'allows custom hooks' do
sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid" })
sanitizer.for(:sign_in) { |user| user.permit(:email, :password) }
assert_equal({ "email" => "jose", "password" => "invalid" }, sanitizer.for(:sign_in))
end
test 'raises on unknown hooks' do
sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid" })
assert_raise NotImplementedError do
sanitizer.for(:unknown)
end
end
end
end

View File

@@ -3,8 +3,4 @@
require File.expand_path('../config/application', __FILE__)
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
Rails.application.load_tasks

View File

@@ -5,4 +5,8 @@ end
class Users::ReplyToMailer < Devise::Mailer
default :from => 'custom@example.com'
default :reply_to => 'custom_reply_to@example.com'
end
end
class Users::FromProcMailer < Devise::Mailer
default :from => proc { 'custom@example.com' }
end

View File

@@ -7,9 +7,8 @@ module Shim
end
module ClassMethods
def last(options = {})
options.delete(:order) if options[:order] == "id"
where(options).last
def order(attribute)
asc(attribute)
end
def find_by_email(email)

3
test/rails_app/bin/bundle Executable file
View File

@@ -0,0 +1,3 @@
#!/usr/bin/env ruby
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
load Gem.bin_path('bundler', 'bundle')

4
test/rails_app/bin/rails Executable file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/env ruby
APP_PATH = File.expand_path('../../config/application', __FILE__)
require_relative '../config/boot'
require 'rails/commands'

4
test/rails_app/bin/rake Executable file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/env ruby
require_relative '../config/boot'
require 'rake'
Rake.application.run

View File

@@ -2,7 +2,6 @@ require File.expand_path('../boot', __FILE__)
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
Bundler.require :default, DEVISE_ORM
@@ -17,7 +16,7 @@ require "devise"
module RailsApp
class Application < Rails::Application
# Add additional load paths for your own custom dirs
config.autoload_paths.reject!{ |p| p =~ /\/app\/(\w+)$/ && !%w(controllers helpers views).include?($1) }
config.autoload_paths.reject!{ |p| p =~ /\/app\/(\w+)$/ && !%w(controllers helpers mailers views).include?($1) }
config.autoload_paths += [ "#{config.root}/app/#{DEVISE_ORM}" ]
# Configure generators values. Many other options are available, be sure to check the documentation.

View File

@@ -2,7 +2,7 @@ unless defined?(DEVISE_ORM)
DEVISE_ORM = (ENV["DEVISE_ORM"] || :active_record).to_sym
end
require 'rubygems'
require 'bundler/setup'
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__)
$:.unshift File.expand_path('../../../../lib', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])

View File

@@ -1,5 +1,5 @@
# Load the rails application
# Load the rails application.
require File.expand_path('../application', __FILE__)
# Initialize the rails application
# Initialize the rails application.
RailsApp::Application.initialize!

View File

@@ -1,18 +1,34 @@
RailsApp::Application.configure do
# Settings specified here will take precedence over those in config/environment.rb
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers.
config.action_dispatch.best_standards_support = :builtin
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL).
config.active_record.auto_explain_threshold_in_seconds = 0.5
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
config.assets.debug = true
end

View File

@@ -1,33 +1,84 @@
RailsApp::Application.configure do
# Settings specified here will take precedence over those in config/environment.rb
# Settings specified here will take precedence over those in config/application.rb.
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
# Code is not reloaded between requests.
config.cache_classes = true
# Full error reports are disabled and caching is turned on
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Enable serving of images, stylesheets, and javascripts from an asset server
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Whether to fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors, bad email addresses will be ignored
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL).
# config.active_record.auto_explain_threshold_in_seconds = 0.5
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end

View File

@@ -1,33 +1,36 @@
RailsApp::Application.configure do
# Settings specified here will take precedence over those in config/environment.rb
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Show full error reports and disable caching
# Configure static asset server for tests with Cache-Control for performance.
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
config.action_dispatch.show_exceptions = false
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
end

View File

@@ -1,2 +1,8 @@
Rails.application.config.secret_token = 'ea942c41850d502f2c8283e26bdc57829f471bb18224ddff0a192c4f32cdf6cb5aa0d82b3a7a7adbeb640c4b06f3aa1cd5f098162d8240f669b39d6b49680571'
Rails.application.config.session_store :cookie_store, :key => "_my_app"
config = Rails.application.config
if Devise.rails4?
config.secret_key_base = 'd588e99efff13a86461fd6ab82327823ad2f8feb5dc217ce652cdd9f0dfc5eb4b5a62a92d24d2574d7d51dfb1ea8dd453ea54e00cf672159a13104a135422a10'
else
config.secret_token = 'ea942c41850d502f2c8283e26bdc57829f471bb18224ddff0a192c4f32cdf6cb5aa0d82b3a7a7adbeb640c4b06f3aa1cd5f098162d8240f669b39d6b49680571'
config.session_store :cookie_store, :key => "_my_app"
end

View File

@@ -0,0 +1 @@
RailsApp::Application.config.session_store :cookie_store, key: '_rails_app_session'

View File

@@ -17,39 +17,39 @@ Rails.application.routes.draw do
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
as :user do
match "/as/sign_in", :to => "devise/sessions#new"
get "/as/sign_in", :to => "devise/sessions#new"
end
match "/sign_in", :to => "devise/sessions#new"
get "/sign_in", :to => "devise/sessions#new"
# Admin scope
devise_for :admin, :path => "admin_area", :controllers => { :sessions => :"admins/sessions" }, :skip => :passwords
match "/admin_area/home", :to => "admins#index", :as => :admin_root
match "/anywhere", :to => "foo#bar", :as => :new_admin_password
get "/admin_area/home", :to => "admins#index", :as => :admin_root
get "/anywhere", :to => "foo#bar", :as => :new_admin_password
authenticate(:admin) do
match "/private", :to => "home#private", :as => :private
get "/private", :to => "home#private", :as => :private
end
authenticate(:admin, lambda { |admin| admin.active? }) do
match "/private/active", :to => "home#private", :as => :private_active
get "/private/active", :to => "home#private", :as => :private_active
end
authenticated :admin do
match "/dashboard", :to => "home#admin_dashboard"
get "/dashboard", :to => "home#admin_dashboard"
end
authenticated :admin, lambda { |admin| admin.active? } do
match "/dashboard/active", :to => "home#admin_dashboard"
get "/dashboard/active", :to => "home#admin_dashboard"
end
authenticated do
match "/dashboard", :to => "home#user_dashboard"
get "/dashboard", :to => "home#user_dashboard"
end
unauthenticated do
match "/join", :to => "home#join"
get "/join", :to => "home#join"
end
# Routes for constraints testing
@@ -92,9 +92,9 @@ Rails.application.routes.draw do
devise_for :delete_or_posts, :sign_out_via => [:delete, :post], :class_name => "Admin"
end
match "/set", :to => "home#set"
match "/unauthenticated", :to => "home#unauthenticated"
match "/custom_strategy/new"
get "/set", :to => "home#set"
get "/unauthenticated", :to => "home#unauthenticated"
get "/custom_strategy/new"
root :to => "home#index"
root :to => "home#index", :via => [:get, :post]
end

View File

@@ -7,7 +7,6 @@ module SharedUser
:trackable, :validatable, :omniauthable
attr_accessor :other_key
attr_accessible :username, :email, :password, :password_confirmation, :remember_me, :confirmation_sent_at
# They need to be included after Devise is called.
extend ExtendMethods

View File

@@ -1,10 +0,0 @@
#!/usr/bin/env ruby
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
ENV_PATH = File.expand_path('../../config/environment', __FILE__)
BOOT_PATH = File.expand_path('../../config/boot', __FILE__)
APP_PATH = File.expand_path('../../config/application', __FILE__)
ROOT_PATH = File.expand_path('../..', __FILE__)
require BOOT_PATH
require 'rails/commands'

View File

@@ -1,5 +1,7 @@
require 'test_helper'
ExpectedRoutingError = Devise.rails4? ? MiniTest::Assertion : ActionController::RoutingError
class DefaultRoutingTest < ActionController::TestCase
test 'map new user session' do
assert_recognizes({:controller => 'devise/sessions', :action => 'new'}, {:path => 'users/sign_in', :method => :get})
@@ -101,7 +103,7 @@ class DefaultRoutingTest < ActionController::TestCase
assert_recognizes({:controller => 'users/omniauth_callbacks', :action => 'google'}, {:path => 'users/auth/google/callback', :method => :post})
assert_named_route "/users/auth/google/callback", :user_omniauth_callback_path, :google
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'ysers/omniauth_callbacks', :action => 'twitter'}, {:path => 'users/auth/twitter/callback', :method => :get})
end
end
@@ -123,7 +125,7 @@ class CustomizedRoutingTest < ActionController::TestCase
end
test 'does not map admin password' do
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'devise/passwords', :action => 'new'}, 'admin_area/password/new')
end
end
@@ -133,7 +135,7 @@ class CustomizedRoutingTest < ActionController::TestCase
end
test 'does only map reader password' do
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'devise/sessions', :action => 'new'}, 'reader/sessions/new')
end
assert_recognizes({:controller => 'devise/passwords', :action => 'new'}, 'reader/password/new')
@@ -161,14 +163,14 @@ class CustomizedRoutingTest < ActionController::TestCase
test 'map deletes with :sign_out_via option' do
assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/deletes/sign_out', :method => :delete})
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/deletes/sign_out', :method => :get})
end
end
test 'map posts with :sign_out_via option' do
assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/posts/sign_out', :method => :post})
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/posts/sign_out', :method => :get})
end
end
@@ -176,56 +178,56 @@ class CustomizedRoutingTest < ActionController::TestCase
test 'map delete_or_posts with :sign_out_via option' do
assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/delete_or_posts/sign_out', :method => :post})
assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/delete_or_posts/sign_out', :method => :delete})
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/delete_or_posts/sign_out', :method => :get})
end
end
test 'map with constraints defined in hash' do
assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => 'http://192.168.1.100/headquarters/sign_up', :method => :get})
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => 'http://10.0.0.100/headquarters/sign_up', :method => :get})
end
end
test 'map with constraints defined in block' do
assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => 'http://192.168.1.100/homebase/sign_up', :method => :get})
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => 'http://10.0.0.100//homebase/sign_up', :method => :get})
end
end
test 'map with format false for sessions' do
assert_recognizes({:controller => 'devise/sessions', :action => 'new'}, {:path => '/htmlonly_admin/sign_in', :method => :get})
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'devise/sessions', :action => 'new'}, {:path => '/htmlonly_admin/sign_in.xml', :method => :get})
end
end
test 'map with format false for passwords' do
assert_recognizes({:controller => 'devise/passwords', :action => 'create'}, {:path => '/htmlonly_admin/password', :method => :post})
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'devise/passwords', :action => 'create'}, {:path => '/htmlonly_admin/password.xml', :method => :post})
end
end
test 'map with format false for registrations' do
assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => '/htmlonly_admin/sign_up', :method => :get})
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'devise/registrations', :action => 'new'}, {:path => '/htmlonly_admin/sign_up.xml', :method => :get})
end
end
test 'map with format false for confirmations' do
assert_recognizes({:controller => 'devise/confirmations', :action => 'show'}, {:path => '/htmlonly_users/confirmation', :method => :get})
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'devise/confirmations', :action => 'show'}, {:path => '/htmlonly_users/confirmation.xml', :method => :get})
end
end
test 'map with format false for unlocks' do
assert_recognizes({:controller => 'devise/unlocks', :action => 'show'}, {:path => '/htmlonly_users/unlock', :method => :get})
assert_raise ActionController::RoutingError do
assert_raise ExpectedRoutingError do
assert_recognizes({:controller => 'devise/unlocks', :action => 'show'}, {:path => '/htmlonly_users/unlock.xml', :method => :get})
end
end

View File

@@ -4,13 +4,20 @@ DEVISE_ORM = (ENV["DEVISE_ORM"] || :active_record).to_sym
$:.unshift File.dirname(__FILE__)
puts "\n==> Devise.orm = #{DEVISE_ORM.inspect}"
module Devise
# Detection for minor differences between Rails 3.2 and 4 in tests.
def self.rails4?
Rails.version.start_with? '4'
end
end
require "rails_app/config/environment"
require "rails/test_help"
require "orm/#{DEVISE_ORM}"
I18n.load_path << File.expand_path("../support/locale/en.yml", __FILE__)
require 'mocha'
require 'mocha/setup'
require 'webrat'
Webrat.configure do |config|
config.mode = :rails

View File

@@ -15,7 +15,6 @@ end
class UserWithVirtualAttributes < User
devise :case_insensitive_keys => [ :email, :email_confirmation ]
validates :email, :presence => true, :confirmation => {:on => :create}
attr_accessible :email, :email_confirmation
end
class Several < Admin