Compare commits

..

9 Commits

Author SHA1 Message Date
José Valim
beeb48c404 Release v2.2.8 2013-11-13 14:11:45 +01:00
José Valim
cd982123a8 Release 2.2.7 2013-08-18 10:29:38 +02:00
José Valim
02a2976f5e Release v2.2.6 2013-08-09 10:31:54 +02:00
José Valim
a44002c68b Fix the build 2013-08-09 10:21:22 +02:00
José Valim
60f3c678e6 Skip storage for cookies on unverified requests 2013-08-09 09:33:19 +02:00
José Valim
81141bb9c8 Update Gemfile.lock 2013-08-02 23:45:31 +02:00
José Valim
373fd03ebc Release 2.2.5 2013-08-02 23:24:17 +02:00
José Valim
b3eace20c7 Update CHANGELOG 2013-08-02 23:22:39 +02:00
José Valim
415fa2ad21 Protect against CSRF token fixation attacks 2013-08-02 23:16:32 +02:00
72 changed files with 432 additions and 915 deletions

View File

@@ -1,13 +1,28 @@
language: ruby
script: "bundle exec rake test"
rvm:
- 1.8.7
- 1.9.2
- 1.9.3
- 2.0.0
env:
- DEVISE_ORM=mongoid
- DEVISE_ORM=active_record
matrix:
exclude:
- 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.2.x
- gemfiles/Gemfile.rails-3.1.x
- Gemfile
services:
- mongodb

View File

@@ -1,41 +1,25 @@
== 3.0.4
== 2.2.8
Security announcement: http://blog.plataformatec.com.br/2013/11/e-mail-enumeration-in-devise-in-paranoid-mode
* bug fix
* Avoid e-mail enumeration on sign in when in paranoid mode
== 3.0.3
== 2.2.7
* bug fix
* Do not confirm account after reset password
== 3.0.2
== 2.2.6
* bug fix
* Skip storage for cookies on unverified requests
== 3.0.1
Security announcement: http://blog.plataformatec.com.br/2013/08/csrf-token-fixation-attacks-in-devise/
* enhancements
* Add after_confirmation callback
== 2.2.5
* bug fix
* When using rails 3.2, the generator adds 'attr_accessible' to the model (by @jcoyne)
* Clean up CSRF token after authentication (by @homakov). Notice this change will clean up the CSRF Token after authentication (sign in, sign up, etc). So if you are using AJAX for such features, you will need to fetch a new CSRF token from the server.
== 3.0.0
* enhancements
* Rails 4 and Strong Parameters compatibility (by @carlosantoniodasilva, @josevalim, @latortuga, @lucasmazza, @nashby, @rafaelfranca, @spastorino)
* Drop support for Rails < 3.2 and Ruby < 1.9.3
* Enable to skip sending reconfirmation email when reconfirmable is on and skip_confirmation_notification! is invoked (by @tkhr)
* bug fix
* Errors on unlock are now properly reflected on the first `unlock_keys`
== 2.2.4
* enhancements
@@ -151,7 +135,6 @@ Security announcement: http://blog.plataformatec.com.br/2013/01/security-announc
* Do not accidentally mark `_prefixes` as private
* Better support for custom strategies on test helpers (by @mattconnolly)
* Return `head :no_content` in SessionsController now that most JS libraries handle it (by @julianvargasalvarez)
* Reverted moving devise/shared/_links.erb to devise/_links.erb
== 2.0.4

View File

@@ -2,7 +2,7 @@ source "https://rubygems.org"
gemspec
gem "rails", "~> 4.0.0"
gem "rails", "~> 3.2.6"
gem "omniauth", "~> 1.0.0"
gem "omniauth-oauth2", "~> 1.0.0"
gem "rdoc"
@@ -24,8 +24,9 @@ platforms :ruby do
gem "sqlite3"
end
platforms :mri_19, :mri_20 do
platforms :mri_19 do
group :mongoid do
gem "mongoid", github: "mongoid/mongoid", branch: "master"
gem "mongoid", "~> 3.0"
end
end

View File

@@ -1,74 +1,71 @@
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 (3.0.4)
devise (2.2.8)
bcrypt-ruby (~> 3.0)
orm_adapter (~> 0.1)
railties (>= 3.2.6, < 5)
warden (~> 1.2.3)
railties (~> 3.1)
warden (~> 1.2.1)
GEM
remote: https://rubygems.org/
specs:
actionmailer (4.0.0)
actionpack (= 4.0.0)
actionmailer (3.2.13)
actionpack (= 3.2.13)
mail (~> 2.5.3)
actionpack (4.0.0)
activesupport (= 4.0.0)
builder (~> 3.1.0)
actionpack (3.2.13)
activemodel (= 3.2.13)
activesupport (= 3.2.13)
builder (~> 3.0.0)
erubis (~> 2.7.0)
rack (~> 1.5.2)
rack-test (~> 0.6.2)
activemodel (4.0.0)
activesupport (= 4.0.0)
builder (~> 3.1.0)
activerecord (4.0.0)
activemodel (= 4.0.0)
activerecord-deprecated_finders (~> 1.0.2)
activesupport (= 4.0.0)
arel (~> 4.0.0)
activerecord-deprecated_finders (1.0.3)
activesupport (4.0.0)
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.10)
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.1.2)
builder (3.1.4)
builder (3.0.4)
erubis (2.7.0)
faraday (0.8.7)
multipart-post (~> 1.1)
hashie (1.2.0)
hike (1.2.3)
hike (1.2.2)
httpauth (0.2.0)
i18n (0.6.4)
i18n (0.6.1)
journey (1.0.4)
json (1.7.7)
jwt (0.1.8)
multi_json (>= 1.5)
mail (2.5.4)
mail (2.5.3)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
metaclass (0.0.1)
mime-types (1.23)
minitest (4.7.5)
mime-types (1.22)
mocha (0.13.3)
metaclass (~> 0.0.1)
mongoid (3.1.2)
activemodel (~> 3.2)
moped (~> 1.4.2)
origin (~> 1.0)
tzinfo (~> 0.3.22)
moped (1.4.5)
multi_json (1.7.7)
multi_json (1.7.2)
multipart-post (1.2.0)
nokogiri (1.5.9)
oauth2 (0.8.1)
@@ -88,47 +85,47 @@ GEM
omniauth-openid (1.0.1)
omniauth (~> 1.0)
rack-openid (~> 1.3.1)
origin (1.1.0)
origin (1.0.11)
orm_adapter (0.4.0)
polyglot (0.3.3)
rack (1.5.2)
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 (4.0.0)
actionmailer (= 4.0.0)
actionpack (= 4.0.0)
activerecord (= 4.0.0)
activesupport (= 4.0.0)
bundler (>= 1.3.0, < 2.0)
railties (= 4.0.0)
sprockets-rails (~> 2.0.0)
railties (4.0.0)
actionpack (= 4.0.0)
activesupport (= 4.0.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)
thor (>= 0.18.1, < 2.0)
rake (10.1.0)
rdoc (4.0.1)
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.10.0)
sprockets (2.2.2)
hike (~> 1.2)
multi_json (~> 1.0)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sprockets-rails (2.0.0)
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.1)
treetop (1.4.14)
tilt (1.3.7)
treetop (1.4.12)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.37)
@@ -148,12 +145,12 @@ DEPENDENCIES
devise!
jruby-openssl
mocha (~> 0.13.1)
mongoid!
mongoid (~> 3.0)
omniauth (~> 1.0.0)
omniauth-facebook
omniauth-oauth2 (~> 1.0.0)
omniauth-openid (~> 1.0.1)
rails (~> 4.0.0)
rails (~> 3.2.6)
rdoc
sqlite3
webrat (= 0.7.3)

150
README.md
View File

@@ -12,7 +12,7 @@ Devise is a flexible authentication solution for Rails based on Warden. It:
* Is Rack based;
* Is a complete MVC solution based on Rails engines;
* Allows you to have multiple models signed in at the same time;
* 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 11 modules:
@@ -29,8 +29,6 @@ It's composed of 11 modules:
* [Validatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Validatable): provides validations of email and password. It's optional and can be customized, so you're able to define your own validations.
* [Lockable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Lockable): locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period.
Devise is guaranteed to be thread-safe on YARV. Thread-safety support on JRuby is on progress.
## Information
### The Devise wiki
@@ -59,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 previous versions of Rails, 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 Rails 2.3, you can always run "gem server" from the command line after you install the gem to access the old documentation.
### Example applications
@@ -92,7 +90,7 @@ Once you have solidified your understanding of Rails and authentication mechanis
## Getting started
Devise 3.0 works with Rails 3.2 onwards. You can add it to your Gemfile with:
Devise 2.0 works with Rails 3.1 onwards. You can add it to your Gemfile with:
```ruby
gem 'devise'
@@ -112,7 +110,7 @@ The generator will install an initializer which describes ALL Devise's configura
rails generate devise MODEL
```
Replace MODEL by the class name used for the applications users, it's frequently `User` but could also be `Admin`. This will create a model (if one does not exist) and configure it with default Devise modules. Next, you'll usually run `rake db:migrate` as the generator will have created a migration file (if your ORM supports them). This generator also configures your config/routes.rb file to point to the Devise controller.
Replace MODEL by the class name used for the applications users, it's frequently 'User' but could also be 'Admin'. This will create a model (if one does not exist) and configure it with default Devise modules. Next, you'll usually run "rake db:migrate" as the generator will have created a migration file (if your ORM supports them). This generator also configures your config/routes.rb file to point to the Devise controller.
Note that you should re-start your app here if you've already started it. Otherwise you'll run into strange errors like users being unable to login and the route helpers being undefined.
@@ -145,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.
@@ -178,57 +176,34 @@ 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.
### Strong Parameters
### Configuring multiple models
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`:
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
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
# 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
```
If you have multiple Devise models, you may want to set up different parameter sanitizer per model. In this case, we recommend inheriting from `Devise::ParameterSanitizer` and add your own logic:
```ruby
class User::ParameterSanitizer < Devise::ParameterSanitizer
def sign_in
default_params.permit(:username, :email)
end
end
```
And then configure your controllers to use it:
```ruby
class ApplicationController < ActionController::Base
protected
def devise_parameter_sanitizer
if resource_class == User
User::ParameterSanitizer.new(User, :user, params)
else
super # Use the default one
end
end
end
```
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.
On the other hand, you can simply run the generator!
### Configuring views
@@ -240,7 +215,7 @@ Since Devise is an engine, all its views are packaged inside the gem. These view
rails generate devise:views
```
If you have more than one Devise model in your application (such as "User" and "Admin"), you will notice that Devise uses the same views for all models. Fortunately, Devise offers an easy way to customize views. All you need to do is set "config.scoped_views = true" inside "config/initializers/devise.rb".
If you have more than one role in your application (such as "User" and "Admin"), you will notice that Devise uses the same views for all roles. Fortunately, Devise offers an easy way to customize views. All you need to do is set "config.scoped_views = true" inside "config/initializers/devise.rb".
After doing so, you will be able to have views based on the role like "users/sessions/new" and "admins/sessions/new". If no view is found within the scope, Devise will use the default view at "devise/sessions/new". You can also use the generator to generate scoped views:
@@ -252,24 +227,22 @@ rails generate devise:views users
If the customization at the views level is not enough, you can customize each controller by following these steps:
1. Create your custom controller, for example a `Admins::SessionsController`:
1) Create your custom controller, for example a Admins::SessionsController:
```ruby
class Admins::SessionsController < Devise::SessionsController
end
```
```ruby
class Admins::SessionsController < Devise::SessionsController
end
```
Note that in the above example, the controller needs to be created in the `app/controller/admins/` directory.
2) Tell the router to use this controller:
2. Tell the router to use this controller:
```ruby
devise_for :admins, :controllers => { :sessions => "admins/sessions" }
```
```ruby
devise_for :admins, :controllers => { :sessions => "admins/sessions" }
```
3) And since we changed the controller, it won't use the "devise/sessions" views, so remember to copy "devise/sessions" to "admin/sessions".
3. And since we changed the controller, it won't use the `"devise/sessions"` views, so remember to copy `"devise/sessions"` to `"admin/sessions"`.
Remember that Devise uses flash messages to let users know if sign in was successful or failed. Devise expects your application to call `"flash[:notice]"` and `"flash[:alert]"` as appropriate. Do not print the entire flash hash, print specific keys or at least remove the `:timedout` key from the hash as Devise adds this key in some circumstances, this key is not meant for display.
Remember that Devise uses flash messages to let users know if sign in was successful or failed. Devise expects your application to call "flash[:notice]" and "flash[:alert]" as appropriate. Do not print the entire flash hash, print specific keys or at least remove the `:timedout` key from the hash as Devise adds this key in some circumstances, this key is not meant for display.
### Configuring routes
@@ -361,14 +334,12 @@ sign_out @user # sign_out(resource)
There are two things that is important to keep in mind:
1. These helpers are not going to work for integration tests driven by Capybara or Webrat. They are meant to be used with functional tests only. Instead, fill in the form or explicitly set the user in session;
1) These helpers are not going to work for integration tests driven by Capybara or Webrat. They are meant to be used with functional tests only. Instead, fill in the form or explicitly set the user in session;
2. If you are testing Devise internal controllers or a controller that inherits from Devise's, you need to tell Devise which mapping should be used before a request. This is necessary because Devise gets this information from router, but since functional tests do not pass through the router, it needs to be told explicitly. For example, if you are testing the user scope, simply do:
2) If you are testing Devise internal controllers or a controller that inherits from Devise's, you need to tell Devise which mapping should be used before a request. This is necessary because Devise gets this information from router, but since functional tests do not pass through the router, it needs to be told explicitly. For example, if you are testing the user scope, simply do:
```ruby
@request.env["devise.mapping"] = Devise.mappings[:user]
get :new
```
### Omniauth
@@ -382,42 +353,15 @@ 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 Devise models as you want. If you want to have an Admin model with just authentication and timeout features, in addition to the User model above, just run:
```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
```
Alternatively, you can simply run the Devise generator.
Keep in mind that those models will have completely different routes. They **do not** and **cannot** share the same controller for sign in, sign out and so on. In case you want to have different roles sharing the same actions, we recommend you to use a role-based approach, by either providing a role column or using [CanCan](https://github.com/ryanb/cancan).
### Other ORMs
Devise supports ActiveRecord (default) and Mongoid. To choose other ORM, you just need to require it in the initializer file.
## Additional information
### 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
### Heroku
@@ -429,6 +373,8 @@ 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:

View File

@@ -1,7 +1,7 @@
class Devise::ConfirmationsController < DeviseController
# GET /resource/confirmation/new
def new
self.resource = resource_class.new
build_resource({})
end
# POST /resource/confirmation
@@ -39,4 +39,5 @@ class Devise::ConfirmationsController < DeviseController
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
self.resource = resource_class.new
build_resource({})
end
# POST /resource/password
@@ -53,7 +53,7 @@ class Devise::PasswordsController < DeviseController
# Check if a reset_password_token is provided in the request
def assert_reset_token_passed
if params[:reset_password_token].blank?
set_flash_message(:alert, :no_token)
set_flash_message(:error, :no_token)
redirect_to new_session_path(resource_name)
end
end

View File

@@ -4,13 +4,13 @@ class Devise::RegistrationsController < DeviseController
# GET /resource/sign_up
def new
build_resource({})
respond_with self.resource
resource = build_resource({})
respond_with resource
end
# POST /resource
def create
build_resource(sign_up_params)
build_resource
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(account_update_params)
if resource.update_with_password(resource_params)
if is_navigational_format?
flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
:update_needs_confirmation : :updated
@@ -83,7 +83,8 @@ 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)
self.resource = resource_class.new_with_session(hash || {}, session)
hash ||= resource_params || {}
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
@@ -115,12 +116,4 @@ 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 = resource_class.new(sign_in_params)
self.resource = build_resource(nil, :unsafe => true)
clean_up_passwords(resource)
respond_with(resource, serialize_options(resource))
end
@@ -34,10 +34,6 @@ 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)

View File

@@ -3,7 +3,7 @@ class Devise::UnlocksController < DeviseController
# GET /resource/unlock/new
def new
self.resource = resource_class.new
build_resource({})
end
# POST /resource/unlock

View File

@@ -28,6 +28,10 @@ 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)
@@ -89,6 +93,23 @@ 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:
@@ -165,8 +186,4 @@ MESSAGE
format.any(*navigational_formats, &block)
end
end
def resource_params
params.fetch(resource_name, {})
end
end

View File

@@ -19,8 +19,8 @@ Gem::Specification.new do |s|
s.test_files = `git ls-files -- test/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency("warden", "~> 1.2.3")
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.2.6", "< 5")
s.add_dependency("railties", "~> 3.1")
end

View File

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

View File

@@ -1,57 +1,60 @@
PATH
remote: ..
specs:
devise (3.0.4)
devise (2.2.8)
bcrypt-ruby (~> 3.0)
orm_adapter (~> 0.1)
railties (>= 3.2.6, < 5)
warden (~> 1.2.3)
railties (~> 3.1)
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)
actionmailer (3.1.12)
actionpack (= 3.1.12)
mail (~> 2.4.4)
actionpack (3.1.12)
activemodel (= 3.1.12)
activesupport (= 3.1.12)
builder (~> 3.0.0)
erubis (~> 2.7.0)
journey (~> 1.0.4)
rack (~> 1.4.5)
i18n (~> 0.6)
rack (~> 1.3.6)
rack-cache (~> 1.2)
rack-mount (~> 0.8.2)
rack-test (~> 0.6.1)
sprockets (~> 2.2.1)
activemodel (3.2.13)
activesupport (= 3.2.13)
sprockets (~> 2.0.4)
activemodel (3.1.12)
activesupport (= 3.1.12)
builder (~> 3.0.0)
activerecord (3.2.13)
activemodel (= 3.2.13)
activesupport (= 3.2.13)
arel (~> 3.0.2)
i18n (~> 0.6)
activerecord (3.1.12)
activemodel (= 3.1.12)
activesupport (= 3.1.12)
arel (~> 2.2.3)
tzinfo (~> 0.3.29)
activeresource (3.2.13)
activemodel (= 3.2.13)
activesupport (= 3.2.13)
activesupport (3.2.13)
i18n (= 0.6.1)
activeresource (3.1.12)
activemodel (= 3.1.12)
activesupport (= 3.1.12)
activesupport (3.1.12)
multi_json (~> 1.0)
arel (3.0.2)
arel (2.2.3)
bcrypt-ruby (3.1.2)
builder (3.0.4)
columnize (0.3.6)
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)
i18n (0.6.4)
json (1.7.7)
jwt (0.1.8)
multi_json (>= 1.5)
mail (2.5.3)
linecache (0.46)
rbx-require-relative (> 0.0.4)
mail (2.4.4)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
@@ -59,9 +62,9 @@ GEM
mime-types (1.23)
mocha (0.13.3)
metaclass (~> 0.0.1)
mongoid (3.1.3)
activemodel (~> 3.2)
moped (~> 1.4.2)
mongoid (3.0.23)
activemodel (~> 3.1)
moped (~> 1.2)
origin (~> 1.0)
tzinfo (~> 0.3.22)
moped (1.4.5)
@@ -88,9 +91,11 @@ GEM
origin (1.1.0)
orm_adapter (0.4.0)
polyglot (0.3.3)
rack (1.4.5)
rack (1.3.10)
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)
@@ -98,32 +103,37 @@ GEM
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)
rails (3.1.12)
actionmailer (= 3.1.12)
actionpack (= 3.1.12)
activerecord (= 3.1.12)
activeresource (= 3.1.12)
activesupport (= 3.1.12)
bundler (~> 1.0)
railties (= 3.2.13)
railties (3.2.13)
actionpack (= 3.2.13)
activesupport (= 3.2.13)
railties (= 3.1.12)
railties (3.1.12)
actionpack (= 3.1.12)
activesupport (= 3.1.12)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (>= 0.14.6, < 2.0)
thor (~> 0.14.6)
rake (10.0.4)
rbx-require-relative (0.0.9)
rdoc (3.12.2)
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.3)
sprockets (2.2.2)
sprockets (2.0.4)
hike (~> 1.2)
multi_json (~> 1.0)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sqlite3 (1.3.7)
thor (0.18.1)
thor (0.14.6)
tilt (1.4.0)
treetop (1.4.12)
polyglot
@@ -150,7 +160,8 @@ DEPENDENCIES
omniauth-facebook
omniauth-oauth2 (~> 1.0.0)
omniauth-openid (~> 1.0.1)
rails (~> 3.2.6)
rails (~> 3.1.0)
rdoc
ruby-debug (>= 0.10.3)
sqlite3
webrat (= 0.7.3)

View File

@@ -6,14 +6,12 @@ require 'set'
require 'securerandom'
module Devise
autoload :Delegator, 'devise/delegator'
autoload :FailureApp, 'devise/failure_app'
autoload :OmniAuth, 'devise/omniauth'
autoload :ParameterFilter, 'devise/parameter_filter'
autoload :BaseSanitizer, 'devise/parameter_sanitizer'
autoload :ParameterSanitizer, 'devise/parameter_sanitizer'
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 :TestHelpers, 'devise/test_helpers'
autoload :TimeInflector, 'devise/time_inflector'
module Controllers
autoload :Helpers, 'devise/controllers/helpers'

View File

@@ -80,17 +80,6 @@ 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

@@ -78,14 +78,7 @@ module Devise
def redirect_url
if warden_message == :timeout
flash[:timedout] = true
path = if request.get?
attempted_path
else
request.referrer
end
path || scope_path
attempted_path || scope_path
else
scope_path
end

View File

@@ -2,6 +2,6 @@
# This is only triggered when the user is explicitly set (with set_user)
Warden::Manager.after_set_user :except => :fetch do |record, warden, options|
if record.respond_to?(:failed_attempts) && warden.authenticated?(options[:scope])
record.update_attribute(:failed_attempts, 0) unless record.failed_attempts.zero?
record.update_attribute(:failed_attempts, 0)
end
end

View File

@@ -29,17 +29,17 @@ module Devise
# Receives an object and find a scope for it. If a scope cannot be found,
# raises an error. If a symbol is given, it's considered to be the scope.
def self.find_scope!(obj)
case obj
def self.find_scope!(duck)
case duck
when String, Symbol
return obj
return duck
when Class
Devise.mappings.each_value { |m| return m.name if obj <= m.to }
Devise.mappings.each_value { |m| return m.name if duck <= m.to }
else
Devise.mappings.each_value { |m| return m.name if obj.is_a?(m.to) }
Devise.mappings.each_value { |m| return m.name if duck.is_a?(m.to) }
end
raise "Could not find a valid mapping for #{obj.inspect}"
raise "Could not find a valid mapping for #{duck.inspect}"
end
def self.find_by_path!(path, path_type=:fullpath)

View File

@@ -22,7 +22,7 @@ module Devise
# 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 false.
# * +http_authenticatable+: if this model allows http authentication. By default true.
# It also accepts an array specifying the strategies that should allow http.
#
# * +params_authenticatable+: if this model allows authentication through request params. By default true.
@@ -244,7 +244,7 @@ module Devise
end
def find_first_by_auth_conditions(tainted_conditions, opts={})
to_adapter.find_first(devise_parameter_filter.filter(tainted_conditions).merge(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.
@@ -276,8 +276,8 @@ module Devise
protected
def devise_parameter_filter
@devise_parameter_filter ||= Devise::ParameterFilter.new(case_insensitive_keys, strip_whitespace_keys)
def devise_param_filter
@devise_param_filter ||= Devise::ParamFilter.new(case_insensitive_keys, strip_whitespace_keys)
end
# Generate a token by looping and ensuring does not already exist.

View File

@@ -35,8 +35,8 @@ module Devise
included do
before_create :generate_confirmation_token, :if => :confirmation_required?
after_create :send_on_create_confirmation_instructions, :if => :send_confirmation_notification?
before_update :postpone_email_change_until_confirmation_and_regenerate_confirmation_token, :if => :postpone_email_change?
after_update :send_reconfirmation_instructions, :if => :reconfirmation_required?
before_update :postpone_email_change_until_confirmation, :if => :postpone_email_change?
after_update :send_confirmation_instructions, :if => :reconfirmation_required?
end
def initialize(*args, &block)
@@ -66,7 +66,7 @@ module Devise
self.confirmation_token = nil
self.confirmed_at = Time.now.utc
saved = if self.class.reconfirmable && unconfirmed_email.present?
if self.class.reconfirmable && unconfirmed_email.present?
skip_reconfirmation!
self.email = unconfirmed_email
self.unconfirmed_email = nil
@@ -76,9 +76,6 @@ module Devise
else
save(:validate => false)
end
after_confirmation if saved
saved
end
end
@@ -93,33 +90,22 @@ module Devise
# Send confirmation instructions by email
def send_confirmation_instructions
ensure_confirmation_token!
self.confirmation_token = nil if reconfirmation_required?
@reconfirmation_required = false
generate_confirmation_token! if self.confirmation_token.blank?
opts = pending_reconfirmation? ? { :to => unconfirmed_email } : { }
send_devise_notification(:confirmation_instructions, opts)
end
def send_reconfirmation_instructions
@reconfirmation_required = false
unless @skip_confirmation_notification
send_confirmation_instructions
end
end
# Resend confirmation token.
# Regenerates the token if the period is expired.
# Resend confirmation token. This method does not need to generate a new token.
def resend_confirmation_token
pending_any_confirmation do
regenerate_confirmation_token! if confirmation_period_expired?
self.confirmation_token = nil if confirmation_period_expired?
send_confirmation_instructions
end
end
# Generate a confirmation token unless already exists and save the record.
def ensure_confirmation_token!
generate_confirmation_token! if should_generate_confirmation_token?
end
# Overwrites active_for_authentication? for confirmation
# by verifying whether a user is active to sign in or not. If the user
@@ -140,7 +126,7 @@ module Devise
self.confirmed_at = Time.now.utc
end
# Skips sending the confirmation/reconfirmation notification email after_create/after_update. Unlike
# Skips sending the confirmation notification email after_create. Unlike
# #skip_confirmation!, record still requires confirmation.
def skip_confirmation_notification!
@skip_confirmation_notification = true
@@ -153,9 +139,6 @@ module Devise
end
protected
def should_generate_confirmation_token?
confirmation_token.nil? || confirmation_period_expired?
end
# A callback method used to deliver confirmation
# instructions on creation. This can be overriden
@@ -232,37 +215,24 @@ module Devise
generate_confirmation_token && save(:validate => false)
end
# Regenerates a new token.
def regenerate_confirmation_token
generate_confirmation_token
end
def regenerate_confirmation_token!
regenerate_confirmation_token && save(:validate => false)
end
def postpone_email_change_until_confirmation_and_regenerate_confirmation_token
def postpone_email_change_until_confirmation
@reconfirmation_required = true
self.unconfirmed_email = self.email
self.email = self.email_was
regenerate_confirmation_token
end
def postpone_email_change?
postpone = self.class.reconfirmable && email_changed? && !@bypass_postpone && !self.email.blank?
postpone = self.class.reconfirmable && email_changed? && !@bypass_postpone
@bypass_postpone = false
postpone
end
def reconfirmation_required?
self.class.reconfirmable && @reconfirmation_required && !self.email.blank?
self.class.reconfirmable && @reconfirmation_required
end
def send_confirmation_notification?
confirmation_required? && !@skip_confirmation_notification && !self.email.blank?
end
def after_confirmation
confirmation_required? && !@skip_confirmation_notification
end
module ClassMethods

View File

@@ -81,7 +81,7 @@ module Devise
#
# Example:
#
# def update_without_password(params, *options)
# def update_without_password(params={})
# params.delete(:email)
# super(params)
# end

View File

@@ -55,7 +55,7 @@ module Devise
# Verifies whether a user is locked or not.
def access_locked?
!!locked_at && !lock_expired?
locked_at && !lock_expired?
end
# Send unlock instructions by email
@@ -146,16 +146,16 @@ module Devise
if access_locked?
yield
else
self.errors.add(Devise.unlock_keys.first, :not_locked)
self.errors.add(:email, :not_locked)
false
end
end
module ClassMethods
# Attempt to find a user by its unlock keys. If a record is found, send new
# Attempt to find a user by its email. If a record is found, send new
# unlock instructions to it. If not user is found, returns a new user
# with an email not found error.
# Options must contain the user's unlock keys
# Options must contain the user email
def send_unlock_instructions(attributes={})
lockable = find_or_initialize_with_errors(unlock_keys, attributes, :not_found)
lockable.resend_unlock_token if lockable.persisted?

View File

@@ -44,15 +44,10 @@ module Devise
# Resets reset password token and send reset password instructions by email
def send_reset_password_instructions
ensure_reset_password_token!
generate_reset_password_token! if should_generate_reset_token?
send_devise_notification(:reset_password_instructions)
end
# Generate reset password token unless already exists and save the record.
def ensure_reset_password_token!
generate_reset_password_token! if should_generate_reset_token?
end
# Checks if the reset password token sent is within the limit time.
# We do this by calculating if the difference between today and the
# sending date does not exceed the confirm in time configured.

View File

@@ -50,7 +50,7 @@ module Devise
def remember_me!(extend_period=false)
self.remember_token = self.class.remember_token if generate_remember_token?
self.remember_created_at = Time.now.utc if generate_remember_timestamp?(extend_period)
save(:validate => false) if self.changed?
save(:validate => false)
end
# If the record is persisted, remove the remember token (but only if

View File

@@ -37,7 +37,7 @@ module Devise
private
def remember_exists_and_not_expired?
return false unless respond_to?(:remember_created_at) && respond_to?(:remember_expired?)
return false unless respond_to?(:remember_created_at)
remember_created_at && !remember_expired?
end

View File

@@ -1,5 +1,5 @@
module Devise
class ParameterFilter
class ParamFilter
def initialize(case_insensitive_keys, strip_whitespace_keys)
@case_insensitive_keys = case_insensitive_keys || []
@strip_whitespace_keys = strip_whitespace_keys || []

View File

@@ -1,63 +0,0 @@
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
# These are the params used to sign in a user so we don't need to
# mass-assign the password param in order to authenticate. Excluding it
# here allows us to construct a new user without sensitive information if
# authentication fails.
def sign_in
default_params.permit(*auth_keys + [:password, :remember_me])
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.respond_to?(:keys) ? resource_class.authentication_keys.keys : resource_class.authentication_keys
end
end
end

View File

@@ -1,3 +1,3 @@
module Devise
VERSION = "3.0.4".freeze
VERSION = "2.2.8".freeze
end

View File

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

View File

@@ -2,7 +2,7 @@ module Devise
module Generators
module OrmHelpers
def model_contents
buffer = <<-CONTENT
<<-CONTENT
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
@@ -10,36 +10,16 @@ module Devise
:recoverable, :rememberable, :trackable, :validatable
CONTENT
buffer += <<-CONTENT if needs_attr_accessible?
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
CONTENT
buffer
end
def needs_attr_accessible?
rails_3? && !strong_parameters_enabled?
end
def rails_3?
Rails::VERSION::MAJOR == 3
end
def strong_parameters_enabled?
defined?(ActionController::StrongParameters)
end
private
def model_exists?
File.exists?(File.join(destination_root, model_path))
end
def migration_exists?(table_name)
Dir.glob("#{File.join(destination_root, migration_path)}/[0-9]*_*.rb").grep(/\d+_add_devise_to_#{table_name}.rb$/).first
end
def migration_path
@migration_path ||= File.join("db", "migrate")
end
@@ -49,4 +29,4 @@ CONTENT
end
end
end
end
end

View File

@@ -22,7 +22,7 @@ module Mongoid
## Database authenticatable
field :email, :type => String, :default => ""
field :encrypted_password, :type => String, :default => ""
## Recoverable
field :reset_password_token, :type => String
field :reset_password_sent_at, :type => Time
@@ -54,4 +54,4 @@ RUBY
end
end
end
end
end

View File

@@ -21,7 +21,7 @@ Some setup you must do manually if you haven't yet:
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
4. If you are deploying on Heroku with Rails 3.2 only, you may want to set:
4. If you are deploying Rails 3.1+ on Heroku, you may want to set:
config.assets.initialize_on_precompile = false

View File

@@ -34,20 +34,10 @@ class HelpersTest < ActionController::TestCase
end
test 'get resource params from request params using resource name as key' do
user_params = {'email' => 'shirley@templar.com'}
user_params = {'name' => 'Shirley Templar'}
@controller.stubs(:params).returns(HashWithIndifferentAccess.new({'user' => user_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)
assert_equal user_params, @controller.resource_params
end
test 'resources methods are not controller actions' do

View File

@@ -4,20 +4,6 @@ class SessionsControllerTest < ActionController::TestCase
tests Devise::SessionsController
include Devise::TestHelpers
test "#create doesn't raise unpermitted params when sign in fails" do
ActiveSupport::Notifications.subscribe /unpermitted_parameters/ do |name, start, finish, id, payload|
flunk "Unpermitted params: #{payload}"
end
request.env["devise.mapping"] = Devise.mappings[:user]
request.session["user_return_to"] = 'foo.bar'
user = create_user
post :create, :user => {
:email => "wrong@email.com",
:password => "wrongpassword"
}
assert_equal 200, @response.status
end
test "#create works even with scoped views" do
swap Devise, :scoped_views => true do
request.env["devise.mapping"] = Devise.mappings[:user]

View File

@@ -10,11 +10,13 @@ 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
@@ -62,41 +64,11 @@ if DEVISE_ORM == :active_record
destination File.expand_path("../../tmp", __FILE__)
setup :prepare_destination
test "all files are properly created in rails 4.0" do
ActiveRecord::Generators::DeviseGenerator.any_instance.stubs(:rails_3?).returns(false)
test "all files are properly created" do
simulate_inside_engine(RailsEngine::Engine, RailsEngine) do
run_generator ["monster"]
assert_file "app/models/rails_engine/monster.rb", /devise/
assert_file "app/models/rails_engine/monster.rb" do |content|
assert_no_match /attr_accessible :email/, content
end
end
end
test "all files are properly created in rails 3.2 when strong_parameters gem is not installed" do
ActiveRecord::Generators::DeviseGenerator.any_instance.stubs(:rails_3?).returns(true)
ActiveRecord::Generators::DeviseGenerator.any_instance.stubs(:strong_parameters_enabled?).returns(false)
simulate_inside_engine(RailsEngine::Engine, RailsEngine) do
run_generator ["monster"]
assert_file "app/models/rails_engine/monster.rb", /devise/
assert_file "app/models/rails_engine/monster.rb" do |content|
assert_match /attr_accessible :email/, content
end
end
end
test "all files are properly created in rails 3.2 when strong_parameters gem is installed" do
ActiveRecord::Generators::DeviseGenerator.any_instance.stubs(:rails_3?).returns(true)
ActiveRecord::Generators::DeviseGenerator.any_instance.stubs(:strong_parameters_enabled?).returns(true)
simulate_inside_engine(RailsEngine::Engine, RailsEngine) do
run_generator ["monster"]
assert_file "app/models/rails_engine/monster.rb", /devise/
assert_file "app/models/rails_engine/monster.rb" do |content|
assert_no_match /attr_accessible :email/, content
end
assert_file "app/models/rails_engine/monster.rb", /devise/,/attr_accessible (:[a-z_]+(, )?)+/
end
end
end

View File

@@ -191,7 +191,7 @@ class AuthenticationRoutesRestrictions < ActionDispatch::IntegrationTest
get dashboard_path
assert_response :success
assert_template 'home/admin_dashboard'
assert_template 'home/admin'
assert_contain 'Admin dashboard'
end
@@ -203,7 +203,7 @@ class AuthenticationRoutesRestrictions < ActionDispatch::IntegrationTest
get dashboard_path
assert_response :success
assert_template 'home/user_dashboard'
assert_template 'home/user'
assert_contain 'User dashboard'
end

View File

@@ -153,8 +153,7 @@ class PasswordTest < ActionDispatch::IntegrationTest
assert_response :success
assert_current_url '/users/password'
assert_have_selector '#error_explanation'
assert_contain Devise.rails4? ?
"Password confirmation doesn't match Password" : "Password doesn't match confirmation"
assert_contain 'Password doesn\'t match confirmation'
assert_not user.reload.valid_password?('987654321')
end

View File

@@ -17,7 +17,7 @@ class RegistrationTest < ActionDispatch::IntegrationTest
assert warden.authenticated?(:admin)
assert_current_url "/admin_area/home"
admin = Admin.order(:id).last
admin = Admin.last :order => "id"
assert_equal admin.email, 'new_user@test.com'
end
@@ -56,7 +56,7 @@ class RegistrationTest < ActionDispatch::IntegrationTest
assert_not warden.authenticated?(:user)
user = User.order(:id).last
user = User.last :order => "id"
assert_equal user.email, 'new_user@test.com'
assert_not user.confirmed?
end
@@ -100,8 +100,7 @@ class RegistrationTest < ActionDispatch::IntegrationTest
assert_template 'registrations/new'
assert_have_selector '#error_explanation'
assert_contain "Email is invalid"
assert_contain Devise.rails4? ?
"Password confirmation doesn't match Password" : "Password doesn't match confirmation"
assert_contain "Password doesn't match confirmation"
assert_contain "2 errors prohibited"
assert_nil User.first
@@ -207,8 +206,7 @@ class RegistrationTest < ActionDispatch::IntegrationTest
fill_in 'current password', :with => '12345678'
click_button 'Update'
assert_contain Devise.rails4? ?
"Password confirmation doesn't match Password" : "Password doesn't match confirmation"
assert_contain "Password doesn't match confirmation"
assert_not User.first.valid_password?('pas123')
end
@@ -253,7 +251,7 @@ class RegistrationTest < ActionDispatch::IntegrationTest
assert_response :success
assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<admin>)
admin = Admin.order(:id).last
admin = Admin.last :order => "id"
assert_equal admin.email, 'new_user@test.com'
end
@@ -262,7 +260,7 @@ class RegistrationTest < ActionDispatch::IntegrationTest
assert_response :success
assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<user>)
user = User.order(:id).last
user = User.last :order => "id"
assert_equal user.email, 'new_user@test.com'
end

View File

@@ -48,7 +48,7 @@ class RememberMeTest < ActionDispatch::IntegrationTest
assert request.session[:_csrf_token]
post user_session_path, :authenticity_token => "oops", :user =>
{ email: "jose.valim@gmail.com", password: "123456", :remember_me => "1" }
{ :email => "jose.valim@gmail.com", :password => "123456", :remember_me => "1" }
assert_not warden.authenticated?(:user)
assert_not request.cookies['remember_user_token']
end

View File

@@ -45,16 +45,6 @@ class SessionTimeoutTest < ActionDispatch::IntegrationTest
assert_not warden.authenticated?(:user)
end
test 'time out user session after deault limit time and redirect to latest get request' do
user = sign_in_as_user
visit edit_form_user_path(user)
click_button 'Update'
sign_in_as_user
assert_equal edit_form_user_url(user), current_url
end
test 'time out is not triggered on sign out' do
user = sign_in_as_user
get expire_user_path(user)

View File

@@ -114,14 +114,6 @@ class ConfirmableTest < ActiveSupport::TestCase
end
end
test 'should not send confirmation when no email is provided' do
assert_email_not_sent do
user = new_user
user.email = ''
user.save(:validate => false)
end
end
test 'should find a user to send confirmation instructions' do
user = create_user
confirmation_user = User.send_confirmation_instructions(:email => user.email)
@@ -294,45 +286,6 @@ class ConfirmableTest < ActiveSupport::TestCase
assert_not_equal user.confirmation_token, old
end
end
test 'should generate a new token when a valid one does not exist' do
swap Devise, :confirm_within => 3.days do
user = create_user
user.update_attribute(:confirmation_sent_at, 4.days.ago)
old = user.confirmation_token
user.ensure_confirmation_token!
assert_not_equal user.confirmation_token, old
end
end
test 'should not generate a new token when a valid one exists' do
user = create_user
assert_not_nil user.confirmation_token
old = user.confirmation_token
user.ensure_confirmation_token!
assert_equal user.confirmation_token, old
end
test 'should call after_confirmation if confirmed' do
user = create_user
user.define_singleton_method :after_confirmation do
self.username = self.username.to_s + 'updated'
end
old = user.username
assert user.confirm!
assert_not_equal user.username, old
end
test 'should not call after_confirmation if not confirmed' do
user = create_user
assert user.confirm!
user.define_singleton_method :after_confirmation do
self.username = self.username.to_s + 'updated'
end
old = user.username
assert_not user.confirm!
assert_equal user.username, old
end
end
class ReconfirmableTest < ActiveSupport::TestCase
@@ -358,15 +311,6 @@ class ReconfirmableTest < ActiveSupport::TestCase
assert_nil admin.confirmation_token
end
test 'should skip sending reconfirmation email when email is changed and skip_confirmation_notification! is invoked' do
admin = create_admin
admin.skip_confirmation_notification!
assert_email_not_sent do
admin.update_attributes(:email => 'new_test@example.com')
end
end
test 'should regenerate confirmation token after changing email' do
admin = create_admin
assert admin.confirm!
@@ -393,15 +337,6 @@ class ReconfirmableTest < ActiveSupport::TestCase
end
end
test 'should not send confirmation by email after changing to a blank email' do
admin = create_admin
assert admin.confirm!
assert_email_not_sent do
admin.email = ''
admin.save(:validate => false)
end
end
test 'should stay confirmed when email is changed' do
admin = create_admin
assert admin.confirm!

View File

@@ -48,19 +48,19 @@ class DatabaseAuthenticatableTest < ActiveSupport::TestCase
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 = Devise::ParameterFilter.new([], []).filter(conditions)
conditions = Devise::ParamFilter.new([], []).filter(conditions)
assert_equal( { "login" => "foo@bar.com", "bool1" => "true", "bool2" => "false", "fixnum" => "123", "will_be_converted" => "1..10" }, conditions)
end
test 'param filter should filter case_insensitive_keys as insensitive' do
conditions = {'insensitive' => 'insensitive_VAL', 'sensitive' => 'sensitive_VAL'}
conditions = Devise::ParameterFilter.new(['insensitive'], []).filter(conditions)
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::ParameterFilter.new([], ['strip_whitespace']).filter(conditions)
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
@@ -123,6 +123,13 @@ 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',
@@ -175,6 +182,12 @@ 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')

View File

@@ -185,12 +185,12 @@ class LockableTest < ActiveSupport::TestCase
end
test 'should require all unlock_keys' do
swap Devise, :unlock_keys => [:username, :email] do
user = create_user
unlock_user = User.send_unlock_instructions(:email => user.email)
assert_not unlock_user.persisted?
assert_equal "can't be blank", unlock_user.errors[:username].join
end
swap Devise, :unlock_keys => [:username, :email] do
user = create_user
unlock_user = User.send_unlock_instructions(:email => user.email)
assert_not unlock_user.persisted?
assert_equal "can't be blank", unlock_user.errors[:username].join
end
end
test 'should not be able to send instructions if the user is not locked' do
@@ -200,15 +200,6 @@ class LockableTest < ActiveSupport::TestCase
assert_equal 'was not locked', user.errors[:email].join
end
test 'should not be able to send instructions if the user if not locked and have username as unlock key' do
swap Devise, :unlock_keys => [:username] do
user = create_user
assert_not user.resend_unlock_token
assert_not user.access_locked?
assert_equal 'was not locked', user.errors[:username].join
end
end
test 'should unlock account if lock has expired and increase attempts on failure' do
swap Devise, :unlock_in => 1.minute do
user = create_user

View File

@@ -110,7 +110,7 @@ class RecoverableTest < ActiveSupport::TestCase
test 'should find a user to reset his password based on reset_password_token' do
user = create_user
user.ensure_reset_password_token!
user.send :generate_reset_password_token!
reset_password_user = User.reset_password_by_token(:reset_password_token => user.reset_password_token)
assert_equal reset_password_user, user
@@ -130,7 +130,7 @@ class RecoverableTest < ActiveSupport::TestCase
test 'should return a new record with errors if password is blank' do
user = create_user
user.ensure_reset_password_token!
user.send :generate_reset_password_token!
reset_password_user = User.reset_password_by_token(:reset_password_token => user.reset_password_token, :password => '')
assert_not reset_password_user.errors.empty?
@@ -140,7 +140,7 @@ class RecoverableTest < ActiveSupport::TestCase
test 'should reset successfully user password given the new password and confirmation' do
user = create_user
old_password = user.password
user.ensure_reset_password_token!
user.send :generate_reset_password_token!
User.reset_password_by_token(
:reset_password_token => user.reset_password_token,
@@ -179,7 +179,7 @@ class RecoverableTest < ActiveSupport::TestCase
swap Devise, :reset_password_within => 1.hour do
user = create_user
old_password = user.password
user.ensure_reset_password_token!
user.send :generate_reset_password_token!
user.reset_password_sent_at = 2.days.ago
user.save!
@@ -202,21 +202,4 @@ class RecoverableTest < ActiveSupport::TestCase
:reset_password_token
]
end
test 'should generate a new token when a valid one does not exist' do
user = create_user
assert_nil user.reset_password_token
user.ensure_reset_password_token!
assert_not_nil user.reset_password_token
end
test 'should not generate a new token when a valid one exists' do
user = create_user
user.send :generate_reset_password_token!
assert_not_nil user.reset_password_token
old = user.reset_password_token
user.ensure_reset_password_token!
assert_equal user.reset_password_token, old
end
end

View File

@@ -43,9 +43,4 @@ class TimeoutableTest < ActiveSupport::TestCase
test 'required_fields should contain the fields that Devise uses' do
assert_same_content Devise::Models::Timeoutable.required_fields(User), []
end
test 'should not raise error if remember_created_at is not empty and rememberable is disabled' do
user = create_admin(remember_created_at: Time.current)
assert user.timedout?(31.minutes.ago)
end
end

View File

@@ -56,12 +56,7 @@ 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?
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
assert_equal 'doesn\'t match confirmation', user.errors[:password].join
end
test 'should require password when updating/resetting password' do
@@ -78,12 +73,7 @@ class ValidatableTest < ActiveSupport::TestCase
user = create_user
user.password_confirmation = 'another_password'
assert user.invalid?
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
assert_equal 'doesn\'t match confirmation', user.errors[:password].join
end
test 'should require a password with minimum of 6 characters' do

View File

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

View File

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

@@ -1,58 +0,0 @@
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", "remember_me" => "1" })
assert_equal({ "email" => "jose", "password" => "invalid", "remember_me" => "1" }, sanitizer.for(:sign_in))
end
test 'handles auth keys as a hash' do
swap Devise, :authentication_keys => {:email => true} do
sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid" })
assert_equal({ "email" => "jose", "password" => "invalid" }, sanitizer.for(:sign_in))
end
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,4 +3,8 @@
require File.expand_path('../config/application', __FILE__)
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
Rails.application.load_tasks

View File

@@ -8,14 +8,6 @@ class UsersController < ApplicationController
respond_with(current_user)
end
def edit_form
user_session['last_request_at'] = 31.minutes.ago.utc
end
def update_form
render :text => 'Update'
end
def accept
@current_user = current_user
end

View File

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

View File

@@ -1 +0,0 @@
<%= button_to 'Update', update_form_user_path(current_user), method: 'put' %>

View File

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

View File

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

View File

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

View File

@@ -2,6 +2,7 @@ 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
@@ -16,7 +17,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 mailers views).include?($1) }
config.autoload_paths.reject!{ |p| p =~ /\/app\/(\w+)$/ && !%w(controllers helpers 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
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__)
require 'rubygems'
require 'bundler/setup'
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
$:.unshift File.expand_path('../../../../lib', __FILE__)

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,34 +1,18 @@
RailsApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Settings specified here will take precedence over those in config/environment.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 web server 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 webserver when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# 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,84 +1,33 @@
RailsApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Settings specified here will take precedence over those in config/environment.rb
# Code is not reloaded between requests.
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# 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.
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# 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
# See everything in the log (default is :info)
# config.log_level = :debug
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# 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.
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = false
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# 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.
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# 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
# Enable threaded mode
# config.threadsafe!
end

View File

@@ -1,36 +1,33 @@
RailsApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Settings specified here will take precedence over those in config/environment.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
# 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
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# 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.
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = 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
# 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
# Print deprecation notices to the stderr.
# 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
config.active_support.deprecation = :stderr
end

View File

@@ -1,8 +1,2 @@
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
Rails.application.config.secret_token = 'ea942c41850d502f2c8283e26bdc57829f471bb18224ddff0a192c4f32cdf6cb5aa0d82b3a7a7adbeb640c4b06f3aa1cd5f098162d8240f669b39d6b49680571'
Rails.application.config.session_store :cookie_store, :key => "_my_app"

View File

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

View File

@@ -1,12 +1,8 @@
Rails.application.routes.draw do
# Resources for testing
resources :users, :only => [:index] do
member do
get :expire
get :accept
get :edit_form
put :update_form
end
get :expire, :on => :member
get :accept, :on => :member
authenticate do
post :exhibit, :on => :member
@@ -100,5 +96,5 @@ Rails.application.routes.draw do
get "/unauthenticated", :to => "home#unauthenticated"
get "/custom_strategy/new"
root :to => "home#index", :via => [:get, :post]
root :to => "home#index"
end

View File

@@ -7,6 +7,7 @@ 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

10
test/rails_app/script/rails Executable file
View File

@@ -0,0 +1,10 @@
#!/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,7 +1,5 @@
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})
@@ -103,7 +101,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 ExpectedRoutingError do
assert_raise ActionController::RoutingError do
assert_recognizes({:controller => 'ysers/omniauth_callbacks', :action => 'twitter'}, {:path => 'users/auth/twitter/callback', :method => :get})
end
end
@@ -125,7 +123,7 @@ class CustomizedRoutingTest < ActionController::TestCase
end
test 'does not map admin password' do
assert_raise ExpectedRoutingError do
assert_raise ActionController::RoutingError do
assert_recognizes({:controller => 'devise/passwords', :action => 'new'}, 'admin_area/password/new')
end
end
@@ -135,7 +133,7 @@ class CustomizedRoutingTest < ActionController::TestCase
end
test 'does only map reader password' do
assert_raise ExpectedRoutingError do
assert_raise ActionController::RoutingError do
assert_recognizes({:controller => 'devise/sessions', :action => 'new'}, 'reader/sessions/new')
end
assert_recognizes({:controller => 'devise/passwords', :action => 'new'}, 'reader/password/new')
@@ -163,14 +161,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 ExpectedRoutingError do
assert_raise ActionController::RoutingError 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 ExpectedRoutingError do
assert_raise ActionController::RoutingError do
assert_recognizes({:controller => 'devise/sessions', :action => 'destroy'}, {:path => '/sign_out_via/posts/sign_out', :method => :get})
end
end
@@ -178,56 +176,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 ExpectedRoutingError do
assert_raise ActionController::RoutingError 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 ExpectedRoutingError do
assert_raise ActionController::RoutingError 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 ExpectedRoutingError do
assert_raise ActionController::RoutingError 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 ExpectedRoutingError do
assert_raise ActionController::RoutingError 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 ExpectedRoutingError do
assert_raise ActionController::RoutingError 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 ExpectedRoutingError do
assert_raise ActionController::RoutingError 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 ExpectedRoutingError do
assert_raise ActionController::RoutingError 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 ExpectedRoutingError do
assert_raise ActionController::RoutingError do
assert_recognizes({:controller => 'devise/unlocks', :action => 'show'}, {:path => '/htmlonly_users/unlock.xml', :method => :get})
end
end

View File

@@ -63,7 +63,7 @@ class ActiveSupport::TestCase
def clear_cached_variables(options)
if options.key?(:case_insensitive_keys) || options.key?(:strip_whitespace_keys)
Devise.mappings.each do |_, mapping|
mapping.to.instance_variable_set(:@devise_parameter_filter, nil)
mapping.to.instance_variable_set(:@devise_param_filter, nil)
end
end
end

View File

@@ -4,13 +4,6 @@ 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}"

View File

@@ -15,6 +15,7 @@ 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