[DRE-commits] [ruby-devise] 01/01: Imported Upstream version 3.4.0

Antonio Terceiro terceiro at moszumanska.debian.org
Wed Nov 11 17:47:25 UTC 2015


This is an automated email from the git hooks/post-receive script.

terceiro pushed a commit to annotated tag upstream/3.4.0
in repository ruby-devise.

commit a8578bf9bc2ac1fb77ee8c3c74cc8b2c9bbaf9f9
Author: Nitesh A Jain <niteshjain92 at gmail.com>
Date:   Tue Nov 18 01:01:05 2014 +0530

    Imported Upstream version 3.4.0
---
 .gitignore                                         |   10 +
 .travis.yml                                        |   35 +
 .yardopts                                          |    9 +
 CHANGELOG.md                                       | 1103 ++++++++++++++++++++
 CONTRIBUTING.md                                    |   14 +
 Gemfile                                            |   29 +
 Gemfile.lock                                       |  192 ++++
 MIT-LICENSE                                        |   20 +
 README.md                                          |  529 ++++++++++
 Rakefile                                           |   35 +
 app/controllers/devise/confirmations_controller.rb |   47 +
 .../devise/omniauth_callbacks_controller.rb        |   30 +
 app/controllers/devise/passwords_controller.rb     |   70 ++
 app/controllers/devise/registrations_controller.rb |  148 +++
 app/controllers/devise/sessions_controller.rb      |   76 ++
 app/controllers/devise/unlocks_controller.rb       |   46 +
 app/controllers/devise_controller.rb               |  176 ++++
 app/helpers/devise_helper.rb                       |   25 +
 app/mailers/devise/mailer.rb                       |   20 +
 app/views/devise/confirmations/new.html.erb        |   12 +
 .../mailer/confirmation_instructions.html.erb      |    5 +
 .../mailer/reset_password_instructions.html.erb    |    8 +
 .../devise/mailer/unlock_instructions.html.erb     |    7 +
 app/views/devise/passwords/edit.html.erb           |   16 +
 app/views/devise/passwords/new.html.erb            |   12 +
 app/views/devise/registrations/edit.html.erb       |   29 +
 app/views/devise/registrations/new.html.erb        |   18 +
 app/views/devise/sessions/new.html.erb             |   17 +
 app/views/devise/shared/_links.html.erb            |   25 +
 app/views/devise/unlocks/new.html.erb              |   12 +
 config/locales/en.yml                              |   60 ++
 devise.gemspec                                     |   28 +
 devise.png                                         |  Bin 0 -> 13322 bytes
 gemfiles/Gemfile.rails-3.2-stable                  |   29 +
 gemfiles/Gemfile.rails-3.2-stable.lock             |  169 +++
 gemfiles/Gemfile.rails-4.0-stable                  |   29 +
 gemfiles/Gemfile.rails-4.0-stable.lock             |  165 +++
 gemfiles/Gemfile.rails-4.1-stable                  |   29 +
 gemfiles/Gemfile.rails-4.1-stable.lock             |  170 +++
 lib/devise.rb                                      |  496 +++++++++
 lib/devise/controllers/helpers.rb                  |  284 +++++
 lib/devise/controllers/rememberable.rb             |   47 +
 lib/devise/controllers/scoped_views.rb             |   17 +
 lib/devise/controllers/sign_in_out.rb              |  102 ++
 lib/devise/controllers/store_location.rb           |   56 +
 lib/devise/controllers/url_helpers.rb              |   69 ++
 lib/devise/delegator.rb                            |   16 +
 lib/devise/failure_app.rb                          |  210 ++++
 lib/devise/hooks/activatable.rb                    |   10 +
 lib/devise/hooks/csrf_cleaner.rb                   |    7 +
 lib/devise/hooks/forgetable.rb                     |    9 +
 lib/devise/hooks/lockable.rb                       |    7 +
 lib/devise/hooks/proxy.rb                          |   21 +
 lib/devise/hooks/rememberable.rb                   |    7 +
 lib/devise/hooks/timeoutable.rb                    |   35 +
 lib/devise/hooks/trackable.rb                      |    9 +
 lib/devise/mailers/helpers.rb                      |   90 ++
 lib/devise/mapping.rb                              |  175 ++++
 lib/devise/models.rb                               |  119 +++
 lib/devise/models/authenticatable.rb               |  290 +++++
 lib/devise/models/confirmable.rb                   |  295 ++++++
 lib/devise/models/database_authenticatable.rb      |  164 +++
 lib/devise/models/lockable.rb                      |  196 ++++
 lib/devise/models/omniauthable.rb                  |   27 +
 lib/devise/models/recoverable.rb                   |  147 +++
 lib/devise/models/registerable.rb                  |   25 +
 lib/devise/models/rememberable.rb                  |  129 +++
 lib/devise/models/timeoutable.rb                   |   49 +
 lib/devise/models/trackable.rb                     |   38 +
 lib/devise/models/validatable.rb                   |   66 ++
 lib/devise/modules.rb                              |   28 +
 lib/devise/omniauth.rb                             |   28 +
 lib/devise/omniauth/config.rb                      |   45 +
 lib/devise/omniauth/url_helpers.rb                 |   18 +
 lib/devise/orm/active_record.rb                    |    3 +
 lib/devise/orm/mongoid.rb                          |    3 +
 lib/devise/parameter_filter.rb                     |   40 +
 lib/devise/parameter_sanitizer.rb                  |   99 ++
 lib/devise/rails.rb                                |   56 +
 lib/devise/rails/routes.rb                         |  495 +++++++++
 lib/devise/rails/warden_compat.rb                  |   22 +
 lib/devise/strategies/authenticatable.rb           |  173 +++
 lib/devise/strategies/base.rb                      |   20 +
 lib/devise/strategies/database_authenticatable.rb  |   24 +
 lib/devise/strategies/rememberable.rb              |   58 +
 lib/devise/test_helpers.rb                         |  132 +++
 lib/devise/time_inflector.rb                       |   14 +
 lib/devise/token_generator.rb                      |   70 ++
 lib/devise/version.rb                              |    3 +
 lib/generators/active_record/devise_generator.rb   |   91 ++
 .../active_record/templates/migration.rb           |   18 +
 .../active_record/templates/migration_existing.rb  |   25 +
 lib/generators/devise/controllers_generator.rb     |   44 +
 lib/generators/devise/devise_generator.rb          |   26 +
 lib/generators/devise/install_generator.rb         |   29 +
 lib/generators/devise/orm_helpers.rb               |   51 +
 lib/generators/devise/views_generator.rb           |  135 +++
 lib/generators/mongoid/devise_generator.rb         |   55 +
 lib/generators/templates/README                    |   35 +
 lib/generators/templates/controllers/README        |   14 +
 .../controllers/confirmations_controller.rb        |   28 +
 .../controllers/omniauth_callbacks_controller.rb   |   28 +
 .../templates/controllers/passwords_controller.rb  |   32 +
 .../controllers/registrations_controller.rb        |   60 ++
 .../templates/controllers/sessions_controller.rb   |   25 +
 .../templates/controllers/unlocks_controller.rb    |   28 +
 lib/generators/templates/devise.rb                 |  263 +++++
 .../markerb/confirmation_instructions.markerb      |    5 +
 .../markerb/reset_password_instructions.markerb    |    8 +
 .../templates/markerb/unlock_instructions.markerb  |    7 +
 .../simple_form_for/confirmations/new.html.erb     |   16 +
 .../simple_form_for/passwords/edit.html.erb        |   19 +
 .../simple_form_for/passwords/new.html.erb         |   15 +
 .../simple_form_for/registrations/edit.html.erb    |   27 +
 .../simple_form_for/registrations/new.html.erb     |   17 +
 .../simple_form_for/sessions/new.html.erb          |   15 +
 .../templates/simple_form_for/unlocks/new.html.erb |   16 +
 metadata.yml                                       |  501 +++++++++
 script/cached-bundle                               |   49 +
 script/s3-put                                      |   71 ++
 .../custom_registrations_controller_test.rb        |   35 +
 test/controllers/custom_strategy_test.rb           |   62 ++
 test/controllers/helpers_test.rb                   |  311 ++++++
 test/controllers/internal_helpers_test.rb          |  123 +++
 test/controllers/passwords_controller_test.rb      |   31 +
 test/controllers/sessions_controller_test.rb       |  103 ++
 test/controllers/url_helpers_test.rb               |   65 ++
 test/delegator_test.rb                             |   19 +
 test/devise_test.rb                                |  107 ++
 test/failure_app_test.rb                           |  268 +++++
 test/generators/active_record_generator_test.rb    |  109 ++
 test/generators/controllers_generator_test.rb      |   48 +
 test/generators/devise_generator_test.rb           |   39 +
 test/generators/install_generator_test.rb          |   13 +
 test/generators/mongoid_generator_test.rb          |   23 +
 test/generators/views_generator_test.rb            |   96 ++
 test/helpers/devise_helper_test.rb                 |   49 +
 test/integration/authenticatable_test.rb           |  729 +++++++++++++
 test/integration/confirmable_test.rb               |  324 ++++++
 test/integration/database_authenticatable_test.rb  |   84 ++
 test/integration/http_authenticatable_test.rb      |  105 ++
 test/integration/lockable_test.rb                  |  239 +++++
 test/integration/omniauthable_test.rb              |  133 +++
 test/integration/recoverable_test.rb               |  334 ++++++
 test/integration/registerable_test.rb              |  359 +++++++
 test/integration/rememberable_test.rb              |  167 +++
 test/integration/timeoutable_test.rb               |  189 ++++
 test/integration/trackable_test.rb                 |   92 ++
 test/mailers/confirmation_instructions_test.rb     |  115 ++
 test/mailers/reset_password_instructions_test.rb   |   96 ++
 test/mailers/unlock_instructions_test.rb           |   91 ++
 test/mapping_test.rb                               |  128 +++
 test/models/authenticatable_test.rb                |   23 +
 test/models/confirmable_test.rb                    |  455 ++++++++
 test/models/database_authenticatable_test.rb       |  249 +++++
 test/models/lockable_test.rb                       |  328 ++++++
 test/models/omniauthable_test.rb                   |    7 +
 test/models/recoverable_test.rb                    |  196 ++++
 test/models/registerable_test.rb                   |    7 +
 test/models/rememberable_test.rb                   |  198 ++++
 test/models/serializable_test.rb                   |   49 +
 test/models/timeoutable_test.rb                    |   51 +
 test/models/trackable_test.rb                      |   41 +
 test/models/validatable_test.rb                    |  127 +++
 test/models_test.rb                                |  144 +++
 test/omniauth/config_test.rb                       |   57 +
 test/omniauth/url_helpers_test.rb                  |   54 +
 test/orm/active_record.rb                          |   10 +
 test/orm/mongoid.rb                                |   13 +
 test/parameter_sanitizer_test.rb                   |   81 ++
 test/rails_app/Rakefile                            |    6 +
 test/rails_app/app/active_record/admin.rb          |    6 +
 test/rails_app/app/active_record/shim.rb           |    2 +
 test/rails_app/app/active_record/user.rb           |    6 +
 test/rails_app/app/active_record/user_on_engine.rb |    7 +
 .../app/active_record/user_on_main_app.rb          |    7 +
 .../app/controllers/admins/sessions_controller.rb  |    6 +
 .../rails_app/app/controllers/admins_controller.rb |   11 +
 .../app/controllers/application_controller.rb      |   12 +
 .../controllers/application_with_fake_engine.rb    |   30 +
 .../controllers/custom/registrations_controller.rb |   21 +
 test/rails_app/app/controllers/home_controller.rb  |   25 +
 .../publisher/registrations_controller.rb          |    2 +
 .../controllers/publisher/sessions_controller.rb   |    2 +
 .../users/omniauth_callbacks_controller.rb         |   14 +
 test/rails_app/app/controllers/users_controller.rb |   31 +
 test/rails_app/app/helpers/application_helper.rb   |    3 +
 .../app/mailers/users/from_proc_mailer.rb          |    3 +
 test/rails_app/app/mailers/users/mailer.rb         |    3 +
 .../rails_app/app/mailers/users/reply_to_mailer.rb |    4 +
 test/rails_app/app/mongoid/admin.rb                |   29 +
 test/rails_app/app/mongoid/shim.rb                 |   23 +
 test/rails_app/app/mongoid/user.rb                 |   39 +
 test/rails_app/app/mongoid/user_on_engine.rb       |   39 +
 test/rails_app/app/mongoid/user_on_main_app.rb     |   39 +
 test/rails_app/app/views/admins/index.html.erb     |    1 +
 .../app/views/admins/sessions/new.html.erb         |    2 +
 .../app/views/home/admin_dashboard.html.erb        |    1 +
 test/rails_app/app/views/home/index.html.erb       |    1 +
 test/rails_app/app/views/home/join.html.erb        |    1 +
 test/rails_app/app/views/home/private.html.erb     |    1 +
 .../app/views/home/user_dashboard.html.erb         |    1 +
 .../app/views/layouts/application.html.erb         |   24 +
 test/rails_app/app/views/users/edit_form.html.erb  |    1 +
 test/rails_app/app/views/users/index.html.erb      |    1 +
 .../users/mailer/confirmation_instructions.erb     |    1 +
 .../app/views/users/sessions/new.html.erb          |    1 +
 test/rails_app/bin/bundle                          |    3 +
 test/rails_app/bin/rails                           |    4 +
 test/rails_app/bin/rake                            |    4 +
 test/rails_app/config.ru                           |    4 +
 test/rails_app/config/application.rb               |   40 +
 test/rails_app/config/boot.rb                      |   14 +
 test/rails_app/config/database.yml                 |   18 +
 test/rails_app/config/environment.rb               |    5 +
 test/rails_app/config/environments/development.rb  |   30 +
 test/rails_app/config/environments/production.rb   |   80 ++
 test/rails_app/config/environments/test.rb         |   36 +
 .../config/initializers/backtrace_silencers.rb     |    7 +
 test/rails_app/config/initializers/devise.rb       |  183 ++++
 test/rails_app/config/initializers/inflections.rb  |    2 +
 test/rails_app/config/initializers/secret_token.rb |    8 +
 .../rails_app/config/initializers/session_store.rb |    1 +
 test/rails_app/config/routes.rb                    |  122 +++
 .../db/migrate/20100401102949_create_tables.rb     |   71 ++
 test/rails_app/db/schema.rb                        |   55 +
 test/rails_app/lib/shared_admin.rb                 |   17 +
 test/rails_app/lib/shared_user.rb                  |   29 +
 test/rails_app/lib/shared_user_without_omniauth.rb |   13 +
 test/rails_app/public/404.html                     |   26 +
 test/rails_app/public/422.html                     |   26 +
 test/rails_app/public/500.html                     |   26 +
 test/rails_app/public/favicon.ico                  |    0
 test/routes_test.rb                                |  264 +++++
 .../support/action_controller/record_identifier.rb |   10 +
 test/support/assertions.rb                         |   39 +
 test/support/helpers.rb                            |   73 ++
 test/support/integration.rb                        |   92 ++
 test/support/locale/en.yml                         |    8 +
 test/support/mongoid.yml                           |    6 +
 test/support/webrat/integrations/rails.rb          |   24 +
 test/test_helper.rb                                |   34 +
 test/test_helpers_test.rb                          |  163 +++
 test/test_models.rb                                |   33 +
 244 files changed, 18502 insertions(+)

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0ff7742
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,10 @@
+test/rails_app/log/*
+test/rails_app/tmp/*
+*~
+coverage/*
+*.sqlite3
+.bundle
+rdoc/*
+pkg
+log
+test/tmp/*
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..278b10c
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,35 @@
+language: ruby
+script: "bundle exec rake test"
+install: script/cached-bundle install --deployment --path vendor/bundle
+rvm:
+  - 1.9.3
+  - 2.0.0
+  - 2.1.2
+env:
+  matrix:
+    - DEVISE_ORM=mongoid
+    - DEVISE_ORM=active_record
+  global:
+    # AMAZON_S3_BUCKET
+    - secure: "qkeYGn2mpgsgU5tKS9GWvFp/utUF/9O8++Shch24DMnq8OB01TrV5QQ2Elj7sSjMWqw2Pbe56nUCA9eOWXhPglGyIq2AI9E0umsEGZxdRlqqobpiMWs5wl8KZ0cFD1rZm6CwfL8atmcNfTt5TnvsaQ2l/k3TerOT2e66R/Mibk8="
+    # AMAZON_ACCESS_KEY_ID
+    - secure: "rTYGUFH9SPN0L7QtdE6Liyy/1z7nGKxqDF9LMRsmNsIfsqxoTPKZ8bCctQ4ksuk9svynGQsLfsda5pA+YvuALzjdWmGcID6ENgOGvoFnhZO5LuJ5f6t0k8gFpV9oBquQgDWzhzrcPYvCUrUYg3GSlHjFSXdPdht3SoYn7PiDaNs="
+    # AMAZON_SECRET_ACCESS_KEY
+    - secure: "VJ4qiWMzoleLojCcluX+w0RtaFVc9ybRNo6NODkGhHSaao8+4EX4rETBQG67tNSInk1iuNqCcZAGwC8V/12RXdao3PguRSLD5IiKeT+D78dqFEoP0+yHg4PbmZ6TJXADW3gUv/IOqkW7f/UYGinRaPu7hloyiC498FpQdmMWSNI="
+gemfile:
+  - gemfiles/Gemfile.rails-4.1-stable
+  - gemfiles/Gemfile.rails-4.0-stable
+  - gemfiles/Gemfile.rails-3.2-stable
+  - Gemfile
+matrix:
+  allow_failures:
+    - gemfile: gemfiles/Gemfile.rails-head
+services:
+  - mongodb
+notifications:
+  email: false
+  campfire:
+    on_success: change
+    on_failure: always
+    rooms:
+      - secure: "TRiqvuM4i/QmRDWjUSNitE5/P91BOzDkNl53+bZjjtxcISCswZtmECWBR7n9\n3xwqCOU1o2lfohxZ32OHOj/Nj7o+90zWJfWxcv+if0hIXRiil62M5pg0lZUd\nyJ4M5VQ0lSWo5he1OUrXhSabPJeaK3B8yT/tdh+qO5yzR+vb/jc="
diff --git a/.yardopts b/.yardopts
new file mode 100644
index 0000000..55bb0d4
--- /dev/null
+++ b/.yardopts
@@ -0,0 +1,9 @@
+--protected
+--no-private
+--embed-mixin ClassMethods
+-
+README.md
+CHANGELOG.rdoc
+CONTRIBUTING.md
+MIT-LICENSE
+
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..9f25131
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,1103 @@
+### Unreleased
+
+* enhancements
+* bugfixes
+
+### 3.4.0
+
+* enhancements
+  * Support added for Rails 4.2. Devise now depends on the `responders` gem due
+    the extraction of the `respond_with` API from Rails. (by @lucasmazza)
+  * The Simple Form templates follow the same change from 3.3.0 by using `Log in` and adding
+    a hint about the minimum password length when `validatable` is enabled. (by @aried3r)
+  * Remove reloading of routes when eager loading is enabled. This change was added during Rails 3 and it doesn't seem to be relevant to currently supported Rails versions (by @fgro)
+  * Controller generator added as `devise:controllers SCOPE`. You can use the `-c` flag
+    to pick which controllers (`unlocks`, `confirmations`, etc) you want to generate. (by @Chun-Yang)
+  * Removed the hardcoded references for "email" in the flash messages. If you are using
+    different attributes as the `authentication_keys` they will be interpolated in the
+    messages instead. (by @timoschilling)
+* bug fix
+  * Fixed a regression where the devise generator would fail with a `ConnectionNotEstablished`
+    exception when executed inside a mountable engine. (by @lucasmazza)
+  * Ensure to return symbols in find_scope! fixing a previous regression from 3.3.0 (by @micat)
+  * Ensure all causes of failed login have the same error message (by @pjungwir)
+  * The `last_attempt_warning` now takes effect when generating the unauthenticated
+    message for your users. To keep the current behavior, this flag is now `true`
+    by default. (by @lucasmazza)
+
+### 3.3.0
+
+* enhancements
+  * Support multiple warden configuration blocks on devise configuration. (by @rossta)
+  * Previously, when a user signed out, all remember me tokens for all sessions/browsers would be
+    invalidated, and this behavior could not be changed. This behavior is now configurable via
+    `expire_all_remember_me_on_sign_out`. The default continues to be true. (by @laurocaetano)
+  * Default email messages was updated with grammar fixes, check the diff on
+    #2906 for the updated copy (by @p-originate)
+  * Allow a resource to be found based on its encrypted password token (by @karlentwistle)
+  * Adds `devise_group`, a macro to define controller helpers for multiple mappings at once. (by @dropletzz)
+  * The default views now use `Log in` instead of `Sign in` and have a hint about the minimum password length if
+    the current scope is using the `validatable` module (by @alexsoble)
+
+* bug fix
+  * Check if there is a signed in user before executing the `SessionsController#destroy`.
+  * `SessionsController#destroy` no longer yields the `resource` to receiving block,
+    since the resource isn't loaded in the action. If you need access to the current
+    resource when overring the action use the scope helper (like `current_user`) before
+    calling `super`
+  * Serialize the `last_request_at` entry as an Integer
+  * Ensure registration controller block yields happen on failure in addition to success (by @dpehrson)
+  * Only valid paths will be stored for redirections (by @parallel588)
+
+### 3.2.4
+
+* enhancements
+  * `bcrypt` dependency updated due https://github.com/codahale/bcrypt-ruby/pull/86.
+  * View generator now can generate specific views with the `-v` flag, like `rails g devise:views -v sessions` (by @kayline)
+
+### 3.2.3
+
+* enhancements
+  * Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key`.
+    You can change this and use your own secret by changing the `devise.rb` initializer.
+
+* bug fix
+  * Migrations will be properly generated when using rails 4.1.0.
+
+### 3.2.2
+
+* bug fix
+  * Ensure timeoutable works when `sign_out_all_scopes` is false (by @louman)
+  * Keep the query string when storing location (by @csexton)
+  * Require rails generator base class in devise generators
+
+### 3.2.1
+
+Security announcement: http://blog.plataformatec.com.br/2013/11/e-mail-enumeration-in-devise-in-paranoid-mode
+
+* enhancements
+  * Add `store_location_for` helper and ensure it is safe (by @matthewrudy and @homakov)
+  * Add `yield` around resource methods in Devise controllers (by @edelpero)
+
+* bug fix
+  * Bring `password_digest` back to fix compatibility with `devise-encryptable`
+  * Avoid e-mail enumeration on sign in when in paranoid mode
+
+### 3.2.0
+
+* enhancements
+  * Previously deprecated token authenticatable and insecure lookups have been removed
+  * Add a class method so you can encrypt passwords from fixtures (by @tenderlove)
+  * Send custom message when user enters invalid password and it has only one attempt
+  to enter correct password before their account will be locked (by @Lightpower)
+  * Prevent mutation of values assigned to case and whitespace santitized members (by @iamvery)
+  * Separate redirects and flash messages in `navigational_formats` and `flashing_formats` (by @ssendev)
+
+* bug fix
+  * A GET to sign_in page shouldn't extend the session (by @drewish)
+  * Splat the arguments to `strong_parameters#permit` to work around a limitation in the `strong_parameters` gem (by @memberful)
+  * Omniauth now uses `mapping.fullpath` when generating routes. This means if you call `devise_for :users` inside a scope, like `scope "/api"`, the scope will now apply to the omniauth route (by @AlexanderZaytsev)
+  * Ensure timeoutable hook respects `Devise.sign_out_all_scopes` configuration
+
+* deprecations
+  * `expire_session_data_after_sign_in!` has been deprecated in favor of `expire_data_after_sign_in!`
+
+### 3.1.1
+
+* bug fix
+  * Improve default message which asked users to sign in even when they were already signed (by @gregates)
+  * Improve error message for when the config.secret_key is missing
+
+### 3.1.0
+
+Security announcement: http://blog.plataformatec.com.br/2013/08/devise-3-1-now-with-more-secure-defaults/
+
+* backwards incompatible changes
+  * Do not store confirmation, unlock and reset password tokens directly in the database. This means tokens previously stored in the database are no longer valid. You can reenable this temporarily by setting `config.allow_insecure_token_lookup = true` in your configuration file. It is recommended to keep this configuration set to true just temporarily in your production servers only to aid migration
+  * The Devise mailer and its views were changed to explicitly receive a token argument as `@token`. You will need to update your mailers and re-copy the views to your application with `rails g devise:views`
+  * Sanitization of parameters should be done by calling `devise_parameter_sanitizer.sanitize(:action)` instead of `devise_parameter_sanitizer.for(:action)`
+
+* deprecations
+  * Token authentication is deprecated
+
+* enhancements
+  * Better security defaults
+  * Allow easier customization of parameter sanitizer (by @alexpeattie)
+
+* bug fix
+  * Do not confirm e-mail after password reset (by @moll)
+  * Do not sign in after confirmation
+  * Do not store confirmation, unlock and reset password tokens directly in the database
+  * Do not compare directly against confirmation, unlock and reset password tokens
+  * Skip storage for cookies on unverified requests
+
+### 3.0.2
+
+* 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
+
+* 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
+  * 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)
+
+* backwards incompatible changes
+  * Changes on session storage will expire all existing sessions on upgrade. For those storing the session in the DB, they can be upgraded according to this gist: https://gist.github.com/moll/6417606
+
+### 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
+  * Fix bug when checking for reconfirmable in templates
+
+### 2.2.1
+
+* bug fix
+  * Fix regression with case_insensitive_keys
+  * Fix regression when password is blank when it is invalid
+
+### 2.2.0
+
+* backwards incompatible changes
+  * `headers_for` is deprecated, customize the mailer directly instead
+  * All mailer methods now expect a second argument with delivery options
+  * Default minimum password length is now 8 (by @carlosgaldino)
+  * Support alternate sign in error message when email record does not exist (this adds a new I18n key to the locale file) (by @gabetax)
+  * DeviseController responds only to HTML requests by default (call `DeviseController.respond_to` or `ApplicationController.respond_to` to add new formats)
+  * Support Mongoid 3 onwards (by @durran)
+
+* enhancements
+  * Fix unlockable which could leak account existence on paranoid mode (by @latortuga)
+  * Confirmable now has a confirm_within option to set a period while the confirmation token is still valid (by @promisedlandt)
+  * Flash messages in controller now respects `resource_name` (by @latortuga)
+  * Separate `sign_in` and `sign_up` on RegistrationsController (by @rubynortheast)
+  * Add autofocus to default views (by @Radagaisus)
+  * Unlock user on password reset (by @marcinb)
+  * Allow validation callbacks to apply to virtual attributes (by @latortuga)
+
+* bug fix
+  * unconfirmed_email now uses the proper e-mail on salutation
+  * Fix default email_regexp config to not allow spaces (by @kukula)
+  * Fix a regression introduced on warden 1.2.1 (by @ejfinneran)
+  * Properly camelize omniauth strategies (by @saizai)
+  * Do not set flash messages for non navigational requests on session sign out (by @mathieul)
+  * Set the proper fields as required on the lockable module (by @nickhoffman)
+  * Respects Devise mailer default's reply_to (by @mrchrisadams)
+  * Properly assign resource on `sign_in` related action (by @adammcnamara)
+  * `update_with_password` doesn't change encrypted password when it is invalid (by @nashby)
+  * Properly handle namespaced models on Active Record generator (by @nashby)
+
+### 2.1.4
+
+* bugfix
+  * Do not confirm account after reset password
+
+### 2.1.3
+
+* bugfix
+  * Require string conversion for all values
+
+### 2.1.2
+
+* enhancements
+  * Handle backwards incompatibility between Rails 3.2.6 and Thor 0.15.x
+
+* bug fix
+  * Fix regression on strategy validation on previous release
+
+### 2.1.1 (yanked)
+
+* enhancements
+  * `sign_out_all_scopes` now locks warden and does not allow new logins in the same action
+  * `Devise.omniauth_path_prefix` is available to configure omniauth path prefix
+  * Redirect to sign in page when trying to access password#edit without a token (by @gbataille)
+  * Allow a lambda in authenticate(d) routes helpers to further select the scope
+  * Removed warnings on Rails 3.2.6 (by @nashby)
+
+* bug fix
+  * `update_with_password` now relies on assign_attributes and forwards the :as option (by @wtn)
+  * Do not trigger timeout on sign in related actions
+  * Timeout does not explode when reset_authentication_token! is accidentally defined by Active Model (by @remomueller)
+
+* deprecations
+  * Strategy#validate() no longer validates nil resources
+
+### 2.1.0
+
+* enhancements
+  * Add `check_fields!(model_class)` method on Devise::Models to check if the model includes the fields that Devise uses
+  * Add `skip_reconfirmation!` to skip reconfirmation
+  * Devise model generator now works with engines
+  * Devise encryptable was moved to its new gem (http://github.com/plataformatec/devise-encryptable)
+
+* deprecations
+  * Deprecations warnings added on Devise 2.0 are now removed with their features
+  * All devise modules should now have a `required_fields(klass)` module method to help gathering missing attributes
+  * `use_salt_as_remember_token` and `apply_schema` does not have any effect since 2.0 and are now deprecated
+  * `valid_for_authentication?` must now return a boolean
+
+* bug fix
+  * Ensure after sign in hook is not called without a resource
+  * Fix a term: now on Omniauth related flash messages, we say that we're authenticating from an omniauth provider instead of authorizing
+  * Fixed redirect when authenticated mounted apps (by @hakanensari)
+  * Ensure the failure app still respects config.relative_url_root
+  * `/users/sign_in` doesn't choke on protected attributes used to select sign in scope (by @Paymium)
+  * `failed_attempts` is set to zero after any sign in (including via reset password) (by @rodrigoflores)
+  * Added token expiration on timeout (by @antiarchitect)
+  * 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
+
+Notes: https://github.com/plataformatec/devise/wiki/How-To:-Upgrade-to-Devise-2.0
+
+* bug fix
+  * Fix when :host is used with devise_for  (by @mreinsch)
+  * Fix a regression that caused Warden to be initialized too late
+
+### 2.0.3 (yanked)
+
+* bug fix
+  * Ensure warning is not shown by mistake on apps with mounted engines
+  * Fixes related to remember_token and rememberable_options
+  * Ensure serializable_hash does not depend on accessible attributes
+  * Ensure that timeout callback does not run on sign out action
+
+### 2.0.2
+
+* enhancements
+  * Add devise_i18n_options to customize I18n message
+
+* bug fix
+  * Ensure Devise.available_router_name defaults to :main_app
+  * Set autocomplete to off for password on edit forms
+  * Better error messages in case a trackable model can't be saved
+  * Show a warning in case someone gives a pluralized name to devise generator
+  * Fix test behavior for rspec subject requests (by @sj26)
+
+### 2.0.1
+
+* enhancements
+  * Improved error messages on deprecation warnings
+  * Hide Devise's internal generators from `rails g` command
+
+* bug fix
+  * Removed tmp and log files from gem
+
+### 2.0.0
+
+* enhancements
+  * Add support for e-mail reconfirmation on change (by @Mandaryn and @heimidal)
+  * Redirect users to sign in page after unlock (by @nashby)
+  * Redirect to the previous URL on timeout
+  * Inherit from the same Devise parent controller (by @sj26)
+  * Allow parent_controller to be customizable via Devise.parent_controller, useful for engines
+  * Allow router_name to be customizable via Devise.router_name, useful for engines
+  * Allow alternate ORMs to run compatibility setup code before Authenticatable is included (by @jm81)
+
+* deprecation
+  * Devise now only supports Rails 3.1 forward
+  * Devise.confirm_within was deprecated in favor Devise.allow_unconfirmed_access_for
+  * Devise.stateless_token= is deprecated in favor of appending :token_auth to Devise.skip_session_storage
+  * Usage of Devise.apply_schema is deprecated
+  * Usage of Devise migration helpers are deprecated
+  * Usage of Devise.remember_across_browsers was deprecated
+  * Usage of rememberable with remember_token was removed
+  * Usage of recoverable without reset_password_sent_at was removed
+  * Usage of Devise.case_insensitive_keys equals to false was removed
+  * Move devise/shared/_links.erb to devise/_links.erb
+  * Deprecated support of nested devise_for blocks
+  * Deprecated support to devise.registrations.reasons and devise.registrations.inactive_signed_up in favor of devise.registrations.signed_up_but_*
+  * Protected method render_with_scope was removed.
+
+### 1.5.3
+
+* bug fix
+  * Ensure delegator converts scope to symbol (by @dmitriy-kiriyenko)
+  * Ensure passing :format => false to devise_for is not permanent
+  * Ensure path checker does not check invalid routes
+
+### 1.5.2
+
+* enhancements
+  * Add support for Rails 3.1 new mass assignment conventions (by @kirs)
+  * Add timeout_in method to Timeoutable, it can be overridden in a model (by @lest)
+
+* bug fix
+  * OmniAuth error message now shows the proper option (:strategy_class instead of :klass)
+
+### 1.5.1
+
+* bug fix
+  * Devise should not attempt to load OmniAuth strategies. Strategies should be loaded before hand by the developer or explicitly given to Devise.
+
+### 1.5.0
+
+* enhancements
+  * Timeoutable also skips tracking if skip_trackable is given
+  * devise_for now accepts :failure_app as an option
+  * Models can select the proper mailer via devise_mailer method (by @locomotivecms)
+  * Migration generator now uses the change method (by @nashby)
+  * Support to markerb templates on the mailer generator (by @sbounmy)
+  * Support for Omniauth 1.0 (older versions are no longer supported) (by @TamiasSibiricus)
+
+* bug fix
+  * Allow idempotent API requests
+  * Fix bug where logs did not show 401 as status code
+  * Change paranoid settings to behave as success instead of as failure
+  * Fix bug where activation messages were shown first than the credentials error message
+  * Instance variables are expired after sign out
+
+* deprecation
+  * redirect_location is deprecated, please use after_sign_in_path_for
+  * after_sign_in_path_for now redirects to session[scope_return_to] if any value is stored in it
+
+### 1.4.9
+
+* bug fix
+  * url helpers were not being set under some circumstances
+
+### 1.4.8
+
+* enhancements
+  * Add docs for assets pipeline and Heroku
+
+* bug fix
+  * confirmation_url was not being set under some circumstances
+
+### 1.4.7
+
+* bug fix
+  * Fix backward incompatible change from 1.4.6 for those using custom controllers
+
+### 1.4.6 (yanked)
+
+* enhancements
+  * Allow devise_for :skip => :all
+  * Allow options to be passed to authenticate_user!
+  * Allow --skip-routes to devise generator
+  * Add allow_params_authentication! to make it explicit when params authentication is allowed in a controller
+
+### 1.4.5
+
+* bug fix
+  * Failure app tries the root path if a session one does not exist
+  * No need to finalize Devise helpers all the time (by @bradleypriest)
+  * Reset password shows proper message if user is not active
+  * `clean_up_passwords` sets the accessors to nil to skip validations
+
+### 1.4.4
+
+* bug fix
+  * Do not always skip helpers, instead provide :skip_helpers as option to trigger it manually
+
+### 1.4.3
+
+* enhancements
+  * Improve Rails 3.1 compatibility
+  * Use serialize_into_session and serialize_from_session in Warden serialize to improve extensibility
+
+* bug fix
+  * Generator properly generates a change_table migration if a model already exists
+  * Properly deprecate setup_mail
+  * Fix encoding issues with email regexp
+  * Only generate helpers for the used mappings
+  * Wrap :action constraints in the proper hash
+
+* deprecations
+  * Loosened the used email regexp to simply assert the existent of "@". If someone relies on a more strict regexp, they may use https://github.com/SixArm/sixarm_ruby_email_address_validation
+
+### 1.4.2
+
+* bug fix
+  * Provide a more robust behavior to serializers and add :force_except option
+
+### 1.4.1
+
+* enhancements
+  * Add :defaults and :format support on router
+  * Add simple form generators
+  * Better localization for devise_error_messages! (by @zedtux)
+
+* bug fix
+  * Ensure to_xml is properly white listened
+  * Ensure handle_unverified_request clean up any cached signed-in user
+
+### 1.4.0
+
+* enhancements
+  * Added authenticated and unauthenticated to the router to route the used based on their status (by @sj26)
+  * Improve e-mail regexp (by @rodrigoflores)
+  * Add strip_whitespace_keys and default to e-mail (by @swrobel)
+  * Do not run format and uniqueness validations on e-mail if it hasn't changed (by @Thibaut)
+  * Added update_without_password to update models but not allowing the password to change (by @fschwahn)
+  * Added config.paranoid, check the generator for more information (by @rodrigoflores)
+
+* bug fix
+  * password_required? should not affect length validation
+  * User cannot access sign up and similar pages if they are already signed in through a cookie or token
+  * Do not convert booleans to strings on finders (by @xavier)
+  * Run validations even if current_password fails (by @crx)
+  * Devise now honors routes constraints (by @macmartine)
+  * Do not return the user resource when requesting instructions (by @rodrigoflores)
+
+### 1.3.4
+
+* bug fix
+  * Do not add formats if html or "*/*"
+
+### 1.3.3
+
+* bug fix
+  * Explicitly mark the token as expired if so
+
+### 1.3.2
+
+* bug fix
+  * Fix another regression related to reset_password_sent_at (by @alexdreher)
+
+### 1.3.1
+
+* enhancements
+  * Improve failure_app responses (by @indirect)
+  * sessions/new and registrations/new also respond to xml and json now
+
+* bug fix
+  * Fix a regression that occurred if reset_password_sent_at is not present (by @stevehodgkiss)
+
+### 1.3.0
+
+* enhancements
+  * All controllers can now handle different mime types than html using Responders (by @sikachu)
+  * Added reset_password_within as configuration option to send the token for recovery (by @jdguyot)
+  * Bump password length to 128 characters (by @k33l0r)
+  * Add :only as option to devise_for (by @timoschilling)
+  * Allow to override path after sending password instructions (by @irohiroki)
+  * require_no_authentication has its own flash message (by @jackdempsey)
+
+* bug fix
+  * Fix a bug where configuration options were being included too late
+  * Ensure Devise::TestHelpers can be used to tests Devise internal controllers (by @jwilger)
+  * valid_password? should not choke on empty passwords (by @mikel)
+  * Calling devise more than once does not include previously added modules anymore
+  * downcase_keys before validation
+
+* backward incompatible changes
+  * authentication_keys are no longer considered when creating the e-mail validations, the previous behavior was buggy. You must double check if you were relying on such behavior.
+
+### 1.2.1
+
+* enhancements
+  * Improve update path messages
+
+### 1.2.0
+
+* bug fix
+  * Properly ignore path prefix on omniauthable
+  * Faster uniqueness queries
+  * Rename active? to active_for_authentication? to avoid conflicts
+
+### 1.2.rc2
+
+* enhancements
+  * Make friendly_token 20 chars long
+  * Use secure_compare
+
+* bug fix
+  * Fix an issue causing infinite redirects in production
+  * rails g destroy works properly with devise generators (by @andmej)
+  * before_failure callbacks should work on test helpers (by @twinge)
+  * rememberable cookie now is httponly by default (by @JamesFerguson)
+  * Add missing confirmation_keys (by @JohnPlummer)
+  * Ensure after_* hooks are called on RegistrationsController
+  * When using database_authenticatable Devise will now only create an email field when appropriate (if using default authentication_keys or custom authentication_keys with email included)
+  * Ensure stateless token does not trigger timeout (by @pixelauthority)
+  * Implement handle_unverified_request for Rails 3.0.4 compatibility and improve FailureApp reliance on symbols
+  * Consider namespaces while generating routes
+  * Custom failure apps no longer ignored in test mode (by @jaghion)
+  * Do not depend on ActiveModel::Dirty
+  * Manual sign_in now triggers remember token
+  * Be sure to halt strategies on failures
+  * Consider SCRIPT_NAME on Omniauth paths
+  * Reset failed attempts when lock is expired
+  * Ensure there is no Mongoid injection
+
+* deprecations
+  * Deprecated anybody_signed_in? in favor of signed_in? (by @gavinhughes)
+  * Removed --haml and --slim view templates
+  * Devise::OmniAuth helpers were deprecated and removed in favor of Omniauth.config.test_mode
+
+### 1.2.rc
+
+* deprecations
+  * cookie_domain is deprecated in favor of cookie_options
+  * after_update_path_for can no longer be defined in ApplicationController
+
+* enhancements
+  * Added OmniAuth support
+  * Added ORM adapter to abstract ORM iteraction
+  * sign_out_via is available in the router to configure the method used for sign out (by @martinrehfeld)
+  * Improved Ajax requests handling in failure app (by @spastorino)
+  * Added request_keys to easily use request specific values (like subdomain) in authentication
+  * Increased the size of friendly_token to 60 characters (reduces the chances of a successful brute attack)
+  * Ensure the friendly token does not include "_" or "-" since some e-mails may not autolink it properly (by @rymai)
+  * Extracted encryptors into :encryptable for better bcrypt support
+  * :rememberable is now able to use salt as token if no remember_token is provided
+  * Store the salt in session and expire the session if the user changes their password
+  * Allow :stateless_token to be set to true avoiding users to be stored in session through token authentication
+  * cookie_options uses session_options values by default
+  * Sign up now checks if the user is active or not and redirect them accordingly, setting the inactive_signed_up message
+  * Use ActiveModel#to_key instead of #id
+  * sign_out_all_scopes now destroys the whole session
+  * Added case_insensitive_keys that automatically downcases the given keys, by default downcases only e-mail (by @adahl)
+
+* default behavior changes
+  * sign_out_all_scopes defaults to true as security measure
+  * http authenticatable is disabled by default
+  * Devise does not intercept 401 returned from applications
+
+* bugfix
+  * after_sign_in_path_for always receives a resource
+  * Do not execute Warden::Callbacks on Devise::TestHelpers (by @sgronblo)
+  * Allow password recovery and account unlocking to change used keys (by @RStankov)
+  * FailureApp now properly handles nil request.format
+  * Fix a bug causing FailureApp to return with HTTP Auth Headers for IE7
+  * Ensure namespaces has proper scoped views
+  * Ensure Devise does not set empty flash messages (by @sxross)
+
+### 1.1.6
+
+* Use a more secure e-mail regexp
+* Implement Rails 3.0.4 handle unverified request
+* Use secure_compare to compare passwords
+
+### 1.1.5
+
+* bugfix
+  * Ensure to convert keys on indifferent hash
+
+* defaults
+  * Set config.http_authenticatable to false to avoid confusion
+
+### 1.1.4
+
+* bugfix
+  * Avoid session fixation attacks
+
+### 1.1.3
+
+* bugfix
+  * Add reply-to to e-mail headers by default
+  * Updated the views generator to respect the rails :template_engine option (by @fredwu)
+  * Check the type of HTTP Authentication before using Basic headers
+  * Avoid invalid_salt errors by checking salt presence (by @thibaudgg)
+  * Forget user deletes the right cookie before logout, not remembering the user anymore (by @emtrane)
+  * Fix for failed first-ever logins on PostgreSQL where column default is nil (by @bensie)
+  * :default options is now honored in migrations
+
+### 1.1.2
+
+* bugfix
+  * Compatibility with latest Rails routes schema
+
+### 1.1.1
+
+* bugfix
+  * Fix a small bug where generated locale file was empty on devise:install
+
+### 1.1.0
+
+* enhancements
+  * Rememberable module allows user to be remembered across browsers and is enabled by default (by @trevorturk)
+  * Rememberable module allows you to activate the period the remember me token is extended (by @trevorturk)
+  * devise_for can now be used together with scope method in routes but with a few limitations (check the documentation)
+  * Support `as` or `devise_scope` in the router to specify controller access scope
+  * HTTP Basic Auth can now be disabled/enabled for xhr(ajax) requests using http_authenticatable_on_xhr option (by @pellja)
+
+* bug fix
+  * Fix a bug in Devise::TestHelpers where current_user was returning a Response object for non active accounts
+  * Devise should respect script_name and path_info contracts
+  * Fix a bug when accessing a path with (.:format) (by @klacointe)
+  * Do not add unlock routes unless unlock strategy is email or both
+  * Email should be case insensitive
+  * Store classes as string in session, to avoid serialization and stale data issues
+
+* deprecations
+  * use_default_scope is deprecated and has no effect. Use :as or :devise_scope in the router instead
+
+### 1.1.rc2
+
+* enhancements
+  * Allow to set cookie domain for the remember token. (by @mantas)
+  * Added navigational formats to specify when it should return a 302 and when a 401.
+  * Added authenticate(scope) support in routes (by @wildchild)
+  * Added after_update_path_for to registrations controller (by @thedelchop)
+  * Allow the mailer object to be replaced through config.mailer = "MyOwnMailer"
+
+* bug fix
+  * Fix a bug where session was timing out on sign out
+
+* deprecations
+  * bcrypt is now the default encryptor
+  * devise.mailer.confirmations_instructions now should be devise.mailer.confirmations_instructions.subject
+  * devise.mailer.user.confirmations_instructions now should be devise.mailer.confirmations_instructions.user_subject
+  * Generators now use Rails 3 syntax (devise:install) instead of devise_install
+
+### 1.1.rc1
+
+* enhancements
+  * Rails 3 compatibility
+  * All controllers and views are namespaced, for example: Devise::SessionsController and "devise/sessions"
+  * Devise.orm is deprecated. This reduces the required API to hook your ORM with devise
+  * Use metal for failure app
+  * HTML e-mails now have proper formatting
+  * Allow to give :skip and :controllers in routes
+  * Move trackable logic to the model
+  * E-mails now use any template available in the filesystem. Easy to create multipart e-mails
+  * E-mails asks headers_for in the model to set the proper headers
+  * Allow to specify haml in devise_views
+  * Compatibility with Mongoid
+  * Make config.devise available on config/application.rb
+  * TokenAuthenticatable now works with HTTP Basic Auth
+  * Allow :unlock_strategy to be :none and add :lock_strategy which can be :failed_attempts or none. Setting those values to :none means that you want to handle lock and unlocking by yourself
+  * No need to append ?unauthenticated=true in URLs anymore since Flash was moved to a middleware in Rails 3
+  * :activatable is included by default in your models
+
+* bug fix
+  * Fix a bug with STI
+
+* deprecations
+  * Rails 3 compatible only
+  * Removed support for MongoMapper
+  * Scoped views are no longer "sessions/users/new". Now use "users/sessions/new"
+  * Devise.orm is deprecated, just require "devise/orm/YOUR_ORM" instead
+  * Devise.default_url_options is deprecated, just modify ApplicationController.default_url_options
+  * All messages under devise.sessions, except :signed_in and :signed_out, should be moved to devise.failure
+  * :as and :scope in routes is deprecated. Use :path and :singular instead
+
+### 1.0.8
+
+* enhancements
+  * Support for latest MongoMapper
+  * Added anybody_signed_in? helper (by @SSDany)
+
+* bug fix
+  * confirmation_required? is properly honored on active? calls. (by @paulrosania)
+
+### 1.0.7
+
+* bug fix
+  * Ensure password confirmation is always required
+
+* deprecations
+  * authenticatable was deprecated and renamed to database_authenticatable
+  * confirmable is not included by default on generation
+
+### 1.0.6
+
+* bug fix
+  * Do not allow unlockable strategies based on time to access a controller.
+  * Do not send unlockable email several times.
+  * Allow controller to upstram custom! failures to Warden.
+
+### 1.0.5
+
+* bug fix
+  * Use prepend_before_filter in require_no_authentication.
+  * require_no_authentication on unlockable.
+  * Fix a bug when giving an association proxy to devise.
+  * Do not use lock! on lockable since it's part of ActiveRecord API.
+
+### 1.0.4
+
+* bug fix
+  * Fixed a bug when deleting an account with rememberable
+  * Fixed a bug with custom controllers
+
+### 1.0.3
+
+* enhancements
+  * HTML e-mails now have proper formatting
+  * Do not remove MongoMapper options in find
+
+### 1.0.2
+
+* enhancements
+  * Allows you set mailer content type (by @glennr)
+
+* bug fix
+  * Uses the same content type as request on http authenticatable 401 responses
+
+### 1.0.1
+
+* enhancements
+  * HttpAuthenticatable is not added by default automatically.
+  * Avoid mass assignment error messages with current password.
+
+* bug fix
+  * Fixed encryptors autoload
+
+### 1.0.0
+
+* deprecation
+  * :old_password in update_with_password is deprecated, use :current_password instead
+
+* enhancements
+  * Added Registerable
+  * Added Http Basic Authentication support
+  * Allow scoped_views to be customized per controller/mailer class
+  * Allow authenticatable to used in change_table statements
+
+### 0.9.2
+
+* bug fix
+  * Ensure inactive user cannot sign in
+  * Ensure redirect to proper url after sign up
+
+* enhancements
+  * Added gemspec to repo
+  * Added token authenticatable (by @grimen)
+
+### 0.9.1
+
+* bug fix
+  * Allow bigger salt size (by @jgeiger)
+  * Fix relative url root
+
+### 0.9.0
+
+* deprecation
+  * devise :all is deprecated
+  * :success and :failure flash messages are now :notice and :alert
+
+* enhancements
+  * Added devise lockable (by @mhfs)
+  * Warden 0.9.0 compatibility
+  * Mongomapper 0.6.10 compatibility
+  * Added Devise.add_module as hooks for extensions (by @grimen)
+  * Ruby 1.9.1 compatibility (by @grimen)
+
+* bug fix
+  * Accept path prefix not starting with slash
+  * url helpers should rely on find_scope!
+
+### 0.8.2
+
+* enhancements
+  * Allow Devise.mailer_sender to be a proc (by @grimen)
+
+* bug fix
+  * Fix bug with passenger, update is required to anyone deploying on passenger (by @dvdpalm)
+
+### 0.8.1
+
+* enhancements
+  * Move salt to encryptors
+  * Devise::Lockable
+  * Moved view links into partial and I18n'ed them
+
+* bug fix
+  * Bcrypt generator was not being loaded neither setting the proper salt
+
+### 0.8.0
+
+* enhancements
+  * Warden 0.8.0 compatibility
+  * Add an easy for map.connect "sign_in", :controller => "sessions", :action => "new" to work
+  * Added :bcrypt encryptor (by @capotej)
+
+* bug fix
+  * sign_in_count is also increased when user signs in via password change, confirmation, etc..
+  * More DataMapper compatibility (by @lancecarlson)
+
+* deprecation
+  * Removed DeviseMailer.sender
+
+### 0.7.5
+
+* enhancements
+  * Set a default value for mailer to avoid find_template issues
+  * Add models configuration to MongoMapper::EmbeddedDocument as well
+
+### 0.7.4
+
+* enhancements
+  * Extract Activatable from Confirmable
+  * Decouple Serializers from Devise modules
+
+### 0.7.3
+
+* bug fix
+  * Give scope to the proper model validation
+
+* enhancements
+  * Mail views are scoped as well
+  * Added update_with_password for authenticatable
+  * Allow render_with_scope to accept :controller option
+
+### 0.7.2
+
+* deprecation
+  * Renamed reset_confirmation! to resend_confirmation!
+  * Copying locale is part of the installation process
+
+* bug fix
+  * Fixed render_with_scope to work with all controllers
+  * Allow sign in with two different users in Devise::TestHelpers
+
+### 0.7.1
+
+* enhancements
+  * Small enhancements for other plugins compatibility (by @grimen)
+
+### 0.7.0
+
+* deprecations
+  * :authenticatable is not included by default anymore
+
+* enhancements
+  * Improve loading process
+  * Extract SessionSerializer from Authenticatable
+
+### 0.6.3
+
+* bug fix
+  * Added trackable to migrations
+  * Allow inflections to work
+
+### 0.6.2
+
+* enhancements
+  * More DataMapper compatibility
+  * Devise::Trackable - track sign in count, timestamps and ips
+
+### 0.6.1
+
+* enhancements
+  * Devise::Timeoutable - timeout sessions without activity
+  * DataMapper now accepts conditions
+
+### 0.6.0
+
+* deprecations
+  * :authenticatable is still included by default, but yields a deprecation warning
+
+* enhancements
+  * Added DataMapper support
+  * Remove store_location from authenticatable strategy and add it to failure app
+  * Allow a strategy to be placed after authenticatable
+  * Do not rely attribute? methods, since they are not added on Datamapper
+
+### 0.5.6
+
+* enhancements
+  * Do not send nil to build (DataMapper compatibility)
+  * Allow to have scoped views
+
+### 0.5.5
+
+* enhancements
+  * Allow overwriting find for authentication method
+  * Remove Ruby 1.8.7 dependency
+
+### 0.5.4
+
+* deprecations
+  * Deprecate :singular in devise_for and use :scope instead
+
+* enhancements
+  * Create after_sign_in_path_for and after_sign_out_path_for hooks to be
+    overwriten in ApplicationController
+  * Create sign_in_and_redirect and sign_out_and_redirect helpers
+  * Warden::Manager.default_scope is automatically configured to the first given scope
+
+### 0.5.3
+
+* bug fix
+  * MongoMapper now converts DateTime to Time
+  * Ensure all controllers are unloadable
+
+* enhancements
+  * Moved friendly_token to Devise
+  * Added Devise.all, so you can freeze your app strategies
+  * Added Devise.apply_schema, so you can turn it to false in Datamapper or MongoMapper
+    in cases you don't want it be handlded automatically
+
+### 0.5.2
+
+* enhancements
+  * Improved sign_in and sign_out helpers to accepts resources
+  * Added stored_location_for as a helper
+  * Added test helpers
+
+### 0.5.1
+
+* enhancements
+  * Added serializers based on Warden ones
+  * Allow authentication keys to be set
+
+### 0.5.0
+
+* bug fix
+  * Fixed a bug where remember me module was not working properly
+
+* enhancements
+  * Moved encryption strategy into the Encryptors module to allow several algorithms (by @mhfs)
+  * Implemented encryptors for Clearance, Authlogic and Restful-Authentication (by @mhfs)
+  * Added support for MongoMapper (by @shingara)
+
+### 0.4.3
+
+* bug fix
+  * Authentication just fails if user cannot be serialized from session, without raising errors;
+  * Default configuration values should not overwrite user values;
+
+### 0.4.2
+
+* deprecations
+  * Renamed mail_sender to mailer_sender
+
+* enhancements
+  * skip_before_filter added in Devise controllers
+  * Use home_or_root_path on require_no_authentication as well
+  * Added devise_controller?, useful to select or reject filters in ApplicationController
+  * Allow :path_prefix to be given to devise_for
+  * Allow default_url_options to be configured through devise (:path_prefix => "/:locale" is now supported)
+
+### 0.4.1
+
+* bug fix
+  * Ensure options can be set even if models were not loaded
+
+### 0.4.0
+
+* deprecations
+  * Notifier is deprecated, use DeviseMailer instead. Remember to rename
+    app/views/notifier to app/views/devise_mailer and I18n key from
+    devise.notifier to devise.mailer
+  * :authenticable calls are deprecated, use :authenticatable instead
+
+* enhancements
+  * Allow devise to be more agnostic and do not require ActiveRecord to be loaded
+  * Allow Warden::Manager to be configured through Devise
+  * Created a generator which creates an initializer
+
+### 0.3.0
+
+* bug fix
+  * Allow yml messages to be configured by not using engine locales
+
+* deprecations
+  * Renamed confirm_in to confirm_within
+  * Do not send confirmation messages when user changes their e-mail
+  * Renamed authenticable to authenticatable and added deprecation warnings
+
+### 0.2.3
+
+* enhancements
+  * Ensure fail! works inside strategies
+  * Make unauthenticated message (when you haven't signed in) different from invalid message
+
+* bug fix
+  * Do not redirect on invalid authenticate
+  * Allow model configuration to be set to nil
+
+### 0.2.2
+
+* bug fix
+  * Fix a bug when using customized resources
+
+### 0.2.1
+
+* refactor
+  * Clean devise_views generator to use devise existing views
+
+* enhancements
+  * Create instance variables (like @user) for each devise controller
+  * Use Devise::Controller::Helpers only internally
+
+* bug fix
+  * Fix a bug with Mongrel and Ruby 1.8.6
+
+### 0.2.0
+
+* enhancements
+  * Allow option :null => true in authenticable migration
+  * Remove attr_accessible calls from devise modules
+  * Customizable time frame for rememberable with :remember_for config
+  * Customizable time frame for confirmable with :confirm_in config
+  * Generators for creating a resource and copy views
+
+* optimize
+  * Do not load hooks or strategies if they are not used
+
+* bug fixes
+  * Fixed requiring devise strategies
+
+### 0.1.1
+
+* bug fixes
+  * Fixed requiring devise mapping
+
+### 0.1.0
+
+* Devise::Authenticable
+* Devise::Confirmable
+* Devise::Recoverable
+* Devise::Validatable
+* Devise::Migratable
+* Devise::Rememberable
+
+* SessionsController
+* PasswordsController
+* ConfirmationsController
+
+* Create an example app
+* devise :all, :except => :rememberable
+* Use sign_in and sign_out in SessionsController
+
+* Mailer subjects namespaced by model
+* Allow stretches and pepper per model
+
+* Store session[:return_to] in session
+* Sign user in automatically after confirming or changing it's password
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..b9c929a
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,14 @@
+### Please read before contributing
+
+1) Do not post questions in the issues tracker. If you have any questions about Devise, search the [Wiki](https://github.com/plataformatec/devise/wiki) or use the [Mailing List](https://groups.google.com/group/plataformatec-devise) or [Stack Overflow](http://stackoverflow.com/questions/tagged/devise).
+
+2) If you find a security bug, **DO NOT** submit an issue here. Please send an e-mail to [opensource at plataformatec.com.br](mailto:opensource at plataformatec.com.br) instead.
+
+3) Do a small search on the issues tracker before submitting your issue to see if it was already reported / fixed.
+
+4) When reporting an issue, include Rails, Devise and Warden versions. If you are getting exceptions, please include the full backtrace.
+
+That's it! The more information you give, the easier it becomes for us to track it down and fix it.
+Ideally, you should provide an application that reproduces the error or a test case to Devise's suite.
+
+Thanks!
diff --git a/Gemfile b/Gemfile
new file mode 100644
index 0000000..3eab620
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,29 @@
+source "https://rubygems.org"
+
+gemspec
+
+gem "rails", "4.2.0.beta2"
+gem "omniauth", "~> 1.2.0"
+gem "omniauth-oauth2", "~> 1.1.0"
+gem "rdoc"
+
+group :test do
+  gem "omniauth-facebook"
+  gem "omniauth-openid", "~> 1.0.1"
+  gem "webrat", "0.7.3", require: false
+  gem "mocha", "~> 1.1", require: false
+end
+
+platforms :jruby do
+  gem "activerecord-jdbc-adapter"
+  gem "activerecord-jdbcsqlite3-adapter"
+  gem "jruby-openssl"
+end
+
+platforms :ruby do
+  gem "sqlite3"
+end
+
+group :mongoid do
+  gem "mongoid", github: "mongoid/mongoid", branch: "master"
+end
diff --git a/Gemfile.lock b/Gemfile.lock
new file mode 100644
index 0000000..6441944
--- /dev/null
+++ b/Gemfile.lock
@@ -0,0 +1,192 @@
+GIT
+  remote: git://github.com/mongoid/mongoid.git
+  revision: 5ba2e1fb4cb8189c9890e29c19cf4e16c25e4bc5
+  branch: master
+  specs:
+    mongoid (4.0.0)
+      activemodel (~> 4.0)
+      moped (~> 2.0.0)
+      origin (~> 2.1)
+      tzinfo (>= 0.3.37)
+
+PATH
+  remote: .
+  specs:
+    devise (3.4.0)
+      bcrypt (~> 3.0)
+      orm_adapter (~> 0.1)
+      railties (>= 3.2.6, < 5)
+      responders
+      thread_safe (~> 0.1)
+      warden (~> 1.2.3)
+
+GEM
+  remote: https://rubygems.org/
+  specs:
+    actionmailer (4.2.0.beta2)
+      actionpack (= 4.2.0.beta2)
+      actionview (= 4.2.0.beta2)
+      activejob (= 4.2.0.beta2)
+      mail (~> 2.5, >= 2.5.4)
+      rails-dom-testing (~> 1.0, >= 1.0.3)
+    actionpack (4.2.0.beta2)
+      actionview (= 4.2.0.beta2)
+      activesupport (= 4.2.0.beta2)
+      rack (~> 1.6.0.beta)
+      rack-test (~> 0.6.2)
+      rails-dom-testing (~> 1.0, >= 1.0.3)
+      rails-html-sanitizer (~> 1.0, >= 1.0.1)
+    actionview (4.2.0.beta2)
+      activesupport (= 4.2.0.beta2)
+      builder (~> 3.1)
+      erubis (~> 2.7.0)
+      rails-dom-testing (~> 1.0, >= 1.0.3)
+      rails-html-sanitizer (~> 1.0, >= 1.0.1)
+    activejob (4.2.0.beta2)
+      activesupport (= 4.2.0.beta2)
+      globalid (>= 0.3.0)
+    activemodel (4.2.0.beta2)
+      activesupport (= 4.2.0.beta2)
+      builder (~> 3.1)
+    activerecord (4.2.0.beta2)
+      activemodel (= 4.2.0.beta2)
+      activesupport (= 4.2.0.beta2)
+      arel (>= 6.0.0.beta1, < 6.1)
+    activesupport (4.2.0.beta2)
+      i18n (>= 0.7.0.beta1, < 0.8)
+      json (~> 1.7, >= 1.7.7)
+      minitest (~> 5.1)
+      thread_safe (~> 0.1)
+      tzinfo (~> 1.1)
+    arel (6.0.0.beta1)
+    bcrypt (3.1.7)
+    bson (2.3.0)
+    builder (3.2.2)
+    connection_pool (2.0.0)
+    erubis (2.7.0)
+    faraday (0.9.0)
+      multipart-post (>= 1.2, < 3)
+    globalid (0.3.0)
+      activesupport (>= 4.1.0)
+    hashie (3.2.0)
+    hike (1.2.3)
+    i18n (0.7.0.beta1)
+    json (1.8.1)
+    jwt (1.0.0)
+    loofah (2.0.1)
+      nokogiri (>= 1.5.9)
+    mail (2.6.1)
+      mime-types (>= 1.16, < 3)
+    metaclass (0.0.4)
+    mime-types (2.3)
+    mini_portile (0.6.0)
+    minitest (5.4.2)
+    mocha (1.1.0)
+      metaclass (~> 0.0.1)
+    moped (2.0.0)
+      bson (~> 2.2)
+      connection_pool (~> 2.0)
+      optionable (~> 0.2.0)
+    multi_json (1.10.1)
+    multi_xml (0.5.5)
+    multipart-post (2.0.0)
+    nokogiri (1.6.3.1)
+      mini_portile (= 0.6.0)
+    oauth2 (0.9.4)
+      faraday (>= 0.8, < 0.10)
+      jwt (~> 1.0)
+      multi_json (~> 1.3)
+      multi_xml (~> 0.5)
+      rack (~> 1.2)
+    omniauth (1.2.2)
+      hashie (>= 1.2, < 4)
+      rack (~> 1.0)
+    omniauth-facebook (1.6.0)
+      omniauth-oauth2 (~> 1.1)
+    omniauth-oauth2 (1.1.2)
+      faraday (>= 0.8, < 0.10)
+      multi_json (~> 1.3)
+      oauth2 (~> 0.9.3)
+      omniauth (~> 1.2)
+    omniauth-openid (1.0.1)
+      omniauth (~> 1.0)
+      rack-openid (~> 1.3.1)
+    optionable (0.2.0)
+    origin (2.1.1)
+    orm_adapter (0.5.0)
+    rack (1.6.0.beta)
+    rack-openid (1.3.1)
+      rack (>= 1.1.0)
+      ruby-openid (>= 2.1.8)
+    rack-test (0.6.2)
+      rack (>= 1.0)
+    rails (4.2.0.beta2)
+      actionmailer (= 4.2.0.beta2)
+      actionpack (= 4.2.0.beta2)
+      actionview (= 4.2.0.beta2)
+      activejob (= 4.2.0.beta2)
+      activemodel (= 4.2.0.beta2)
+      activerecord (= 4.2.0.beta2)
+      activesupport (= 4.2.0.beta2)
+      bundler (>= 1.3.0, < 2.0)
+      railties (= 4.2.0.beta2)
+      sprockets-rails (~> 3.0.0.beta1)
+    rails-deprecated_sanitizer (1.0.3)
+      activesupport (>= 4.2.0.alpha)
+    rails-dom-testing (1.0.3)
+      activesupport
+      nokogiri (~> 1.6.0)
+      rails-deprecated_sanitizer (>= 1.0.1)
+    rails-html-sanitizer (1.0.1)
+      loofah (~> 2.0)
+    railties (4.2.0.beta2)
+      actionpack (= 4.2.0.beta2)
+      activesupport (= 4.2.0.beta2)
+      rake (>= 0.8.7)
+      thor (>= 0.18.1, < 2.0)
+    rake (10.3.2)
+    rdoc (4.1.1)
+      json (~> 1.4)
+    responders (2.0.0)
+      railties (>= 4.2.0.alpha, < 5)
+    ruby-openid (2.5.0)
+    sprockets (2.12.2)
+      hike (~> 1.2)
+      multi_json (~> 1.0)
+      rack (~> 1.0)
+      tilt (~> 1.1, != 1.3.0)
+    sprockets-rails (3.0.0.beta1)
+      actionpack (>= 4.0)
+      activesupport (>= 4.0)
+      sprockets (~> 2.8)
+    sqlite3 (1.3.9)
+    thor (0.19.1)
+    thread_safe (0.3.4)
+    tilt (1.4.1)
+    tzinfo (1.2.2)
+      thread_safe (~> 0.1)
+    warden (1.2.3)
+      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 (~> 1.1)
+  mongoid!
+  omniauth (~> 1.2.0)
+  omniauth-facebook
+  omniauth-oauth2 (~> 1.1.0)
+  omniauth-openid (~> 1.0.1)
+  rails (= 4.2.0.beta2)
+  rdoc
+  sqlite3
+  webrat (= 0.7.3)
diff --git a/MIT-LICENSE b/MIT-LICENSE
new file mode 100644
index 0000000..6d66ba3
--- /dev/null
+++ b/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright 2009-2014 Plataformatec. http://plataformatec.com.br
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..7ef0b7b
--- /dev/null
+++ b/README.md
@@ -0,0 +1,529 @@
+![Devise Logo](https://raw.github.com/plataformatec/devise/master/devise.png)
+
+By [Plataformatec](http://plataformatec.com.br/).
+
+[![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)
+[![Security](https://hakiri.io/github/plataformatec/devise/master.svg)](https://hakiri.io/github/plataformatec/devise/master)
+
+This README is [also available in a friendly navigable format](http://devise.plataformatec.com.br/).
+
+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;
+* Is based on a modularity concept: use just what you really need.
+
+It's composed of 10 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.
+* [Omniauthable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Omniauthable): adds Omniauth (https://github.com/intridea/omniauth) support.
+* [Confirmable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Confirmable): sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in.
+* [Recoverable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Recoverable): resets the user password and sends reset instructions.
+* [Registerable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Registerable): handles signing up users through a registration process, also allowing them to edit and destroy their account.
+* [Rememberable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Rememberable): manages generating and clearing a token for remembering the user from a saved cookie.
+* [Trackable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Trackable): tracks sign in count, timestamps and IP address.
+* [Timeoutable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Timeoutable): expires sessions that have no activity in a specified period of time.
+* [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 in progress.
+
+## Information
+
+### The Devise wiki
+
+The Devise Wiki has lots of additional information about Devise including many "how-to" articles and answers to the most frequently asked questions. Please browse the Wiki after finishing this README:
+
+https://github.com/plataformatec/devise/wiki
+
+### Bug reports
+
+If you discover a problem with Devise, we would like to know about it. However, we ask that you please review these guidelines before submitting a bug report:
+
+https://github.com/plataformatec/devise/wiki/Bug-reports
+
+If you found a security bug, do *NOT* use the GitHub issue tracker. Send an email to opensource at plataformatec.com.br.
+
+### Mailing list
+
+If you have any questions, comments, or concerns, please use the Google Group instead of the GitHub issue tracker:
+
+https://groups.google.com/group/plataformatec-devise
+
+### RDocs
+
+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.
+
+### Example applications
+
+There are a few example applications available on GitHub that demonstrate various features of Devise with different versions of Rails. You can view them here:
+
+https://github.com/plataformatec/devise/wiki/Example-Applications
+
+### Extensions
+
+Our community has created a number of extensions that add functionality above and beyond what is included with Devise. You can view a list of available extensions and add your own here:
+
+https://github.com/plataformatec/devise/wiki/Extensions
+
+### Contributing
+
+We hope that you will consider contributing to Devise. Please read this short overview for some information about how to get started:
+
+https://github.com/plataformatec/devise/wiki/Contributing
+
+You will usually want to write tests for your changes.  To run the test suite, go into Devise's top-level directory and run "bundle install" and "rake".  For the tests to pass, you will need to have a MongoDB server (version 2.0 or newer) running on your system.
+
+## Starting with Rails?
+
+If you are building your first Rails application, we recommend you to *not* use Devise. Devise requires a good understanding of the Rails Framework. In such cases, we advise you to start a simple authentication system from scratch, today we have two resources:
+
+* Michael Hartl's online book: http://www.railstutorial.org/book/demo_app#sec-modeling_demo_users
+* Ryan Bates' Railscast: http://railscasts.com/episodes/250-authentication-from-scratch
+
+Once you have solidified your understanding of Rails and authentication mechanisms, we assure you Devise will be very pleasant to work with. :)
+
+## Getting started
+
+Devise 3.0 works with Rails 3.2 onwards. You can add it to your Gemfile with:
+
+```ruby
+gem 'devise'
+```
+
+Run the bundle command to install it.
+
+After you install Devise and add it to your Gemfile, you need to run the generator:
+
+```console
+rails generate devise:install
+```
+
+The generator will install an initializer which describes ALL Devise's configuration options and you MUST take a look at it. When you are done, you are ready to add Devise to any of your models using the generator:
+
+```console
+rails generate devise MODEL
+```
+
+Replace MODEL with the class name used for the application’s 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. The generator also configures your `config/routes.rb` file to point to the Devise controller.
+
+Next, check the MODEL for any additional configuration options you might want to add, such as confirmable or lockable. If you add an option, be sure to inspect the migration file (created by the generator if your ORM supports them) and uncomment the appropriate section.  For example, if you add the confirmable option in the model, you'll need to uncomment the Confirmable section in the migration. Then run `rake db:migrate`
+
+Next, you need to set up the default URL options for the Devise mailer in each environment. Here is a possible configuration for `config/environments/development.rb`:
+
+```ruby
+config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
+```
+
+You should restart your application after changing Devise's configuration options. Otherwise you'll run into strange errors like users being unable to login and route helpers being undefined.
+
+### Controller filters and helpers
+
+Devise will create some helpers to use inside your controllers and views. To set up a controller with user authentication, just add this before_action (assuming your devise model is 'User'):
+
+```ruby
+before_action :authenticate_user!
+```
+
+If your devise model is something other than User, replace "_user" with "_yourmodel". The same logic applies to the instructions below.
+
+To verify if a user is signed in, use the following helper:
+
+```ruby
+user_signed_in?
+```
+
+For the current signed-in user, this helper is available:
+
+```ruby
+current_user
+```
+
+You can access the session for this scope:
+
+```ruby
+user_session
+```
+
+After signing in a user, confirming the account or updating the password, Devise will look for a scoped root path to redirect. For instance, for a `:user` resource, the `user_root_path` will be used if it exists, otherwise the default `root_path` will be used. This means that you need to set the root inside your routes:
+
+```ruby
+root to: "home#index"
+```
+
+You can also override `after_sign_in_path_for` and `after_sign_out_path_for` to customize your redirect hooks.
+
+Notice that if your Devise model is called `Member` instead of `User`, for example, then the helpers available are:
+
+```ruby
+before_action :authenticate_member!
+
+member_signed_in?
+
+current_member
+
+member_session
+```
+
+### Configuring Models
+
+The Devise method in your models also accepts some options to configure its modules. For example, you can choose the cost of the encryption algorithm with:
+
+```ruby
+devise :database_authenticatable, :registerable, :confirmable, :recoverable, stretches: 20
+```
+
+Besides `:stretches`, you can define `:pepper`, `:encryptor`, `:confirm_within`, `:remember_for`, `:timeout_in`, `:unlock_in` among other options. For more details, see the initializer file that was created when you invoked the "devise:install" generator described above.
+
+### Strong Parameters
+
+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 permitted parameters by default are:
+
+* `sign_in` (`Devise::SessionsController#create`) - 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 permit additional parameters (the lazy way™) you can do with a simple before filter in your `ApplicationController`:
+
+```ruby
+class ApplicationController < ActionController::Base
+  before_action :configure_permitted_parameters, if: :devise_controller?
+
+  protected
+
+  def configure_permitted_parameters
+    devise_parameter_sanitizer.for(:sign_up) << :username
+  end
+end
+```
+
+The above works for any additional fields where the parameters are simple scalar types. If you have nested attributes (say you're using `accepts_nested_attributes_for`), then you will need to tell devise about those nestings and types. Devise allows you to completely change Devise defaults or invoke custom behaviour by passing a block:
+
+To permit simple scalar values for username and email, use this
+
+```ruby
+def configure_permitted_parameters
+  devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email) }
+end
+```
+
+If you have some checkboxes that express the roles a user may take on registration, the browser will send those selected checkboxes as an array. An array is not one of Strong Parameters permitted scalars, so we need to configure Devise thusly:
+
+```ruby
+def configure_permitted_parameters
+  devise_parameter_sanitizer.for(:sign_up) { |u| u.permit({ roles: [] }, :email, :password, :password_confirmation) }
+end
+```
+For the list of permitted scalars, and how to declare permitted keys in nested hashes and arrays, see
+
+https://github.com/rails/strong_parameters#nested-parameters
+
+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.
+
+### Configuring views
+
+We built Devise to help you quickly develop an application that uses authentication. However, we don't want to be in your way when you need to customize it.
+
+Since Devise is an engine, all its views are packaged inside the gem. These views will help you get started, but after some time you may want to change them. If this is the case, you just need to invoke the following generator, and it will copy all views to your application:
+
+```console
+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 the `config/initializers/devise.rb` file.
+
+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:
+
+```console
+rails generate devise:views users
+```
+
+If you want to generate only a few set of views, like the ones for the `registrable` and `confirmable` module,
+you can pass a list of modules to the generator with the `-v` flag.
+
+```console
+rails generate devise:views -v registrations confirmations
+```
+
+### Configuring controllers
+
+If the customization at the views level is not enough, you can customize each controller by following these steps:
+
+1. Create your custom controllers using the generator which requires a scope:
+
+    ```console
+    rails generate devise:controllers [scope]
+    ```
+
+    If you specify `admins` as the scope, controllers will be created in `app/controllers/admins/`.
+    And the sessions controller will look like this:
+
+    ```ruby
+    class Admins::SessionsController < Devise::SessionsController
+      # GET /resource/sign_in
+      # def new
+      #   super
+      # end
+      ...
+    end
+    ```
+
+2. Tell the router to use this controller:
+
+    ```ruby
+    devise_for :admins, controllers: { sessions: "admins/sessions" }
+    ```
+
+3. Copy the views from `devise/sessions` to `admins/sessions`. Since the controller was changed, it won't use the default views located in `devise/sessions`.
+
+4. Finally, change or extend the desired controller actions.
+
+    You can completely override a controller action:
+
+    ```ruby
+    class Admins::SessionsController < Devise::SessionsController
+      def create
+        # custom sign-in code
+      end
+    end
+    ```
+
+    Or you can simply add new behaviour to it:
+
+    ```ruby
+    class Admins::SessionsController < Devise::SessionsController
+      def create
+        super do |resource|
+          BackgroundWorker.trigger(resource)
+        end
+      end
+    end
+    ```
+
+    This is useful for triggering background jobs or logging events during certain actions.
+
+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 only specific keys. In some circumstances, Devise adds a `:timedout` key to the flash hash, which is not meant for display. Remove this key from the hash if you intend to print the entire hash.
+
+### Configuring routes
+
+Devise also ships with default routes. If you need to customize them, you should probably be able to do it through the devise_for method. It accepts several options like :class_name, :path_prefix and so on, including the possibility to change path names for I18n:
+
+```ruby
+devise_for :users, path: "auth", path_names: { sign_in: 'login', sign_out: 'logout', password: 'secret', confirmation: 'verification', unlock: 'unblock', registration: 'register', sign_up: 'cmon_let_me_in' }
+```
+
+Be sure to check `devise_for` documentation for details.
+
+If you have the need for more deep customization, for instance to also allow "/sign_in" besides "/users/sign_in", all you need to do is to create your routes normally and wrap them in a `devise_scope` block in the router:
+
+```ruby
+devise_scope :user do
+  get "sign_in", to: "devise/sessions#new"
+end
+```
+
+This way you tell Devise to use the scope `:user` when "/sign_in" is accessed. Notice `devise_scope` is also aliased as `as` in your router.
+
+### I18n
+
+Devise uses flash messages with I18n with the flash keys :notice and :alert. To customize your app, you can set up your locale file:
+
+```yaml
+en:
+  devise:
+    sessions:
+      signed_in: 'Signed in successfully.'
+```
+
+You can also create distinct messages based on the resource you've configured using the singular name given in routes:
+
+```yaml
+en:
+  devise:
+    sessions:
+      user:
+        signed_in: 'Welcome user, you are signed in.'
+      admin:
+        signed_in: 'Hello admin!'
+```
+
+The Devise mailer uses a similar pattern to create subject messages:
+
+```yaml
+en:
+  devise:
+    mailer:
+      confirmation_instructions:
+        subject: 'Hello everybody!'
+        user_subject: 'Hello User! Please confirm your email'
+      reset_password_instructions:
+        subject: 'Reset instructions'
+```
+
+Take a look at our locale file to check all available messages. You may also be interested in one of the many translations that are available on our wiki:
+
+https://github.com/plataformatec/devise/wiki/I18n
+
+Caution: Devise Controllers inherit from ApplicationController. If your app uses multiple locales, you should be sure to set I18n.locale in ApplicationController
+
+### Test helpers
+
+Devise includes some test helpers for functional specs. In order to use them, you need to include Devise in your functional tests by adding the following to the bottom of your `test/test_helper.rb` file:
+
+```ruby
+class ActionController::TestCase
+  include Devise::TestHelpers
+end
+```
+
+If you're using RSpec, you can put the following inside a file named `spec/support/devise.rb` or in your `spec/spec_helper.rb` (or `spec/rails_helper.rb` if you are using rspec-rails):
+
+```ruby
+RSpec.configure do |config|
+  config.include Devise::TestHelpers, type: :controller
+end
+```
+
+Now you are ready to use the `sign_in` and `sign_out` methods. Such methods have the same signature as in controllers:
+
+```ruby
+sign_in :user, @user   # sign_in(scope, resource)
+sign_in @user          # sign_in(resource)
+
+sign_out :user         # sign_out(scope)
+sign_out @user         # sign_out(resource)
+```
+
+There are two things that are 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;
+
+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 the 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
+
+Devise comes with Omniauth support out of the box to authenticate with other providers. To use it, just specify your omniauth configuration in `config/initializers/devise.rb`:
+
+```ruby
+config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
+```
+
+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 a dedicated gem for authorization.
+
+### ActiveJob Integration
+
+If you are using Rails 4.2 and ActiveJob to deliver ActionMailer messages in the
+background through a queueing backend, you can send Devise emails through your
+existing queue by overriding the `send_devise_notification` method in your model.
+
+```ruby
+def send_devise_notification(notification, *args)
+  devise_mailer.send(notification, self, *args).deliver_later
+end
+```
+
+### Other ORMs
+
+Devise supports ActiveRecord (default) and Mongoid. To choose other ORM, you just need to require it in the initializer file.
+
+## Additional information
+
+### Heroku
+
+Using Devise on Heroku with Ruby on Rails 3.1 requires setting:
+
+```ruby
+config.assets.initialize_on_precompile = false
+```
+
+Read more about the potential issues at http://guides.rubyonrails.org/asset_pipeline.html
+
+### 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:
+
+https://github.com/hassox/warden
+
+### Contributors
+
+We have a long list of valued contributors. Check them all at:
+
+https://github.com/plataformatec/devise/graphs/contributors
+
+## License
+
+MIT License. Copyright 2009-2014 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.
diff --git a/Rakefile b/Rakefile
new file mode 100644
index 0000000..553344b
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,35 @@
+# encoding: UTF-8
+require "bundler/gem_tasks"
+require 'rake/testtask'
+require 'rdoc/task'
+
+desc 'Default: run tests for all ORMs.'
+task default: :test
+
+desc 'Run Devise tests for all ORMs.'
+task :pre_commit do
+  Dir[File.join(File.dirname(__FILE__), 'test', 'orm', '*.rb')].each do |file|
+    orm = File.basename(file).split(".").first
+    # "Some day, my son, rake's inner wisdom will reveal itself.  Until then,
+    # take this `system` -- may its brute force protect you well."
+    exit 1 unless system "rake test DEVISE_ORM=#{orm}"
+  end
+end
+
+desc 'Run Devise unit tests.'
+Rake::TestTask.new(:test) do |t|
+  t.libs << 'lib'
+  t.libs << 'test'
+  t.pattern = 'test/**/*_test.rb'
+  t.verbose = true
+  t.warning = false
+end
+
+desc 'Generate documentation for Devise.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+  rdoc.rdoc_dir = 'rdoc'
+  rdoc.title    = 'Devise'
+  rdoc.options << '--line-numbers' << '--inline-source'
+  rdoc.rdoc_files.include('README.md')
+  rdoc.rdoc_files.include('lib/**/*.rb')
+end
diff --git a/app/controllers/devise/confirmations_controller.rb b/app/controllers/devise/confirmations_controller.rb
new file mode 100644
index 0000000..ec4aff1
--- /dev/null
+++ b/app/controllers/devise/confirmations_controller.rb
@@ -0,0 +1,47 @@
+class Devise::ConfirmationsController < DeviseController
+  # GET /resource/confirmation/new
+  def new
+    self.resource = resource_class.new
+  end
+
+  # POST /resource/confirmation
+  def create
+    self.resource = resource_class.send_confirmation_instructions(resource_params)
+    yield resource if block_given?
+
+    if successfully_sent?(resource)
+      respond_with({}, location: after_resending_confirmation_instructions_path_for(resource_name))
+    else
+      respond_with(resource)
+    end
+  end
+
+  # GET /resource/confirmation?confirmation_token=abcdef
+  def show
+    self.resource = resource_class.confirm_by_token(params[:confirmation_token])
+    yield resource if block_given?
+
+    if resource.errors.empty?
+      set_flash_message(:notice, :confirmed) if is_flashing_format?
+      respond_with_navigational(resource){ redirect_to after_confirmation_path_for(resource_name, resource) }
+    else
+      respond_with_navigational(resource.errors, status: :unprocessable_entity){ render :new }
+    end
+  end
+
+  protected
+
+    # The path used after resending confirmation instructions.
+    def after_resending_confirmation_instructions_path_for(resource_name)
+      is_navigational_format? ? new_session_path(resource_name) : '/'
+    end
+
+    # The path used after confirmation.
+    def after_confirmation_path_for(resource_name, resource)
+      if signed_in?(resource_name)
+        signed_in_root_path(resource)
+      else
+        new_session_path(resource_name)
+      end
+    end
+end
diff --git a/app/controllers/devise/omniauth_callbacks_controller.rb b/app/controllers/devise/omniauth_callbacks_controller.rb
new file mode 100644
index 0000000..92e4067
--- /dev/null
+++ b/app/controllers/devise/omniauth_callbacks_controller.rb
@@ -0,0 +1,30 @@
+class Devise::OmniauthCallbacksController < DeviseController
+  prepend_before_filter { request.env["devise.skip_timeout"] = true }
+
+  def passthru
+    render status: 404, text: "Not found. Authentication passthru."
+  end
+
+  def failure
+    set_flash_message :alert, :failure, kind: OmniAuth::Utils.camelize(failed_strategy.name), reason: failure_message
+    redirect_to after_omniauth_failure_path_for(resource_name)
+  end
+
+  protected
+
+  def failed_strategy
+    env["omniauth.error.strategy"]
+  end
+
+  def failure_message
+    exception = env["omniauth.error"]
+    error   = exception.error_reason if exception.respond_to?(:error_reason)
+    error ||= exception.error        if exception.respond_to?(:error)
+    error ||= env["omniauth.error.type"].to_s
+    error.to_s.humanize if error
+  end
+
+  def after_omniauth_failure_path_for(scope)
+    new_session_path(scope)
+  end
+end
diff --git a/app/controllers/devise/passwords_controller.rb b/app/controllers/devise/passwords_controller.rb
new file mode 100644
index 0000000..d88ebdb
--- /dev/null
+++ b/app/controllers/devise/passwords_controller.rb
@@ -0,0 +1,70 @@
+class Devise::PasswordsController < DeviseController
+  prepend_before_filter :require_no_authentication
+  # Render the #edit only if coming from a reset password email link
+  append_before_filter :assert_reset_token_passed, only: :edit
+
+  # GET /resource/password/new
+  def new
+    self.resource = resource_class.new
+  end
+
+  # POST /resource/password
+  def create
+    self.resource = resource_class.send_reset_password_instructions(resource_params)
+    yield resource if block_given?
+
+    if successfully_sent?(resource)
+      respond_with({}, location: after_sending_reset_password_instructions_path_for(resource_name))
+    else
+      respond_with(resource)
+    end
+  end
+
+  # GET /resource/password/edit?reset_password_token=abcdef
+  def edit
+    self.resource = resource_class.new
+    resource.reset_password_token = params[:reset_password_token]
+  end
+
+  # PUT /resource/password
+  def update
+    self.resource = resource_class.reset_password_by_token(resource_params)
+    yield resource if block_given?
+
+    if resource.errors.empty?
+      resource.unlock_access! if unlockable?(resource)
+      flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
+      set_flash_message(:notice, flash_message) if is_flashing_format?
+      sign_in(resource_name, 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) if is_navigational_format?
+    end
+
+    # 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)
+        redirect_to new_session_path(resource_name)
+      end
+    end
+
+    # Check if proper Lockable module methods are present & unlock strategy
+    # allows to unlock resource on password reset
+    def unlockable?(resource)
+      resource.respond_to?(:unlock_access!) &&
+        resource.respond_to?(:unlock_strategy_enabled?) &&
+        resource.unlock_strategy_enabled?(:email)
+    end
+end
diff --git a/app/controllers/devise/registrations_controller.rb b/app/controllers/devise/registrations_controller.rb
new file mode 100644
index 0000000..f8f82b0
--- /dev/null
+++ b/app/controllers/devise/registrations_controller.rb
@@ -0,0 +1,148 @@
+class Devise::RegistrationsController < DeviseController
+  prepend_before_filter :require_no_authentication, only: [ :new, :create, :cancel ]
+  prepend_before_filter :authenticate_scope!, only: [:edit, :update, :destroy]
+
+  # GET /resource/sign_up
+  def new
+    build_resource({})
+    @validatable = devise_mapping.validatable?
+    if @validatable
+      @minimum_password_length = resource_class.password_length.min
+    end
+    respond_with self.resource
+  end
+
+  # POST /resource
+  def create
+    build_resource(sign_up_params)
+
+    resource_saved = resource.save
+    yield resource if block_given?
+    if resource_saved
+      if resource.active_for_authentication?
+        set_flash_message :notice, :signed_up if is_flashing_format?
+        sign_up(resource_name, resource)
+        respond_with resource, location: after_sign_up_path_for(resource)
+      else
+        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
+        expire_data_after_sign_in!
+        respond_with resource, location: after_inactive_sign_up_path_for(resource)
+      end
+    else
+      clean_up_passwords resource
+      @validatable = devise_mapping.validatable?
+      if @validatable
+        @minimum_password_length = resource_class.password_length.min
+      end
+      respond_with resource
+    end
+  end
+
+  # GET /resource/edit
+  def edit
+    render :edit
+  end
+
+  # PUT /resource
+  # We need to use a copy of the resource because we don't want to change
+  # the current user in place.
+  def update
+    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)
+
+    resource_updated = update_resource(resource, account_update_params)
+    yield resource if block_given?
+    if resource_updated
+      if is_flashing_format?
+        flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
+          :update_needs_confirmation : :updated
+        set_flash_message :notice, flash_key
+      end
+      sign_in resource_name, resource, bypass: true
+      respond_with resource, location: after_update_path_for(resource)
+    else
+      clean_up_passwords resource
+      respond_with resource
+    end
+  end
+
+  # DELETE /resource
+  def destroy
+    resource.destroy
+    Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
+    set_flash_message :notice, :destroyed if is_flashing_format?
+    yield resource if block_given?
+    respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }
+  end
+
+  # GET /resource/cancel
+  # Forces the session data which is usually expired after sign
+  # in to be expired now. This is useful if the user wants to
+  # cancel oauth signing in/up in the middle of the process,
+  # removing all OAuth session data.
+  def cancel
+    expire_data_after_sign_in!
+    redirect_to new_registration_path(resource_name)
+  end
+
+  protected
+
+  def update_needs_confirmation?(resource, previous)
+    resource.respond_to?(:pending_reconfirmation?) &&
+      resource.pending_reconfirmation? &&
+      previous != resource.unconfirmed_email
+  end
+
+  # By default we want to require a password checks on update.
+  # You can overwrite this method in your own RegistrationsController.
+  def update_resource(resource, params)
+    resource.update_with_password(params)
+  end
+
+  # 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)
+  end
+
+  # Signs in a user on sign up. You can overwrite this method in your own
+  # RegistrationsController.
+  def sign_up(resource_name, resource)
+    sign_in(resource_name, resource)
+  end
+
+  # The path used after sign up. You need to overwrite this method
+  # in your own RegistrationsController.
+  def after_sign_up_path_for(resource)
+    after_sign_in_path_for(resource)
+  end
+
+  # The path used after sign up for inactive accounts. You need to overwrite
+  # this method in your own RegistrationsController.
+  def after_inactive_sign_up_path_for(resource)
+    scope = Devise::Mapping.find_scope!(resource)
+    router_name = Devise.mappings[scope].router_name
+    context = router_name ? send(router_name) : self
+    context.respond_to?(:root_path) ? context.root_path : "/"
+  end
+
+  # The default url to be used after updating a resource. You need to overwrite
+  # this method in your own RegistrationsController.
+  def after_update_path_for(resource)
+    signed_in_root_path(resource)
+  end
+
+  # Authenticates the current scope and gets the current resource from the session.
+  def authenticate_scope!
+    send(:"authenticate_#{resource_name}!", force: true)
+    self.resource = send(:"current_#{resource_name}")
+  end
+
+  def sign_up_params
+    devise_parameter_sanitizer.sanitize(:sign_up)
+  end
+
+  def account_update_params
+    devise_parameter_sanitizer.sanitize(:account_update)
+  end
+end
diff --git a/app/controllers/devise/sessions_controller.rb b/app/controllers/devise/sessions_controller.rb
new file mode 100644
index 0000000..4a5497a
--- /dev/null
+++ b/app/controllers/devise/sessions_controller.rb
@@ -0,0 +1,76 @@
+class Devise::SessionsController < DeviseController
+  prepend_before_filter :require_no_authentication, only: [ :new, :create ]
+  prepend_before_filter :allow_params_authentication!, only: :create
+  prepend_before_filter :verify_signed_out_user, only: :destroy
+  prepend_before_filter only: [ :create, :destroy ] { request.env["devise.skip_timeout"] = true }
+
+  # GET /resource/sign_in
+  def new
+    self.resource = resource_class.new(sign_in_params)
+    clean_up_passwords(resource)
+    respond_with(resource, serialize_options(resource))
+  end
+
+  # POST /resource/sign_in
+  def create
+    self.resource = warden.authenticate!(auth_options)
+    set_flash_message(:notice, :signed_in) if is_flashing_format?
+    sign_in(resource_name, resource)
+    yield resource if block_given?
+    respond_with resource, location: after_sign_in_path_for(resource)
+  end
+
+  # DELETE /resource/sign_out
+  def destroy
+    signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))
+    set_flash_message :notice, :signed_out if signed_out && is_flashing_format?
+    yield if block_given?
+    respond_to_on_destroy
+  end
+
+  protected
+
+  def sign_in_params
+    devise_parameter_sanitizer.sanitize(:sign_in)
+  end
+
+  def serialize_options(resource)
+    methods = resource_class.authentication_keys.dup
+    methods = methods.keys if methods.is_a?(Hash)
+    methods << :password if resource.respond_to?(:password)
+    { methods: methods, only: [:password] }
+  end
+
+  def auth_options
+    { scope: resource_name, recall: "#{controller_path}#new" }
+  end
+
+  private
+
+  # Check if there is no signed in user before doing the sign out.
+  #
+  # If there is no signed in user, it will set the flash message and redirect
+  # to the after_sign_out path.
+  def verify_signed_out_user
+    if all_signed_out?
+      set_flash_message :notice, :already_signed_out if is_flashing_format?
+
+      respond_to_on_destroy
+    end
+  end
+
+  def all_signed_out?
+    users = Devise.mappings.keys.map { |s| warden.user(scope: s, run_callbacks: false) }
+
+    users.all?(&:blank?)
+  end
+
+  def respond_to_on_destroy
+    # We actually need to hardcode this as Rails default responder doesn't
+    # support returning empty response on GET request
+    respond_to do |format|
+      format.all { head :no_content }
+      format.any(*navigational_formats) { redirect_to after_sign_out_path_for(resource_name) }
+    end
+  end
+end
diff --git a/app/controllers/devise/unlocks_controller.rb b/app/controllers/devise/unlocks_controller.rb
new file mode 100644
index 0000000..903dcdb
--- /dev/null
+++ b/app/controllers/devise/unlocks_controller.rb
@@ -0,0 +1,46 @@
+class Devise::UnlocksController < DeviseController
+  prepend_before_filter :require_no_authentication
+
+  # GET /resource/unlock/new
+  def new
+    self.resource = resource_class.new
+  end
+
+  # POST /resource/unlock
+  def create
+    self.resource = resource_class.send_unlock_instructions(resource_params)
+    yield resource if block_given?
+
+    if successfully_sent?(resource)
+      respond_with({}, location: after_sending_unlock_instructions_path_for(resource))
+    else
+      respond_with(resource)
+    end
+  end
+
+  # GET /resource/unlock?unlock_token=abcdef
+  def show
+    self.resource = resource_class.unlock_access_by_token(params[:unlock_token])
+    yield resource if block_given?
+
+    if resource.errors.empty?
+      set_flash_message :notice, :unlocked if is_flashing_format?
+      respond_with_navigational(resource){ redirect_to after_unlock_path_for(resource) }
+    else
+      respond_with_navigational(resource.errors, status: :unprocessable_entity){ render :new }
+    end
+  end
+
+  protected
+
+    # The path used after sending unlock password instructions
+    def after_sending_unlock_instructions_path_for(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)  if is_navigational_format?
+    end
+
+end
diff --git a/app/controllers/devise_controller.rb b/app/controllers/devise_controller.rb
new file mode 100644
index 0000000..7cdd0f7
--- /dev/null
+++ b/app/controllers/devise_controller.rb
@@ -0,0 +1,176 @@
+# All Devise controllers are inherited from here.
+class DeviseController < Devise.parent_controller.constantize
+  include Devise::Controllers::ScopedViews
+
+  helper DeviseHelper
+
+  helpers = %w(resource scope_name resource_name signed_in_resource
+               resource_class resource_params devise_mapping)
+  hide_action(*helpers)
+  helper_method(*helpers)
+
+  prepend_before_filter :assert_is_devise_resource!
+  respond_to :html if mimes_for_respond_to.empty?
+
+  # Gets the actual resource stored in the instance variable
+  def resource
+    instance_variable_get(:"@#{resource_name}")
+  end
+
+  # Proxy to devise map name
+  def resource_name
+    devise_mapping.name
+  end
+  alias :scope_name :resource_name
+
+  # Proxy to devise map class
+  def resource_class
+    devise_mapping.to
+  end
+
+  # Returns a signed in resource from session (if one exists)
+  def signed_in_resource
+    warden.authenticate(scope: resource_name)
+  end
+
+  # Attempt to find the mapped route for devise based on request path
+  def devise_mapping
+    @devise_mapping ||= request.env["devise.mapping"]
+  end
+
+  # Override prefixes to consider the scoped view.
+  # Notice we need to check for the request due to a bug in
+  # Action Controller tests that forces _prefixes to be
+  # loaded before even having a request object.
+  def _prefixes #:nodoc:
+    @_prefixes ||= if self.class.scoped_views? && request && devise_mapping
+      ["#{devise_mapping.scoped_path}/#{controller_name}"] + super
+    else
+      super
+    end
+  end
+
+  hide_action :_prefixes
+
+  protected
+
+  # Checks whether it's a devise mapped resource or not.
+  def assert_is_devise_resource! #:nodoc:
+    unknown_action! <<-MESSAGE unless devise_mapping
+Could not find devise mapping for path #{request.fullpath.inspect}.
+This may happen for two reasons:
+
+1) You forgot to wrap your route inside the scope block. For example:
+
+  devise_scope :user do
+    get "/some/route" => "some_devise_controller"
+  end
+
+2) You are testing a Devise controller bypassing the router.
+   If so, you can explicitly tell Devise which mapping to use:
+
+   @request.env["devise.mapping"] = Devise.mappings[:user]
+
+MESSAGE
+  end
+
+  # Returns real navigational formats which are supported by Rails
+  def navigational_formats
+    @navigational_formats ||= Devise.navigational_formats.select { |format| Mime::EXTENSION_LOOKUP[format.to_s] }
+  end
+
+  def unknown_action!(msg)
+    logger.debug "[Devise] #{msg}" if logger
+    raise AbstractController::ActionNotFound, msg
+  end
+
+  # Sets the resource creating an instance variable
+  def resource=(new_resource)
+    instance_variable_set(:"@#{resource_name}", new_resource)
+  end
+
+  # Helper for use in before_filters where no authentication is required.
+  #
+  # Example:
+  #   before_filter :require_no_authentication, only: :new
+  def require_no_authentication
+    assert_is_devise_resource!
+    return unless is_navigational_format?
+    no_input = devise_mapping.no_input_strategies
+
+    authenticated = if no_input.present?
+      args = no_input.dup.push scope: resource_name
+      warden.authenticate?(*args)
+    else
+      warden.authenticated?(resource_name)
+    end
+
+    if authenticated && resource = warden.user(resource_name)
+      flash[:alert] = I18n.t("devise.failure.already_authenticated")
+      redirect_to after_sign_in_path_for(resource)
+    end
+  end
+
+  # Helper for use after calling send_*_instructions methods on a resource.
+  # If we are in paranoid mode, we always act as if the resource was valid
+  # and instructions were sent.
+  def successfully_sent?(resource)
+    notice = if Devise.paranoid
+      resource.errors.clear
+      :send_paranoid_instructions
+    elsif resource.errors.empty?
+      :send_instructions
+    end
+
+    if notice
+      set_flash_message :notice, notice if is_flashing_format?
+      true
+    end
+  end
+
+  # Sets the flash message with :key, using I18n. By default you are able
+  # to setup your messages using specific resource scope, and if no one is
+  # found we look to default scope.
+  # Example (i18n locale file):
+  #
+  #   en:
+  #     devise:
+  #       passwords:
+  #         #default_scope_messages - only if resource_scope is not found
+  #         user:
+  #           #resource_scope_messages
+  #
+  # Please refer to README or en.yml locale file to check what messages are
+  # available.
+  def set_flash_message(key, kind, options = {})
+    message = find_message(kind, options)
+    flash[key] = message if message.present?
+  end
+
+  def devise_i18n_options(options)
+    options
+  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)
+    I18n.t("#{options[:resource_name]}.#{kind}", options)
+  end
+
+  def clean_up_passwords(object)
+    object.clean_up_passwords if object.respond_to?(:clean_up_passwords)
+  end
+
+  def respond_with_navigational(*args, &block)
+    respond_with(*args) do |format|
+      format.any(*navigational_formats, &block)
+    end
+  end
+
+  def resource_params
+    params.fetch(resource_name, {})
+  end
+end
diff --git a/app/helpers/devise_helper.rb b/app/helpers/devise_helper.rb
new file mode 100644
index 0000000..f2d0726
--- /dev/null
+++ b/app/helpers/devise_helper.rb
@@ -0,0 +1,25 @@
+module DeviseHelper
+  # A simple way to show error messages for the current devise resource. If you need
+  # to customize this method, you can either overwrite it in your application helpers or
+  # copy the views to your application.
+  #
+  # This method is intended to stay simple and it is unlikely that we are going to change
+  # it to add more behavior or options.
+  def devise_error_messages!
+    return "" if resource.errors.empty?
+
+    messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
+    sentence = I18n.t("errors.messages.not_saved",
+                      count: resource.errors.count,
+                      resource: resource.class.model_name.human.downcase)
+
+    html = <<-HTML
+    <div id="error_explanation">
+      <h2>#{sentence}</h2>
+      <ul>#{messages}</ul>
+    </div>
+    HTML
+
+    html.html_safe
+  end
+end
diff --git a/app/mailers/devise/mailer.rb b/app/mailers/devise/mailer.rb
new file mode 100644
index 0000000..e069eef
--- /dev/null
+++ b/app/mailers/devise/mailer.rb
@@ -0,0 +1,20 @@
+if defined?(ActionMailer)
+  class Devise::Mailer < Devise.parent_mailer.constantize
+    include Devise::Mailers::Helpers
+
+    def confirmation_instructions(record, token, opts={})
+      @token = token
+      devise_mail(record, :confirmation_instructions, opts)
+    end
+
+    def reset_password_instructions(record, token, opts={})
+      @token = token
+      devise_mail(record, :reset_password_instructions, opts)
+    end
+
+    def unlock_instructions(record, token, opts={})
+      @token = token
+      devise_mail(record, :unlock_instructions, opts)
+    end
+  end
+end
diff --git a/app/views/devise/confirmations/new.html.erb b/app/views/devise/confirmations/new.html.erb
new file mode 100644
index 0000000..65ba288
--- /dev/null
+++ b/app/views/devise/confirmations/new.html.erb
@@ -0,0 +1,12 @@
+<h2>Resend confirmation instructions</h2>
+
+<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %>
+  <%= devise_error_messages! %>
+
+  <div><%= f.label :email %><br />
+  <%= f.email_field :email, autofocus: true %></div>
+
+  <div><%= f.submit "Resend confirmation instructions" %></div>
+<% end %>
+
+<%= render "devise/shared/links" %>
diff --git a/app/views/devise/mailer/confirmation_instructions.html.erb b/app/views/devise/mailer/confirmation_instructions.html.erb
new file mode 100644
index 0000000..dc55f64
--- /dev/null
+++ b/app/views/devise/mailer/confirmation_instructions.html.erb
@@ -0,0 +1,5 @@
+<p>Welcome <%= @email %>!</p>
+
+<p>You can confirm your account email through the link below:</p>
+
+<p><%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %></p>
diff --git a/app/views/devise/mailer/reset_password_instructions.html.erb b/app/views/devise/mailer/reset_password_instructions.html.erb
new file mode 100644
index 0000000..f667dc1
--- /dev/null
+++ b/app/views/devise/mailer/reset_password_instructions.html.erb
@@ -0,0 +1,8 @@
+<p>Hello <%= @resource.email %>!</p>
+
+<p>Someone has requested a link to change your password. You can do this through the link below.</p>
+
+<p><%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %></p>
+
+<p>If you didn't request this, please ignore this email.</p>
+<p>Your password won't change until you access the link above and create a new one.</p>
diff --git a/app/views/devise/mailer/unlock_instructions.html.erb b/app/views/devise/mailer/unlock_instructions.html.erb
new file mode 100644
index 0000000..41e148b
--- /dev/null
+++ b/app/views/devise/mailer/unlock_instructions.html.erb
@@ -0,0 +1,7 @@
+<p>Hello <%= @resource.email %>!</p>
+
+<p>Your account has been locked due to an excessive number of unsuccessful sign in attempts.</p>
+
+<p>Click the link below to unlock your account:</p>
+
+<p><%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %></p>
diff --git a/app/views/devise/passwords/edit.html.erb b/app/views/devise/passwords/edit.html.erb
new file mode 100644
index 0000000..5535098
--- /dev/null
+++ b/app/views/devise/passwords/edit.html.erb
@@ -0,0 +1,16 @@
+<h2>Change your password</h2>
+
+<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %>
+  <%= devise_error_messages! %>
+  <%= f.hidden_field :reset_password_token %>
+
+  <div><%= f.label :password, "New password" %><br />
+    <%= f.password_field :password, autofocus: true, autocomplete: "off" %></div>
+
+  <div><%= f.label :password_confirmation, "Confirm new password" %><br />
+    <%= f.password_field :password_confirmation, autocomplete: "off" %></div>
+
+  <div><%= f.submit "Change my password" %></div>
+<% end %>
+
+<%= render "devise/shared/links" %>
diff --git a/app/views/devise/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb
new file mode 100644
index 0000000..ea1d46e
--- /dev/null
+++ b/app/views/devise/passwords/new.html.erb
@@ -0,0 +1,12 @@
+<h2>Forgot your password?</h2>
+
+<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %>
+  <%= devise_error_messages! %>
+
+  <div><%= f.label :email %><br />
+  <%= f.email_field :email, autofocus: true %></div>
+
+  <div><%= f.submit "Send me reset password instructions" %></div>
+<% end %>
+
+<%= render "devise/shared/links" %>
diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb
new file mode 100644
index 0000000..808d62c
--- /dev/null
+++ b/app/views/devise/registrations/edit.html.erb
@@ -0,0 +1,29 @@
+<h2>Edit <%= resource_name.to_s.humanize %></h2>
+
+<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
+  <%= devise_error_messages! %>
+
+  <div><%= f.label :email %><br />
+  <%= f.email_field :email, autofocus: true %></div>
+
+  <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
+    <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
+  <% end %>
+
+  <div><%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
+    <%= f.password_field :password, autocomplete: "off" %></div>
+
+  <div><%= f.label :password_confirmation %><br />
+    <%= f.password_field :password_confirmation, autocomplete: "off" %></div>
+
+  <div><%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
+    <%= f.password_field :current_password, autocomplete: "off" %></div>
+
+  <div><%= f.submit "Update" %></div>
+<% end %>
+
+<h3>Cancel my account</h3>
+
+<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>
+
+<%= link_to "Back", :back %>
diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb
new file mode 100644
index 0000000..4183042
--- /dev/null
+++ b/app/views/devise/registrations/new.html.erb
@@ -0,0 +1,18 @@
+<h2>Sign up</h2>
+
+<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
+  <%= devise_error_messages! %>
+
+  <div><%= f.label :email %><br />
+  <%= f.email_field :email, autofocus: true %></div>
+
+  <div><%= f.label :password %> <% if @validatable %><i>(<%= @minimum_password_length %> characters minimum)</i><% end %><br />
+    <%= f.password_field :password, autocomplete: "off" %></div>
+
+  <div><%= f.label :password_confirmation %><br />
+    <%= f.password_field :password_confirmation, autocomplete: "off" %></div>
+
+  <div><%= f.submit "Sign up" %></div>
+<% end %>
+
+<%= render "devise/shared/links" %>
diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb
new file mode 100644
index 0000000..f24d7df
--- /dev/null
+++ b/app/views/devise/sessions/new.html.erb
@@ -0,0 +1,17 @@
+<h2>Log in</h2>
+
+<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
+  <div><%= f.label :email %><br />
+  <%= f.email_field :email, autofocus: true %></div>
+
+  <div><%= f.label :password %><br />
+    <%= f.password_field :password, autocomplete: "off" %></div>
+
+  <% if devise_mapping.rememberable? -%>
+    <div><%= f.check_box :remember_me %> <%= f.label :remember_me %></div>
+  <% end -%>
+
+  <div><%= f.submit "Log in" %></div>
+<% end %>
+
+<%= render "devise/shared/links" %>
diff --git a/app/views/devise/shared/_links.html.erb b/app/views/devise/shared/_links.html.erb
new file mode 100644
index 0000000..cd795ad
--- /dev/null
+++ b/app/views/devise/shared/_links.html.erb
@@ -0,0 +1,25 @@
+<%- if controller_name != 'sessions' %>
+  <%= link_to "Log in", new_session_path(resource_name) %><br />
+<% end -%>
+
+<%- if devise_mapping.registerable? && controller_name != 'registrations' %>
+  <%= link_to "Sign up", new_registration_path(resource_name) %><br />
+<% end -%>
+
+<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %>
+  <%= link_to "Forgot your password?", new_password_path(resource_name) %><br />
+<% end -%>
+
+<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %>
+  <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %><br />
+<% end -%>
+
+<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %>
+  <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %><br />
+<% end -%>
+
+<%- if devise_mapping.omniauthable? %>
+  <%- resource_class.omniauth_providers.each do |provider| %>
+    <%= link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider) %><br />
+  <% end -%>
+<% end -%>
diff --git a/app/views/devise/unlocks/new.html.erb b/app/views/devise/unlocks/new.html.erb
new file mode 100644
index 0000000..6fb5612
--- /dev/null
+++ b/app/views/devise/unlocks/new.html.erb
@@ -0,0 +1,12 @@
+<h2>Resend unlock instructions</h2>
+
+<%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %>
+  <%= devise_error_messages! %>
+
+  <div><%= f.label :email %><br />
+  <%= f.email_field :email, autofocus: true %></div>
+
+  <div><%= f.submit "Resend unlock instructions" %></div>
+<% end %>
+
+<%= render "devise/shared/links" %>
diff --git a/config/locales/en.yml b/config/locales/en.yml
new file mode 100644
index 0000000..26a10f2
--- /dev/null
+++ b/config/locales/en.yml
@@ -0,0 +1,60 @@
+# Additional translations at https://github.com/plataformatec/devise/wiki/I18n
+
+en:
+  devise:
+    confirmations:
+      confirmed: "Your email address has been successfully confirmed."
+      send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes."
+      send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes."
+    failure:
+      already_authenticated: "You are already signed in."
+      inactive: "Your account is not activated yet."
+      invalid: "Invalid %{authentication_keys} or password."
+      locked: "Your account is locked."
+      last_attempt: "You have one more attempt before your account is locked."
+      not_found_in_database: "Invalid %{authentication_keys} 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 email address 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 on 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 has been changed successfully. You are now signed in."
+      updated_not_active: "Your password has been changed successfully."
+    registrations:
+      destroyed: "Bye! Your account has been 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 follow 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 follow the confirm link to confirm your new email address."
+      updated: "Your account has been updated successfully."
+    sessions:
+      signed_in: "Signed in successfully."
+      signed_out: "Signed out successfully."
+      already_signed_out: "Signed out successfully."
+    unlocks:
+      send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes."
+      send_paranoid_instructions: "If your account exists, you will receive an email with instructions for 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"
+      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:"
diff --git a/devise.gemspec b/devise.gemspec
new file mode 100644
index 0000000..73b8107
--- /dev/null
+++ b/devise.gemspec
@@ -0,0 +1,28 @@
+# -*- encoding: utf-8 -*-
+$:.push File.expand_path("../lib", __FILE__)
+require "devise/version"
+
+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 at plataformatec.com.br"
+  s.homepage    = "https://github.com/plataformatec/devise"
+  s.description = "Flexible authentication solution for Rails with Warden"
+  s.authors     = ['José Valim', 'Carlos Antônio']
+
+  s.rubyforge_project = "devise"
+
+  s.files         = `git ls-files`.split("\n")
+  s.test_files    = `git ls-files -- test/*`.split("\n")
+  s.require_paths = ["lib"]
+
+  s.add_dependency("warden", "~> 1.2.3")
+  s.add_dependency("orm_adapter", "~> 0.1")
+  s.add_dependency("bcrypt", "~> 3.0")
+  s.add_dependency("thread_safe", "~> 0.1")
+  s.add_dependency("railties", ">= 3.2.6", "< 5")
+  s.add_dependency("responders")
+end
diff --git a/devise.png b/devise.png
new file mode 100644
index 0000000..d803835
Binary files /dev/null and b/devise.png differ
diff --git a/gemfiles/Gemfile.rails-3.2-stable b/gemfiles/Gemfile.rails-3.2-stable
new file mode 100644
index 0000000..99713e0
--- /dev/null
+++ b/gemfiles/Gemfile.rails-3.2-stable
@@ -0,0 +1,29 @@
+source "https://rubygems.org"
+
+gemspec path: '..'
+
+gem "rails", github: 'rails/rails', branch: '3-2-stable'
+gem "omniauth", "~> 1.2.0"
+gem "omniauth-oauth2", "~> 1.1.0"
+gem "rdoc"
+
+group :test do
+  gem "omniauth-facebook"
+  gem "omniauth-openid", "~> 1.0.1"
+  gem "webrat", "0.7.3", require: false
+  gem "mocha", "~> 1.1", require: false
+end
+
+platforms :jruby do
+  gem "activerecord-jdbc-adapter"
+  gem "activerecord-jdbcsqlite3-adapter"
+  gem "jruby-openssl"
+end
+
+platforms :ruby do
+  gem "sqlite3"
+end
+
+group :mongoid do
+  gem "mongoid", "~> 3.0"
+end
diff --git a/gemfiles/Gemfile.rails-3.2-stable.lock b/gemfiles/Gemfile.rails-3.2-stable.lock
new file mode 100644
index 0000000..174922a
--- /dev/null
+++ b/gemfiles/Gemfile.rails-3.2-stable.lock
@@ -0,0 +1,169 @@
+GIT
+  remote: git://github.com/rails/rails.git
+  revision: 11fd052aa815ae0255ea5b2463e88138fb3fec61
+  branch: 3-2-stable
+  specs:
+    actionmailer (3.2.19)
+      actionpack (= 3.2.19)
+      mail (~> 2.5.4)
+    actionpack (3.2.19)
+      activemodel (= 3.2.19)
+      activesupport (= 3.2.19)
+      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.19)
+      activesupport (= 3.2.19)
+      builder (~> 3.0.0)
+    activerecord (3.2.19)
+      activemodel (= 3.2.19)
+      activesupport (= 3.2.19)
+      arel (~> 3.0.2)
+      tzinfo (~> 0.3.29)
+    activeresource (3.2.19)
+      activemodel (= 3.2.19)
+      activesupport (= 3.2.19)
+    activesupport (3.2.19)
+      i18n (~> 0.6, >= 0.6.4)
+      multi_json (~> 1.0)
+    rails (3.2.19)
+      actionmailer (= 3.2.19)
+      actionpack (= 3.2.19)
+      activerecord (= 3.2.19)
+      activeresource (= 3.2.19)
+      activesupport (= 3.2.19)
+      bundler (~> 1.0)
+      railties (= 3.2.19)
+    railties (3.2.19)
+      actionpack (= 3.2.19)
+      activesupport (= 3.2.19)
+      rack-ssl (~> 1.3.2)
+      rake (>= 0.8.7)
+      rdoc (~> 3.4)
+      thor (>= 0.14.6, < 2.0)
+
+PATH
+  remote: ..
+  specs:
+    devise (3.4.0)
+      bcrypt (~> 3.0)
+      orm_adapter (~> 0.1)
+      railties (>= 3.2.6, < 5)
+      responders
+      thread_safe (~> 0.1)
+      warden (~> 1.2.3)
+
+GEM
+  remote: https://rubygems.org/
+  specs:
+    arel (3.0.3)
+    bcrypt (3.1.7)
+    builder (3.0.4)
+    erubis (2.7.0)
+    faraday (0.9.0)
+      multipart-post (>= 1.2, < 3)
+    hashie (3.2.0)
+    hike (1.2.3)
+    i18n (0.6.11)
+    journey (1.0.4)
+    json (1.8.1)
+    jwt (1.0.0)
+    mail (2.5.4)
+      mime-types (~> 1.16)
+      treetop (~> 1.4.8)
+    metaclass (0.0.4)
+    mime-types (1.25.1)
+    mini_portile (0.6.0)
+    mocha (1.1.0)
+      metaclass (~> 0.0.1)
+    mongoid (3.1.6)
+      activemodel (~> 3.2)
+      moped (~> 1.4)
+      origin (~> 1.0)
+      tzinfo (~> 0.3.29)
+    moped (1.5.2)
+    multi_json (1.10.1)
+    multi_xml (0.5.5)
+    multipart-post (2.0.0)
+    nokogiri (1.6.3.1)
+      mini_portile (= 0.6.0)
+    oauth2 (0.9.4)
+      faraday (>= 0.8, < 0.10)
+      jwt (~> 1.0)
+      multi_json (~> 1.3)
+      multi_xml (~> 0.5)
+      rack (~> 1.2)
+    omniauth (1.2.2)
+      hashie (>= 1.2, < 4)
+      rack (~> 1.0)
+    omniauth-facebook (1.6.0)
+      omniauth-oauth2 (~> 1.1)
+    omniauth-oauth2 (1.1.2)
+      faraday (>= 0.8, < 0.10)
+      multi_json (~> 1.3)
+      oauth2 (~> 0.9.3)
+      omniauth (~> 1.2)
+    omniauth-openid (1.0.1)
+      omniauth (~> 1.0)
+      rack-openid (~> 1.3.1)
+    origin (1.1.0)
+    orm_adapter (0.5.0)
+    polyglot (0.3.5)
+    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.4)
+      rack
+    rack-test (0.6.2)
+      rack (>= 1.0)
+    rake (10.3.2)
+    rdoc (3.12.2)
+      json (~> 1.4)
+    responders (1.1.1)
+      railties (>= 3.2, < 4.2)
+    ruby-openid (2.5.0)
+    sprockets (2.2.2)
+      hike (~> 1.2)
+      multi_json (~> 1.0)
+      rack (~> 1.0)
+      tilt (~> 1.1, != 1.3.0)
+    sqlite3 (1.3.9)
+    thor (0.19.1)
+    thread_safe (0.3.4)
+    tilt (1.4.1)
+    treetop (1.4.15)
+      polyglot
+      polyglot (>= 0.3.1)
+    tzinfo (0.3.41)
+    warden (1.2.3)
+      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 (~> 1.1)
+  mongoid (~> 3.0)
+  omniauth (~> 1.2.0)
+  omniauth-facebook
+  omniauth-oauth2 (~> 1.1.0)
+  omniauth-openid (~> 1.0.1)
+  rails!
+  rdoc
+  sqlite3
+  webrat (= 0.7.3)
diff --git a/gemfiles/Gemfile.rails-4.0-stable b/gemfiles/Gemfile.rails-4.0-stable
new file mode 100644
index 0000000..66ab20d
--- /dev/null
+++ b/gemfiles/Gemfile.rails-4.0-stable
@@ -0,0 +1,29 @@
+source "https://rubygems.org"
+
+gemspec path: '..'
+
+gem "rails", github: 'rails/rails', branch: '4-0-stable'
+gem "omniauth", "~> 1.2.0"
+gem "omniauth-oauth2", "~> 1.1.0"
+gem "rdoc"
+
+group :test do
+  gem "omniauth-facebook"
+  gem "omniauth-openid", "~> 1.0.1"
+  gem "webrat", "0.7.3", require: false
+  gem "mocha", "~> 1.1", require: false
+end
+
+platforms :jruby do
+  gem "activerecord-jdbc-adapter"
+  gem "activerecord-jdbcsqlite3-adapter"
+  gem "jruby-openssl"
+end
+
+platforms :ruby do
+  gem "sqlite3"
+end
+
+group :mongoid do
+  gem "mongoid", "~> 4.0.0"
+end
diff --git a/gemfiles/Gemfile.rails-4.0-stable.lock b/gemfiles/Gemfile.rails-4.0-stable.lock
new file mode 100644
index 0000000..4cfa4ff
--- /dev/null
+++ b/gemfiles/Gemfile.rails-4.0-stable.lock
@@ -0,0 +1,165 @@
+GIT
+  remote: git://github.com/rails/rails.git
+  revision: 2d8886e05104316273a0f95dfbcd171d3b12678b
+  branch: 4-0-stable
+  specs:
+    actionmailer (4.0.9)
+      actionpack (= 4.0.9)
+      mail (~> 2.5, >= 2.5.4)
+    actionpack (4.0.9)
+      activesupport (= 4.0.9)
+      builder (~> 3.1.0)
+      erubis (~> 2.7.0)
+      rack (~> 1.5.2)
+      rack-test (~> 0.6.2)
+    activemodel (4.0.9)
+      activesupport (= 4.0.9)
+      builder (~> 3.1.0)
+    activerecord (4.0.9)
+      activemodel (= 4.0.9)
+      activerecord-deprecated_finders (~> 1.0.2)
+      activesupport (= 4.0.9)
+      arel (~> 4.0.0)
+    activesupport (4.0.9)
+      i18n (~> 0.6, >= 0.6.9)
+      minitest (~> 4.2)
+      multi_json (~> 1.3)
+      thread_safe (~> 0.1)
+      tzinfo (~> 0.3.37)
+    rails (4.0.9)
+      actionmailer (= 4.0.9)
+      actionpack (= 4.0.9)
+      activerecord (= 4.0.9)
+      activesupport (= 4.0.9)
+      bundler (>= 1.3.0, < 2.0)
+      railties (= 4.0.9)
+      sprockets-rails (~> 2.0)
+    railties (4.0.9)
+      actionpack (= 4.0.9)
+      activesupport (= 4.0.9)
+      rake (>= 0.8.7)
+      thor (>= 0.18.1, < 2.0)
+
+PATH
+  remote: ..
+  specs:
+    devise (3.4.0)
+      bcrypt (~> 3.0)
+      orm_adapter (~> 0.1)
+      railties (>= 3.2.6, < 5)
+      responders
+      thread_safe (~> 0.1)
+      warden (~> 1.2.3)
+
+GEM
+  remote: https://rubygems.org/
+  specs:
+    activerecord-deprecated_finders (1.0.3)
+    arel (4.0.2)
+    bcrypt (3.1.7)
+    bson (2.3.0)
+    builder (3.1.4)
+    connection_pool (2.0.0)
+    erubis (2.7.0)
+    faraday (0.9.0)
+      multipart-post (>= 1.2, < 3)
+    hashie (3.2.0)
+    hike (1.2.3)
+    i18n (0.6.11)
+    json (1.8.1)
+    jwt (1.0.0)
+    mail (2.6.1)
+      mime-types (>= 1.16, < 3)
+    metaclass (0.0.4)
+    mime-types (2.3)
+    mini_portile (0.6.0)
+    minitest (4.7.5)
+    mocha (1.1.0)
+      metaclass (~> 0.0.1)
+    mongoid (4.0.0)
+      activemodel (~> 4.0)
+      moped (~> 2.0.0)
+      origin (~> 2.1)
+      tzinfo (>= 0.3.37)
+    moped (2.0.0)
+      bson (~> 2.2)
+      connection_pool (~> 2.0)
+      optionable (~> 0.2.0)
+    multi_json (1.10.1)
+    multi_xml (0.5.5)
+    multipart-post (2.0.0)
+    nokogiri (1.6.3.1)
+      mini_portile (= 0.6.0)
+    oauth2 (0.9.4)
+      faraday (>= 0.8, < 0.10)
+      jwt (~> 1.0)
+      multi_json (~> 1.3)
+      multi_xml (~> 0.5)
+      rack (~> 1.2)
+    omniauth (1.2.2)
+      hashie (>= 1.2, < 4)
+      rack (~> 1.0)
+    omniauth-facebook (1.6.0)
+      omniauth-oauth2 (~> 1.1)
+    omniauth-oauth2 (1.1.2)
+      faraday (>= 0.8, < 0.10)
+      multi_json (~> 1.3)
+      oauth2 (~> 0.9.3)
+      omniauth (~> 1.2)
+    omniauth-openid (1.0.1)
+      omniauth (~> 1.0)
+      rack-openid (~> 1.3.1)
+    optionable (0.2.0)
+    origin (2.1.1)
+    orm_adapter (0.5.0)
+    rack (1.5.2)
+    rack-openid (1.3.1)
+      rack (>= 1.1.0)
+      ruby-openid (>= 2.1.8)
+    rack-test (0.6.2)
+      rack (>= 1.0)
+    rake (10.3.2)
+    rdoc (4.1.1)
+      json (~> 1.4)
+    responders (1.1.1)
+      railties (>= 3.2, < 4.2)
+    ruby-openid (2.5.0)
+    sprockets (2.12.1)
+      hike (~> 1.2)
+      multi_json (~> 1.0)
+      rack (~> 1.0)
+      tilt (~> 1.1, != 1.3.0)
+    sprockets-rails (2.1.3)
+      actionpack (>= 3.0)
+      activesupport (>= 3.0)
+      sprockets (~> 2.8)
+    sqlite3 (1.3.9)
+    thor (0.19.1)
+    thread_safe (0.3.4)
+    tilt (1.4.1)
+    tzinfo (0.3.41)
+    warden (1.2.3)
+      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 (~> 1.1)
+  mongoid (~> 4.0.0)
+  omniauth (~> 1.2.0)
+  omniauth-facebook
+  omniauth-oauth2 (~> 1.1.0)
+  omniauth-openid (~> 1.0.1)
+  rails!
+  rdoc
+  sqlite3
+  webrat (= 0.7.3)
diff --git a/gemfiles/Gemfile.rails-4.1-stable b/gemfiles/Gemfile.rails-4.1-stable
new file mode 100644
index 0000000..f4f0e37
--- /dev/null
+++ b/gemfiles/Gemfile.rails-4.1-stable
@@ -0,0 +1,29 @@
+source "https://rubygems.org"
+
+gemspec path: '..'
+
+gem "rails", github: 'rails/rails', branch: '4-1-stable'
+gem "omniauth", "~> 1.2.0"
+gem "omniauth-oauth2", "~> 1.1.0"
+gem "rdoc"
+
+group :test do
+  gem "omniauth-facebook"
+  gem "omniauth-openid", "~> 1.0.1"
+  gem "webrat", "0.7.3", require: false
+  gem "mocha", "~> 1.1", require: false
+end
+
+platforms :jruby do
+  gem "activerecord-jdbc-adapter"
+  gem "activerecord-jdbcsqlite3-adapter"
+  gem "jruby-openssl"
+end
+
+platforms :ruby do
+  gem "sqlite3"
+end
+
+group :mongoid do
+  gem "mongoid", "~> 4.0.0"
+end
diff --git a/gemfiles/Gemfile.rails-4.1-stable.lock b/gemfiles/Gemfile.rails-4.1-stable.lock
new file mode 100644
index 0000000..7bf1312
--- /dev/null
+++ b/gemfiles/Gemfile.rails-4.1-stable.lock
@@ -0,0 +1,170 @@
+GIT
+  remote: git://github.com/rails/rails.git
+  revision: 90b70cd453e6b88b2ad484861ad9913f70bd15c9
+  branch: 4-1-stable
+  specs:
+    actionmailer (4.1.5)
+      actionpack (= 4.1.5)
+      actionview (= 4.1.5)
+      mail (~> 2.5, >= 2.5.4)
+    actionpack (4.1.5)
+      actionview (= 4.1.5)
+      activesupport (= 4.1.5)
+      rack (~> 1.5.2)
+      rack-test (~> 0.6.2)
+    actionview (4.1.5)
+      activesupport (= 4.1.5)
+      builder (~> 3.1)
+      erubis (~> 2.7.0)
+    activemodel (4.1.5)
+      activesupport (= 4.1.5)
+      builder (~> 3.1)
+    activerecord (4.1.5)
+      activemodel (= 4.1.5)
+      activesupport (= 4.1.5)
+      arel (~> 5.0.0)
+    activesupport (4.1.5)
+      i18n (~> 0.6, >= 0.6.9)
+      json (~> 1.7, >= 1.7.7)
+      minitest (~> 5.1)
+      thread_safe (~> 0.1)
+      tzinfo (~> 1.1)
+    rails (4.1.5)
+      actionmailer (= 4.1.5)
+      actionpack (= 4.1.5)
+      actionview (= 4.1.5)
+      activemodel (= 4.1.5)
+      activerecord (= 4.1.5)
+      activesupport (= 4.1.5)
+      bundler (>= 1.3.0, < 2.0)
+      railties (= 4.1.5)
+      sprockets-rails (~> 2.0)
+    railties (4.1.5)
+      actionpack (= 4.1.5)
+      activesupport (= 4.1.5)
+      rake (>= 0.8.7)
+      thor (>= 0.18.1, < 2.0)
+
+PATH
+  remote: ..
+  specs:
+    devise (3.4.0)
+      bcrypt (~> 3.0)
+      orm_adapter (~> 0.1)
+      railties (>= 3.2.6, < 5)
+      responders
+      thread_safe (~> 0.1)
+      warden (~> 1.2.3)
+
+GEM
+  remote: https://rubygems.org/
+  specs:
+    arel (5.0.1.20140414130214)
+    bcrypt (3.1.7)
+    bson (2.3.0)
+    builder (3.2.2)
+    connection_pool (2.0.0)
+    erubis (2.7.0)
+    faraday (0.9.0)
+      multipart-post (>= 1.2, < 3)
+    hashie (3.2.0)
+    hike (1.2.3)
+    i18n (0.6.11)
+    json (1.8.1)
+    jwt (1.0.0)
+    mail (2.6.1)
+      mime-types (>= 1.16, < 3)
+    metaclass (0.0.4)
+    mime-types (2.3)
+    mini_portile (0.6.0)
+    minitest (5.4.0)
+    mocha (1.1.0)
+      metaclass (~> 0.0.1)
+    mongoid (4.0.0)
+      activemodel (~> 4.0)
+      moped (~> 2.0.0)
+      origin (~> 2.1)
+      tzinfo (>= 0.3.37)
+    moped (2.0.0)
+      bson (~> 2.2)
+      connection_pool (~> 2.0)
+      optionable (~> 0.2.0)
+    multi_json (1.10.1)
+    multi_xml (0.5.5)
+    multipart-post (2.0.0)
+    nokogiri (1.6.3.1)
+      mini_portile (= 0.6.0)
+    oauth2 (0.9.4)
+      faraday (>= 0.8, < 0.10)
+      jwt (~> 1.0)
+      multi_json (~> 1.3)
+      multi_xml (~> 0.5)
+      rack (~> 1.2)
+    omniauth (1.2.2)
+      hashie (>= 1.2, < 4)
+      rack (~> 1.0)
+    omniauth-facebook (1.6.0)
+      omniauth-oauth2 (~> 1.1)
+    omniauth-oauth2 (1.1.2)
+      faraday (>= 0.8, < 0.10)
+      multi_json (~> 1.3)
+      oauth2 (~> 0.9.3)
+      omniauth (~> 1.2)
+    omniauth-openid (1.0.1)
+      omniauth (~> 1.0)
+      rack-openid (~> 1.3.1)
+    optionable (0.2.0)
+    origin (2.1.1)
+    orm_adapter (0.5.0)
+    rack (1.5.2)
+    rack-openid (1.3.1)
+      rack (>= 1.1.0)
+      ruby-openid (>= 2.1.8)
+    rack-test (0.6.2)
+      rack (>= 1.0)
+    rake (10.3.2)
+    rdoc (4.1.1)
+      json (~> 1.4)
+    responders (1.1.1)
+      railties (>= 3.2, < 4.2)
+    ruby-openid (2.5.0)
+    sprockets (2.12.1)
+      hike (~> 1.2)
+      multi_json (~> 1.0)
+      rack (~> 1.0)
+      tilt (~> 1.1, != 1.3.0)
+    sprockets-rails (2.1.3)
+      actionpack (>= 3.0)
+      activesupport (>= 3.0)
+      sprockets (~> 2.8)
+    sqlite3 (1.3.9)
+    thor (0.19.1)
+    thread_safe (0.3.4)
+    tilt (1.4.1)
+    tzinfo (1.2.2)
+      thread_safe (~> 0.1)
+    warden (1.2.3)
+      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 (~> 1.1)
+  mongoid (~> 4.0.0)
+  omniauth (~> 1.2.0)
+  omniauth-facebook
+  omniauth-oauth2 (~> 1.1.0)
+  omniauth-openid (~> 1.0.1)
+  rails!
+  rdoc
+  sqlite3
+  webrat (= 0.7.3)
diff --git a/lib/devise.rb b/lib/devise.rb
new file mode 100644
index 0000000..88c7c27
--- /dev/null
+++ b/lib/devise.rb
@@ -0,0 +1,496 @@
+require 'rails'
+require 'active_support/core_ext/numeric/time'
+require 'active_support/dependencies'
+require 'orm_adapter'
+require 'set'
+require 'securerandom'
+require 'responders'
+
+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 :TokenGenerator,     'devise/token_generator'
+
+  module Controllers
+    autoload :Helpers, 'devise/controllers/helpers'
+    autoload :Rememberable, 'devise/controllers/rememberable'
+    autoload :ScopedViews, 'devise/controllers/scoped_views'
+    autoload :SignInOut, 'devise/controllers/sign_in_out'
+    autoload :StoreLocation, 'devise/controllers/store_location'
+    autoload :UrlHelpers, 'devise/controllers/url_helpers'
+  end
+
+  module Hooks
+    autoload :Proxy, 'devise/hooks/proxy'
+  end
+
+  module Mailers
+    autoload :Helpers, 'devise/mailers/helpers'
+  end
+
+  module Strategies
+    autoload :Base, 'devise/strategies/base'
+    autoload :Authenticatable, 'devise/strategies/authenticatable'
+  end
+
+  # Constants which holds devise configuration for extensions. Those should
+  # not be modified by the "end user" (this is why they are constants).
+  ALL         = []
+  CONTROLLERS = ActiveSupport::OrderedHash.new
+  ROUTES      = ActiveSupport::OrderedHash.new
+  STRATEGIES  = ActiveSupport::OrderedHash.new
+  URL_HELPERS = ActiveSupport::OrderedHash.new
+
+  # Strategies that do not require user input.
+  NO_INPUT = []
+
+  # True values used to check params
+  TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE']
+
+  # Secret key used by the key generator
+  mattr_accessor :secret_key
+  @@secret_key = nil
+
+  [ :allow_insecure_token_lookup,
+    :allow_insecure_sign_in_after_confirmation,
+    :token_authentication_key ].each do |method|
+    class_eval <<-RUBY
+    def self.#{method}
+      ActiveSupport::Deprecation.warn "Devise.#{method} is deprecated " \
+        "and has no effect"
+    end
+
+    def self.#{method}=(val)
+      ActiveSupport::Deprecation.warn "Devise.#{method}= is deprecated " \
+        "and has no effect"
+    end
+    RUBY
+  end
+
+  # Custom domain or key for cookies. Not set by default
+  mattr_accessor :rememberable_options
+  @@rememberable_options = {}
+
+  # The number of times to encrypt password.
+  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 ]
+
+  # Request keys used when authenticating a user.
+  mattr_accessor :request_keys
+  @@request_keys = []
+
+  # Keys that should be case-insensitive.
+  mattr_accessor :case_insensitive_keys
+  @@case_insensitive_keys = [ :email ]
+
+  # Keys that should have whitespace stripped.
+  mattr_accessor :strip_whitespace_keys
+  @@strip_whitespace_keys = []
+
+  # If http authentication is enabled by default.
+  mattr_accessor :http_authenticatable
+  @@http_authenticatable = false
+
+  # If http headers should be returned for ajax requests. True by default.
+  mattr_accessor :http_authenticatable_on_xhr
+  @@http_authenticatable_on_xhr = true
+
+  # If params authenticatable is enabled by default.
+  mattr_accessor :params_authenticatable
+  @@params_authenticatable = true
+
+  # The realm used in Http Basic Authentication.
+  mattr_accessor :http_authentication_realm
+  @@http_authentication_realm = "Application"
+
+  # Email regex used to validate email formats. It simply asserts that
+  # an one (and only one) @ exists in the given string. This is mainly
+  # to give user feedback and not to assert the e-mail validity.
+  mattr_accessor :email_regexp
+  @@email_regexp = /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
+
+  # Range validation for password length
+  mattr_accessor :password_length
+  @@password_length = 6..128
+
+  # The time the user will be remembered without asking for credentials again.
+  mattr_accessor :remember_for
+  @@remember_for = 2.weeks
+
+  # If true, extends the user's remember period when remembered via cookie.
+  mattr_accessor :extend_remember_period
+  @@extend_remember_period = false
+
+  # If true, all the remember me tokens are going to be invalidated when the user signs out.
+  mattr_accessor :expire_all_remember_me_on_sign_out
+  @@expire_all_remember_me_on_sign_out = true
+
+  # 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
+
+  # Time interval the confirmation token is valid. nil = unlimited
+  mattr_accessor :confirm_within
+  @@confirm_within = nil
+
+  # Defines which key will be used when confirming an account.
+  mattr_accessor :confirmation_keys
+  @@confirmation_keys = [ :email ]
+
+  # Defines if email should be reconfirmable.
+  # False by default for backwards compatibility.
+  mattr_accessor :reconfirmable
+  @@reconfirmable = false
+
+  # Time interval to timeout the user session without activity.
+  mattr_accessor :timeout_in
+  @@timeout_in = 30.minutes
+
+  # Authentication token expiration on timeout
+  mattr_accessor :expire_auth_token_on_timeout
+  @@expire_auth_token_on_timeout = false
+
+  # Used to encrypt password. Please generate one with rake secret.
+  mattr_accessor :pepper
+  @@pepper = nil
+
+  # Scoped views. Since it relies on fallbacks to render default views, it's
+  # turned off by default.
+  mattr_accessor :scoped_views
+  @@scoped_views = false
+
+  # Defines which strategy can be used to lock an account.
+  # Values: :failed_attempts, :none
+  mattr_accessor :lock_strategy
+  @@lock_strategy = :failed_attempts
+
+  # Defines which key will be used when locking and unlocking an account
+  mattr_accessor :unlock_keys
+  @@unlock_keys = [ :email ]
+
+  # Defines which strategy can be used to unlock an account.
+  # Values: :email, :time, :both
+  mattr_accessor :unlock_strategy
+  @@unlock_strategy = :both
+
+  # Number of authentication tries before locking an account
+  mattr_accessor :maximum_attempts
+  @@maximum_attempts = 20
+
+  # Time interval to unlock the account if :time is defined as unlock_strategy.
+  mattr_accessor :unlock_in
+  @@unlock_in = 1.hour
+
+  # Defines which key will be used when recovering the password for an account
+  mattr_accessor :reset_password_keys
+  @@reset_password_keys = [ :email ]
+
+  # Time interval you can reset your password with a reset password key
+  mattr_accessor :reset_password_within
+  @@reset_password_within = 6.hours
+
+  # The default scope which is used by warden.
+  mattr_accessor :default_scope
+  @@default_scope = nil
+
+  # Address which sends Devise e-mails.
+  mattr_accessor :mailer_sender
+  @@mailer_sender = nil
+
+  # Skip session storage for the following strategies
+  mattr_accessor :skip_session_storage
+  @@skip_session_storage = []
+
+  # Which formats should be treated as navigational.
+  mattr_accessor :navigational_formats
+  @@navigational_formats = ["*/*", :html]
+
+  # When set to true, signing out a user signs out all other scopes.
+  mattr_accessor :sign_out_all_scopes
+  @@sign_out_all_scopes = true
+
+  # The default method used while signing out
+  mattr_accessor :sign_out_via
+  @@sign_out_via = :get
+
+  # The parent controller all Devise controllers inherits from.
+  # Defaults to ApplicationController. This should be set early
+  # in the initialization process and should be set to a string.
+  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 overridden by engines in order
+  # to provide custom routes.
+  mattr_accessor :router_name
+  @@router_name = nil
+
+  # Set the omniauth path prefix so it can be overridden when
+  # Devise is used in a mountable engine
+  mattr_accessor :omniauth_path_prefix
+  @@omniauth_path_prefix = nil
+
+  # Set if we should clean up the CSRF Token on authentication
+  mattr_accessor :clean_up_csrf_token_on_authentication
+  @@clean_up_csrf_token_on_authentication = true
+
+  # PRIVATE CONFIGURATION
+
+  # Store scopes mappings.
+  mattr_reader :mappings
+  @@mappings = ActiveSupport::OrderedHash.new
+
+  # Omniauth configurations.
+  mattr_reader :omniauth_configs
+  @@omniauth_configs = ActiveSupport::OrderedHash.new
+
+  # Define a set of modules that are called when a mapping is added.
+  mattr_reader :helpers
+  @@helpers = Set.new
+  @@helpers << Devise::Controllers::Helpers
+
+  # Private methods to interface with Warden.
+  mattr_accessor :warden_config
+  @@warden_config = nil
+  @@warden_config_blocks = []
+
+  # When true, enter in paranoid mode to avoid user enumeration.
+  mattr_accessor :paranoid
+  @@paranoid = false
+
+  # When true, warn user if they just used next-to-last attempt of authentication
+  mattr_accessor :last_attempt_warning
+  @@last_attempt_warning = true
+
+  # Stores the token generator
+  mattr_accessor :token_generator
+  @@token_generator = nil
+
+  # Default way to setup Devise. Run rails generate devise_install to create
+  # a fresh initializer with all configuration values.
+  def self.setup
+    yield self
+  end
+
+  class Getter
+    def initialize name
+      @name = name
+    end
+
+    def get
+      ActiveSupport::Dependencies.constantize(@name)
+    end
+  end
+
+  def self.ref(arg)
+    if defined?(ActiveSupport::Dependencies::ClassCache)
+      ActiveSupport::Dependencies::reference(arg)
+      Getter.new(arg)
+    else
+      ActiveSupport::Dependencies.ref(arg)
+    end
+  end
+
+  def self.available_router_name
+    router_name || :main_app
+  end
+
+  def self.omniauth_providers
+    omniauth_configs.keys
+  end
+
+  # Get the mailer class from the mailer reference object.
+  def self.mailer
+    @@mailer_ref.get
+  end
+
+  # Set the mailer reference object to access the mailer.
+  def self.mailer=(class_name)
+    @@mailer_ref = ref(class_name)
+  end
+  self.mailer = "Devise::Mailer"
+
+  # Small method that adds a mapping to Devise.
+  def self.add_mapping(resource, options)
+    mapping = Devise::Mapping.new(resource, options)
+    @@mappings[mapping.name] = mapping
+    @@default_scope ||= mapping.name
+    @@helpers.each { |h| h.define_helpers(mapping) }
+    mapping
+  end
+
+  # Make Devise aware of an 3rd party Devise-module (like invitable). For convenience.
+  #
+  # == Options:
+  #
+  #   +model+      - String representing the load path to a custom *model* for this module (to autoload.)
+  #   +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*.
+  #
+  # All values, except :model, accept also a boolean and will have the same name as the given module
+  # name.
+  #
+  # == Examples:
+  #
+  #   Devise.add_module(:party_module)
+  #   Devise.add_module(:party_module, strategy: true, controller: :sessions)
+  #   Devise.add_module(:party_module, model: 'party_module/model')
+  #
+  def self.add_module(module_name, options = {})
+    ALL << module_name
+    options.assert_valid_keys(:strategy, :model, :controller, :route, :no_input)
+
+    if strategy = options[:strategy]
+      strategy = (strategy == true ? module_name : strategy)
+      STRATEGIES[module_name] = strategy
+    end
+
+    if controller = options[:controller]
+      controller = (controller == true ? module_name : controller)
+      CONTROLLERS[module_name] = controller
+    end
+
+    NO_INPUT << strategy if options[:no_input]
+
+    if route = options[:route]
+      case route
+      when TrueClass
+        key, value = module_name, []
+      when Symbol
+        key, value = route, []
+      when Hash
+        key, value = route.keys.first, route.values.flatten
+      else
+        raise ArgumentError, ":route should be true, a Symbol or a Hash"
+      end
+
+      URL_HELPERS[key] ||= []
+      URL_HELPERS[key].concat(value)
+      URL_HELPERS[key].uniq!
+
+      ROUTES[module_name] = key
+    end
+
+    if options[:model]
+      path = (options[:model] == true ? "devise/models/#{module_name}" : options[:model])
+      camelized = ActiveSupport::Inflector.camelize(module_name.to_s)
+      Devise::Models.send(:autoload, camelized.to_sym, path)
+    end
+
+    Devise::Mapping.add_module module_name
+  end
+
+  # Sets warden configuration using a block that will be invoked on warden
+  # initialization.
+  #
+  #  Devise.setup do |config|
+  #    config.allow_unconfirmed_access_for = 2.days
+  #
+  #    config.warden do |manager|
+  #      # Configure warden to use other strategies, like oauth.
+  #      manager.oauth(:twitter)
+  #    end
+  #  end
+  def self.warden(&block)
+    @@warden_config_blocks << block
+  end
+
+  # Specify an omniauth provider.
+  #
+  #   config.omniauth :github, APP_ID, APP_SECRET
+  #
+  def self.omniauth(provider, *args)
+    @@helpers << Devise::OmniAuth::UrlHelpers
+    config = Devise::OmniAuth::Config.new(provider, args)
+    @@omniauth_configs[config.strategy_name.to_sym] = config
+  end
+
+  # Include helpers in the given scope to AC and AV.
+  def self.include_helpers(scope)
+    ActiveSupport.on_load(:action_controller) do
+      include scope::Helpers if defined?(scope::Helpers)
+      include scope::UrlHelpers
+    end
+
+    ActiveSupport.on_load(:action_view) do
+      include scope::UrlHelpers
+    end
+  end
+
+  # Regenerates url helpers considering Devise.mapping
+  def self.regenerate_helpers!
+    Devise::Controllers::UrlHelpers.remove_helpers!
+    Devise::Controllers::UrlHelpers.generate_helpers!
+  end
+
+  # A method used internally to setup warden manager from the Rails initialize
+  # block.
+  def self.configure_warden! #:nodoc:
+    @@warden_configured ||= begin
+      warden_config.failure_app   = Devise::Delegator.new
+      warden_config.default_scope = Devise.default_scope
+      warden_config.intercept_401 = false
+
+      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_blocks.map { |block| block.call Devise.warden_config }
+      true
+    end
+  end
+
+  # Generate a friendly string randomly to be used as token.
+  def self.friendly_token
+    SecureRandom.urlsafe_base64(15).tr('lIO0', 'sxyz')
+  end
+
+  # constant-time comparison algorithm to prevent timing attacks
+  def self.secure_compare(a, b)
+    return false if a.blank? || b.blank? || a.bytesize != b.bytesize
+    l = a.unpack "C#{a.bytesize}"
+
+    res = 0
+    b.each_byte { |byte| res |= byte ^ l.shift }
+    res == 0
+  end
+end
+
+require 'warden'
+require 'devise/mapping'
+require 'devise/models'
+require 'devise/modules'
+require 'devise/rails'
diff --git a/lib/devise/controllers/helpers.rb b/lib/devise/controllers/helpers.rb
new file mode 100644
index 0000000..b3f43d0
--- /dev/null
+++ b/lib/devise/controllers/helpers.rb
@@ -0,0 +1,284 @@
+module Devise
+  module Controllers
+    # Those helpers are convenience methods added to ApplicationController.
+    module Helpers
+      extend ActiveSupport::Concern
+      include Devise::Controllers::SignInOut
+      include Devise::Controllers::StoreLocation
+
+      included do
+        helper_method :warden, :signed_in?, :devise_controller?
+      end
+
+      module ClassMethods
+        # Define authentication filters and accessor helpers for a group of mappings.
+        # These methods are useful when you are working with multiple mappings that
+        # share some functionality. They are pretty much the same as the ones
+        # defined for normal mappings.
+        #
+        # Example:
+        #
+        #   inside BlogsController (or any other controller, it doesn't matter which):
+        #     devise_group :blogger, contains: [:user, :admin]
+        #
+        #   Generated methods:
+        #     authenticate_blogger!  # Redirects unless user or admin are signed in
+        #     blogger_signed_in?     # Checks whether there is either a user or an admin signed in
+        #     current_blogger        # Currently signed in user or admin
+        #     current_bloggers       # Currently signed in user and admin
+        #
+        #   Use:
+        #     before_filter :authenticate_blogger!              # Redirects unless either a user or an admin are authenticated
+        #     before_filter ->{ authenticate_blogger! :admin }  # Redirects to the admin login page
+        #     current_blogger :user                             # Preferably returns a User if one is signed in
+        #
+        def devise_group(group_name, opts={})
+          mappings = "[#{ opts[:contains].map { |m| ":#{m}" }.join(',') }]"
+
+          class_eval <<-METHODS, __FILE__, __LINE__ + 1
+            def authenticate_#{group_name}!(favourite=nil, opts={})
+              unless #{group_name}_signed_in?
+                mappings = #{mappings}
+                mappings.unshift mappings.delete(favourite.to_sym) if favourite
+                mappings.each do |mapping|
+                  opts[:scope] = mapping
+                  warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
+                end
+              end
+            end
+
+            def #{group_name}_signed_in?
+              #{mappings}.any? do |mapping|
+                warden.authenticate?(scope: mapping)
+              end
+            end
+
+            def current_#{group_name}(favourite=nil)
+              mappings = #{mappings}
+              mappings.unshift mappings.delete(favourite.to_sym) if favourite
+              mappings.each do |mapping|
+                current = warden.authenticate(scope: mapping)
+                return current if current
+              end
+              nil
+            end
+
+            def current_#{group_name.to_s.pluralize}
+              #{mappings}.map do |mapping|
+                warden.authenticate(scope: mapping)
+              end.compact
+            end
+
+            helper_method "current_#{group_name}", "current_#{group_name.to_s.pluralize}", "#{group_name}_signed_in?"
+          METHODS
+        end
+
+        def log_process_action(payload)
+          payload[:status] ||= 401 unless payload[:exception]
+          super
+        end
+      end
+
+      # Define authentication filters and accessor helpers based on mappings.
+      # These filters should be used inside the controllers as before_filters,
+      # so you can control the scope of the user who should be signed in to
+      # access that specific controller/action.
+      # Example:
+      #
+      #   Roles:
+      #     User
+      #     Admin
+      #
+      #   Generated methods:
+      #     authenticate_user!  # Signs user in or redirect
+      #     authenticate_admin! # Signs admin in or redirect
+      #     user_signed_in?     # Checks whether there is a user signed in or not
+      #     admin_signed_in?    # Checks whether there is an admin signed in or not
+      #     current_user        # Current signed in user
+      #     current_admin       # Current signed in admin
+      #     user_session        # Session data available only to the user scope
+      #     admin_session       # Session data available only to the admin scope
+      #
+      #   Use:
+      #     before_filter :authenticate_user!  # Tell devise to use :user map
+      #     before_filter :authenticate_admin! # Tell devise to use :admin map
+      #
+      def self.define_helpers(mapping) #:nodoc:
+        mapping = mapping.name
+
+        class_eval <<-METHODS, __FILE__, __LINE__ + 1
+          def authenticate_#{mapping}!(opts={})
+            opts[:scope] = :#{mapping}
+            warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
+          end
+
+          def #{mapping}_signed_in?
+            !!current_#{mapping}
+          end
+
+          def current_#{mapping}
+            @current_#{mapping} ||= warden.authenticate(scope: :#{mapping})
+          end
+
+          def #{mapping}_session
+            current_#{mapping} && warden.session(:#{mapping})
+          end
+        METHODS
+
+        ActiveSupport.on_load(:action_controller) do
+          helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session"
+        end
+      end
+
+      # The main accessor for the warden proxy instance
+      def warden
+        request.env['warden']
+      end
+
+      # Return true if it's a devise_controller. false to all controllers unless
+      # the controllers defined inside devise. Useful if you want to apply a before
+      # filter to all controllers, except the ones in devise:
+      #
+      #   before_filter :my_filter, unless: :devise_controller?
+      def devise_controller?
+        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
+      end
+
+      # The scope root url to be used when they're signed in. By default, it first
+      # tries to find a resource_root_path, otherwise it uses the root_path.
+      def signed_in_root_path(resource_or_scope)
+        scope = Devise::Mapping.find_scope!(resource_or_scope)
+        router_name = Devise.mappings[scope].router_name
+
+        home_path = "#{scope}_root_path"
+
+        context = router_name ? send(router_name) : self
+
+        if context.respond_to?(home_path, true)
+          context.send(home_path)
+        elsif context.respond_to?(:root_path)
+          context.root_path
+        elsif respond_to?(:root_path)
+          root_path
+        else
+          "/"
+        end
+      end
+
+      # The default url to be used after signing in. This is used by all Devise
+      # controllers and you can overwrite it in your ApplicationController to
+      # provide a custom hook for a custom resource.
+      #
+      # By default, it first tries to find a valid resource_return_to key in the
+      # session, then it fallbacks to resource_root_path, otherwise it uses the
+      # root path. For a user scope, you can define the default url in
+      # the following way:
+      #
+      #   map.user_root '/users', controller: 'users' # creates user_root_path
+      #
+      #   map.namespace :user do |user|
+      #     user.root controller: 'users' # creates user_root_path
+      #   end
+      #
+      # If the resource root path is not defined, root_path is used. However,
+      # if this default is not enough, you can customize it, for example:
+      #
+      #   def after_sign_in_path_for(resource)
+      #     stored_location_for(resource) ||
+      #       if resource.is_a?(User) && resource.can_publish?
+      #         publisher_url
+      #       else
+      #         super
+      #       end
+      #   end
+      #
+      def after_sign_in_path_for(resource_or_scope)
+        stored_location_for(resource_or_scope) || signed_in_root_path(resource_or_scope)
+      end
+
+      # Method used by sessions controller to sign out a user. You can overwrite
+      # it in your ApplicationController to provide a custom hook for a custom
+      # scope. Notice that differently from +after_sign_in_path_for+ this method
+      # receives a symbol with the scope, and not the resource.
+      #
+      # By default it is the root_path.
+      def after_sign_out_path_for(resource_or_scope)
+        scope = Devise::Mapping.find_scope!(resource_or_scope)
+        router_name = Devise.mappings[scope].router_name
+        context = router_name ? send(router_name) : self
+        context.respond_to?(:root_path) ? context.root_path : "/"
+      end
+
+      # Sign in a user and tries to redirect first to the stored location and
+      # then to the url specified by after_sign_in_path_for. It accepts the same
+      # parameters as the sign_in method.
+      def sign_in_and_redirect(resource_or_scope, *args)
+        options  = args.extract_options!
+        scope    = Devise::Mapping.find_scope!(resource_or_scope)
+        resource = args.last || resource_or_scope
+        sign_in(scope, resource, options)
+        redirect_to after_sign_in_path_for(resource)
+      end
+
+      # Sign out a user and tries to redirect to the url specified by
+      # after_sign_out_path_for.
+      def sign_out_and_redirect(resource_or_scope)
+        scope = Devise::Mapping.find_scope!(resource_or_scope)
+        redirect_path = after_sign_out_path_for(scope)
+        Devise.sign_out_all_scopes ? sign_out : sign_out(scope)
+        redirect_to redirect_path
+      end
+
+      # Overwrite Rails' handle unverified request to sign out all scopes,
+      # clear run strategies and remove cached variables.
+      def handle_unverified_request
+        super # call the default behaviour which resets/nullifies/raises
+        request.env["devise.skip_storage"] = true
+        sign_out_all_scopes(false)
+      end
+
+      def request_format
+        @request_format ||= request.format.try(:ref)
+      end
+
+      def is_navigational_format?
+        Devise.navigational_formats.include?(request_format)
+      end
+
+      # Check if flash messages should be emitted. Default is to do it on
+      # navigational formats
+      def is_flashing_format?
+        is_navigational_format?
+      end
+
+      private
+
+      def expire_session_data_after_sign_in!
+        ActiveSupport::Deprecation.warn "expire_session_data_after_sign_in! is deprecated " \
+          "in favor of expire_data_after_sign_in!"
+        expire_data_after_sign_in!
+      end
+
+      def expire_data_after_sign_out!
+        Devise.mappings.each { |_,m| instance_variable_set("@current_#{m.name}", nil) }
+        super
+      end
+    end
+  end
+end
diff --git a/lib/devise/controllers/rememberable.rb b/lib/devise/controllers/rememberable.rb
new file mode 100644
index 0000000..76edfe8
--- /dev/null
+++ b/lib/devise/controllers/rememberable.rb
@@ -0,0 +1,47 @@
+module Devise
+  module Controllers
+    # A module that may be optionally included in a controller in order
+    # to provide remember me behavior. Useful when signing in is done
+    # through a callback, like in Omniauth.
+    module Rememberable
+      # Return default cookie values retrieved from session options.
+      def self.cookie_values
+        Rails.configuration.session_options.slice(:path, :domain, :secure)
+      end
+
+      # Remembers the given resource by setting up a cookie
+      def remember_me(resource)
+        return if env["devise.skip_storage"]
+        scope = Devise::Mapping.find_scope!(resource)
+        resource.remember_me!(resource.extend_remember_period)
+        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_key(resource, scope), forget_cookie_values(resource))
+      end
+
+      protected
+
+      def forget_cookie_values(resource)
+        Devise::Controllers::Rememberable.cookie_values.merge!(resource.rememberable_options)
+      end
+
+      def remember_cookie_values(resource)
+        options = { httponly: true }
+        options.merge!(forget_cookie_values(resource))
+        options.merge!(
+          value: resource.class.serialize_into_cookie(resource),
+          expires: resource.remember_expires_at
+        )
+      end
+
+      def remember_key(resource, scope)
+        resource.rememberable_options.fetch(:key, "remember_#{scope}_token")
+      end
+    end
+  end
+end
diff --git a/lib/devise/controllers/scoped_views.rb b/lib/devise/controllers/scoped_views.rb
new file mode 100644
index 0000000..7ba965e
--- /dev/null
+++ b/lib/devise/controllers/scoped_views.rb
@@ -0,0 +1,17 @@
+module Devise
+  module Controllers
+    module ScopedViews
+      extend ActiveSupport::Concern
+
+      module ClassMethods
+        def scoped_views?
+          defined?(@scoped_views) ? @scoped_views : Devise.scoped_views
+        end
+
+        def scoped_views=(value)
+          @scoped_views = value
+        end
+      end
+    end
+  end
+end
diff --git a/lib/devise/controllers/sign_in_out.rb b/lib/devise/controllers/sign_in_out.rb
new file mode 100644
index 0000000..8516d43
--- /dev/null
+++ b/lib/devise/controllers/sign_in_out.rb
@@ -0,0 +1,102 @@
+module Devise
+  module Controllers
+    # Provide sign in and sign out functionality.
+    # Included by default in all controllers.
+    module SignInOut
+      # Return true if the given scope is signed in session. If no scope given, return
+      # true if any scope is signed in. Does not run authentication hooks.
+      def signed_in?(scope=nil)
+        [ scope || Devise.mappings.keys ].flatten.any? do |_scope|
+          warden.authenticate?(scope: _scope)
+        end
+      end
+
+      # Sign in a user that already was authenticated. This helper is useful for logging
+      # users in after sign up.
+      #
+      # All options given to sign_in is passed forward to the set_user method in warden.
+      # The only exception is the :bypass option, which bypass warden callbacks and stores
+      # the user straight in session. This option is useful in cases the user is already
+      # signed in, but we want to refresh the credentials in session.
+      #
+      # Examples:
+      #
+      #   sign_in :user, @user                      # sign_in(scope, resource)
+      #   sign_in @user                             # sign_in(resource)
+      #   sign_in @user, event: :authentication  # sign_in(resource, options)
+      #   sign_in @user, store: false            # sign_in(resource, options)
+      #   sign_in @user, bypass: true            # sign_in(resource, options)
+      #
+      def sign_in(resource_or_scope, *args)
+        options  = args.extract_options!
+        scope    = Devise::Mapping.find_scope!(resource_or_scope)
+        resource = args.last || resource_or_scope
+
+        expire_data_after_sign_in!
+
+        if options[:bypass]
+          warden.session_serializer.store(resource, scope)
+        elsif warden.user(scope) == resource && !options.delete(:force)
+          # Do nothing. User already signed in and we are not forcing it.
+          true
+        else
+          warden.set_user(resource, options.merge!(scope: scope))
+        end
+      end
+
+      # Sign out a given user or scope. This helper is useful for signing out a user
+      # after deleting accounts. Returns true if there was a logout and false if there
+      # is no user logged in on the referred scope
+      #
+      # Examples:
+      #
+      #   sign_out :user     # sign_out(scope)
+      #   sign_out @user     # sign_out(resource)
+      #
+      def sign_out(resource_or_scope=nil)
+        return sign_out_all_scopes unless resource_or_scope
+        scope = Devise::Mapping.find_scope!(resource_or_scope)
+        user = warden.user(scope: scope, run_callbacks: false) # If there is no user
+
+        warden.raw_session.inspect # Without this inspect here. The session does not clear.
+        warden.logout(scope)
+        warden.clear_strategies_cache!(scope: scope)
+        instance_variable_set(:"@current_#{scope}", nil)
+
+        !!user
+      end
+
+      # Sign out all active users or scopes. This helper is useful for signing out all roles
+      # in one click. This signs out ALL scopes in warden. Returns true if there was at least one logout
+      # and false if there was no user logged in on all scopes.
+      def sign_out_all_scopes(lock=true)
+        users = Devise.mappings.keys.map { |s| warden.user(scope: s, run_callbacks: false) }
+
+        warden.logout
+        expire_data_after_sign_out!
+        warden.clear_strategies_cache!
+        warden.lock! if lock
+
+        users.any?
+      end
+
+      private
+
+      def expire_data_after_sign_in!
+        # session.keys will return an empty array if the session is not yet loaded.
+        # This is a bug in both Rack and Rails.
+        # A call to #empty? forces the session to be loaded.
+        session.empty?
+        session.keys.grep(/^devise\./).each { |k| session.delete(k) }
+      end
+
+      def expire_data_after_sign_out!
+        # session.keys will return an empty array if the session is not yet loaded.
+        # This is a bug in both Rack and Rails.
+        # A call to #empty? forces the session to be loaded.
+        session.empty?
+        session.keys.grep(/^devise\./).each { |k| session.delete(k) }
+      end
+    end
+  end
+end
diff --git a/lib/devise/controllers/store_location.rb b/lib/devise/controllers/store_location.rb
new file mode 100644
index 0000000..ad36a4f
--- /dev/null
+++ b/lib/devise/controllers/store_location.rb
@@ -0,0 +1,56 @@
+require "uri"
+
+module Devise
+  module Controllers
+    # Provide the ability to store a location.
+    # Used to redirect back to a desired path after sign in.
+    # Included by default in all controllers.
+    module StoreLocation
+      # Returns and delete (if it's navigational format) the url stored in the session for
+      # the given scope. Useful for giving redirect backs after sign up:
+      #
+      # Example:
+      #
+      #   redirect_to stored_location_for(:user) || root_path
+      #
+      def stored_location_for(resource_or_scope)
+        session_key = stored_location_key_for(resource_or_scope)
+
+        if is_navigational_format?
+          session.delete(session_key)
+        else
+          session[session_key]
+        end
+      end
+
+      # Stores the provided location to redirect the user after signing in.
+      # Useful in combination with the `stored_location_for` helper.
+      #
+      # Example:
+      #
+      #   store_location_for(:user, dashboard_path)
+      #   redirect_to user_omniauth_authorize_path(:facebook)
+      #
+      def store_location_for(resource_or_scope, location)
+        session_key = stored_location_key_for(resource_or_scope)
+        uri = parse_uri(location)
+        if uri
+          session[session_key] = [uri.path.sub(/\A\/+/, '/'), uri.query].compact.join('?')
+        end
+      end
+
+      private
+
+      def parse_uri(location)
+        location && URI.parse(location)
+      rescue URI::InvalidURIError
+        nil
+      end
+
+      def stored_location_key_for(resource_or_scope)
+        scope = Devise::Mapping.find_scope!(resource_or_scope)
+        "#{scope}_return_to"
+      end
+    end
+  end
+end
diff --git a/lib/devise/controllers/url_helpers.rb b/lib/devise/controllers/url_helpers.rb
new file mode 100644
index 0000000..465d698
--- /dev/null
+++ b/lib/devise/controllers/url_helpers.rb
@@ -0,0 +1,69 @@
+module Devise
+  module Controllers
+    # Create url helpers to be used with resource/scope configuration. Acts as
+    # proxies to the generated routes created by devise.
+    # Resource param can be a string or symbol, a class, or an instance object.
+    # Example using a :user resource:
+    #
+    #   new_session_path(:user)      => new_user_session_path
+    #   session_path(:user)          => user_session_path
+    #   destroy_session_path(:user)  => destroy_user_session_path
+    #
+    #   new_password_path(:user)     => new_user_password_path
+    #   password_path(:user)         => user_password_path
+    #   edit_password_path(:user)    => edit_user_password_path
+    #
+    #   new_confirmation_path(:user) => new_user_confirmation_path
+    #   confirmation_path(:user)     => user_confirmation_path
+    #
+    # Those helpers are included by default to ActionController::Base.
+    #
+    # In case you want to add such helpers to another class, you can do
+    # that as long as this new class includes both url_helpers and
+    # mounted_helpers. Example:
+    #
+    #     include Rails.application.routes.url_helpers
+    #     include Rails.application.routes.mounted_helpers
+    #
+    module UrlHelpers
+      def self.remove_helpers!
+        self.instance_methods.map(&:to_s).grep(/_(url|path)$/).each do |method|
+          remove_method method
+        end
+      end
+
+      def self.generate_helpers!(routes=nil)
+        routes ||= begin
+          mappings = Devise.mappings.values.map(&:used_helpers).flatten.uniq
+          Devise::URL_HELPERS.slice(*mappings)
+        end
+
+        routes.each do |module_name, actions|
+          [:path, :url].each do |path_or_url|
+            actions.each do |action|
+              action = action ? "#{action}_" : ""
+              method = "#{action}#{module_name}_#{path_or_url}"
+
+              class_eval <<-URL_HELPERS, __FILE__, __LINE__ + 1
+                def #{method}(resource_or_scope, *args)
+                  scope = Devise::Mapping.find_scope!(resource_or_scope)
+                  router_name = Devise.mappings[scope].router_name
+                  context = router_name ? send(router_name) : _devise_route_context
+                  context.send("#{action}\#{scope}_#{module_name}_#{path_or_url}", *args)
+                end
+              URL_HELPERS
+            end
+          end
+        end
+      end
+
+      generate_helpers!(Devise::URL_HELPERS)
+
+      private
+
+      def _devise_route_context
+        @_devise_route_context ||= send(Devise.available_router_name)
+      end
+    end
+  end
+end
diff --git a/lib/devise/delegator.rb b/lib/devise/delegator.rb
new file mode 100644
index 0000000..361d4cf
--- /dev/null
+++ b/lib/devise/delegator.rb
@@ -0,0 +1,16 @@
+module Devise
+  # Checks the scope in the given environment and returns the associated failure app.
+  class Delegator
+    def call(env)
+      failure_app(env).call(env)
+    end
+
+    def failure_app(env)
+      app = env["warden.options"] &&
+        (scope = env["warden.options"][:scope]) &&
+        Devise.mappings[scope.to_sym].failure_app
+
+      app || Devise::FailureApp
+    end
+  end
+end
diff --git a/lib/devise/failure_app.rb b/lib/devise/failure_app.rb
new file mode 100644
index 0000000..7cedf64
--- /dev/null
+++ b/lib/devise/failure_app.rb
@@ -0,0 +1,210 @@
+require "action_controller/metal"
+
+module Devise
+  # Failure application that will be called every time :warden is thrown from
+  # any strategy or hook. Responsible for redirect the user to the sign in
+  # page based on current scope and mapping. If no scope is given, redirect
+  # to the default_url.
+  class FailureApp < ActionController::Metal
+    include ActionController::RackDelegation
+    include ActionController::UrlFor
+    include ActionController::Redirecting
+
+    include Rails.application.routes.url_helpers
+    include Rails.application.routes.mounted_helpers
+
+    include Devise::Controllers::StoreLocation
+
+    delegate :flash, to: :request
+
+    def self.call(env)
+      @respond ||= action(:respond)
+      @respond.call(env)
+    end
+
+    def self.default_url_options(*args)
+      if defined?(ApplicationController)
+        ApplicationController.default_url_options(*args)
+      else
+        {}
+      end
+    end
+
+    def respond
+      if http_auth?
+        http_auth
+      elsif warden_options[:recall]
+        recall
+      else
+        redirect
+      end
+    end
+
+    def http_auth
+      self.status = 401
+      self.headers["WWW-Authenticate"] = %(Basic realm=#{Devise.http_authentication_realm.inspect}) if http_auth_header?
+      self.content_type = request.format.to_s
+      self.response_body = http_auth_body
+    end
+
+    def recall
+      env["PATH_INFO"]  = attempted_path
+      flash.now[:alert] = i18n_message(:invalid)
+      self.response = recall_app(warden_options[:recall]).call(env)
+    end
+
+    def redirect
+      store_location!
+      if flash[:timedout] && flash[:alert]
+        flash.keep(:timedout)
+        flash.keep(:alert)
+      else
+        flash[:alert] = i18n_message
+      end
+      redirect_to redirect_url
+    end
+
+  protected
+
+    def i18n_options(options)
+      options
+    end
+
+    def i18n_message(default = nil)
+      message = warden_message || default || :unauthenticated
+
+      if message.is_a?(Symbol)
+        options = {}
+        options[:resource_name] = scope
+        options[:scope] = "devise.failure"
+        options[:default] = [message]
+        options[:authentication_keys] = scope_class.authentication_keys.join(I18n.translate(:"support.array.words_connector"))
+        options = i18n_options(options)
+
+        I18n.t(:"#{scope}.#{message}", options)
+      else
+        message.to_s
+      end
+    end
+
+    def redirect_url
+      if warden_message == :timeout
+        flash[:timedout] = true
+
+        path = if request.get?
+          attempted_path
+        else
+          request.referrer
+        end
+
+        path || scope_url
+      else
+        scope_url
+      end
+    end
+
+    def scope_url
+      opts  = {}
+      route = :"new_#{scope}_session_url"
+      opts[:format] = request_format unless skip_format?
+
+      config = Rails.application.config
+      opts[:script_name] = (config.relative_url_root if config.respond_to?(:relative_url_root))
+
+      context = send(Devise.available_router_name)
+
+      if context.respond_to?(route)
+        context.send(route, opts)
+      elsif respond_to?(:root_url)
+        root_url(opts)
+      else
+        "/"
+      end
+    end
+
+    def skip_format?
+      %w(html */*).include? request_format.to_s
+    end
+
+    # Choose whether we should respond in a http authentication fashion,
+    # including 401 and optional headers.
+    #
+    # This method allows the user to explicitly disable http authentication
+    # on ajax requests in case they want to redirect on failures instead of
+    # handling the errors on their own. This is useful in case your ajax API
+    # is the same as your public API and uses a format like JSON (so you
+    # cannot mark JSON as a navigational format).
+    def http_auth?
+      if request.xhr?
+        Devise.http_authenticatable_on_xhr
+      else
+        !(request_format && is_navigational_format?)
+      end
+    end
+
+    # It does not make sense to send authenticate headers in ajax requests
+    # or if the user disabled them.
+    def http_auth_header?
+      scope_class.http_authenticatable && !request.xhr?
+    end
+
+    def http_auth_body
+      return i18n_message unless request_format
+      method = "to_#{request_format}"
+      if method == "to_xml"
+        { error: i18n_message }.to_xml(root: "errors")
+      elsif {}.respond_to?(method)
+        { error: i18n_message }.send(method)
+      else
+        i18n_message
+      end
+    end
+
+    def recall_app(app)
+      controller, action = app.split("#")
+      controller_name  = ActiveSupport::Inflector.camelize(controller)
+      controller_klass = ActiveSupport::Inflector.constantize("#{controller_name}Controller")
+      controller_klass.action(action)
+    end
+
+    def warden
+      env['warden']
+    end
+
+    def warden_options
+      env['warden.options']
+    end
+
+    def warden_message
+      @message ||= warden.message || warden_options[:message]
+    end
+
+    def scope
+      @scope ||= warden_options[:scope] || Devise.default_scope
+    end
+
+    def scope_class
+      @scope_class ||= Devise.mappings[scope].to
+    end
+
+    def attempted_path
+      warden_options[:attempted_path]
+    end
+
+    # Stores requested uri to redirect the user after signing in. We cannot use
+    # scoped session provided by warden here, since the user is not authenticated
+    # yet, but we still need to store the uri based on scope, so different scopes
+    # would never use the same uri to redirect.
+    def store_location!
+      store_location_for(scope, attempted_path) if request.get? && !http_auth?
+    end
+
+    def is_navigational_format?
+      Devise.navigational_formats.include?(request_format)
+    end
+
+    def request_format
+      @request_format ||= request.format.try(:ref)
+    end
+  end
+end
diff --git a/lib/devise/hooks/activatable.rb b/lib/devise/hooks/activatable.rb
new file mode 100644
index 0000000..805c2c5
--- /dev/null
+++ b/lib/devise/hooks/activatable.rb
@@ -0,0 +1,10 @@
+# Deny user access whenever their account is not active yet.
+# We need this as hook to validate the user activity on each request
+# and in case the user is using other strategies beside Devise ones.
+Warden::Manager.after_set_user do |record, warden, options|
+  if record && record.respond_to?(:active_for_authentication?) && !record.active_for_authentication?
+    scope = options[:scope]
+    warden.logout(scope)
+    throw :warden, scope: scope, message: record.inactive_message
+  end
+end
diff --git a/lib/devise/hooks/csrf_cleaner.rb b/lib/devise/hooks/csrf_cleaner.rb
new file mode 100644
index 0000000..28d4aea
--- /dev/null
+++ b/lib/devise/hooks/csrf_cleaner.rb
@@ -0,0 +1,7 @@
+Warden::Manager.after_authentication do |record, warden, options|
+  clean_up_for_winning_strategy = !warden.winning_strategy.respond_to?(:clean_up_csrf?) ||
+    warden.winning_strategy.clean_up_csrf?
+  if Devise.clean_up_csrf_token_on_authentication && clean_up_for_winning_strategy
+    warden.request.session.try(:delete, :_csrf_token)
+  end
+end
diff --git a/lib/devise/hooks/forgetable.rb b/lib/devise/hooks/forgetable.rb
new file mode 100644
index 0000000..50e2062
--- /dev/null
+++ b/lib/devise/hooks/forgetable.rb
@@ -0,0 +1,9 @@
+# Before logout hook to forget the user in the given scope, if it responds
+# to forget_me! Also clear remember token to ensure the user won't be
+# remembered again. Notice that we forget the user unless the record is not persisted.
+# This avoids forgetting deleted users.
+Warden::Manager.before_logout do |record, warden, options|
+  if record.respond_to?(:forget_me!)
+    Devise::Hooks::Proxy.new(warden).forget_me(record)
+  end
+end
diff --git a/lib/devise/hooks/lockable.rb b/lib/devise/hooks/lockable.rb
new file mode 100644
index 0000000..50b726b
--- /dev/null
+++ b/lib/devise/hooks/lockable.rb
@@ -0,0 +1,7 @@
+# After each sign in, if resource responds to failed_attempts, sets it to 0
+# 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.to_i.zero?
+  end
+end
diff --git a/lib/devise/hooks/proxy.rb b/lib/devise/hooks/proxy.rb
new file mode 100644
index 0000000..f27e1d0
--- /dev/null
+++ b/lib/devise/hooks/proxy.rb
@@ -0,0 +1,21 @@
+module Devise
+  module Hooks
+    # A small warden proxy so we can remember, forget and
+    # sign out users from hooks.
+    class Proxy #:nodoc:
+      include Devise::Controllers::Rememberable
+      include Devise::Controllers::SignInOut
+
+      attr_reader :warden
+      delegate :cookies, :env, to: :warden
+
+      def initialize(warden)
+        @warden = warden
+      end
+
+      def session
+        warden.request.session
+      end
+    end
+  end
+end
diff --git a/lib/devise/hooks/rememberable.rb b/lib/devise/hooks/rememberable.rb
new file mode 100644
index 0000000..077be53
--- /dev/null
+++ b/lib/devise/hooks/rememberable.rb
@@ -0,0 +1,7 @@
+Warden::Manager.after_set_user except: :fetch do |record, warden, options|
+  scope = options[:scope]
+  if record.respond_to?(:remember_me) && options[:store] != false &&
+     record.remember_me && warden.authenticated?(scope)
+    Devise::Hooks::Proxy.new(warden).remember_me(record)
+  end
+end
diff --git a/lib/devise/hooks/timeoutable.rb b/lib/devise/hooks/timeoutable.rb
new file mode 100644
index 0000000..b9373cb
--- /dev/null
+++ b/lib/devise/hooks/timeoutable.rb
@@ -0,0 +1,35 @@
+# Each time a record is set we check whether its session has already timed out
+# or not, based on last request time. If so, the record is logged out and
+# redirected to the sign in page. Also, each time the request comes and the
+# record is set, we set the last request time inside its scoped session to
+# verify timeout in the following request.
+Warden::Manager.after_set_user do |record, warden, options|
+  scope = options[:scope]
+  env   = warden.request.env
+
+  if record && record.respond_to?(:timedout?) && warden.authenticated?(scope) && options[:store] != false
+    last_request_at = warden.session(scope)['last_request_at']
+
+    if last_request_at.is_a? Integer
+      last_request_at = Time.at(last_request_at).utc
+    elsif last_request_at.is_a? String
+      last_request_at = Time.parse(last_request_at)
+    end
+
+    proxy = Devise::Hooks::Proxy.new(warden)
+
+    if record.timedout?(last_request_at) && !env['devise.skip_timeout']
+      Devise.sign_out_all_scopes ? proxy.sign_out : proxy.sign_out(scope)
+
+      if record.respond_to?(:expire_auth_token_on_timeout) && record.expire_auth_token_on_timeout
+        record.reset_authentication_token!
+      end
+
+      throw :warden, scope: scope, message: :timeout
+    end
+
+    unless env['devise.skip_trackable']
+      warden.session(scope)['last_request_at'] = Time.now.utc.to_i
+    end
+  end
+end
diff --git a/lib/devise/hooks/trackable.rb b/lib/devise/hooks/trackable.rb
new file mode 100644
index 0000000..9bb2128
--- /dev/null
+++ b/lib/devise/hooks/trackable.rb
@@ -0,0 +1,9 @@
+# After each sign in, update sign in time, sign in count and sign in IP.
+# This is only triggered when the user is explicitly set (with set_user)
+# and on authentication. Retrieving the user from session (:fetch) does
+# not trigger it.
+Warden::Manager.after_set_user except: :fetch do |record, warden, options|
+  if record.respond_to?(:update_tracked_fields!) && warden.authenticated?(options[:scope]) && !warden.request.env['devise.skip_trackable']
+    record.update_tracked_fields!(warden.request)
+  end
+end
diff --git a/lib/devise/mailers/helpers.rb b/lib/devise/mailers/helpers.rb
new file mode 100644
index 0000000..60bf612
--- /dev/null
+++ b/lib/devise/mailers/helpers.rb
@@ -0,0 +1,90 @@
+module Devise
+  module Mailers
+    module Helpers
+      extend ActiveSupport::Concern
+
+      included do
+        include Devise::Controllers::ScopedViews
+        attr_reader :scope_name, :resource
+      end
+
+      protected
+
+      # Configure default email options
+      def devise_mail(record, action, opts={})
+        initialize_from_record(record)
+        mail headers_for(action, opts)
+      end
+
+      def initialize_from_record(record)
+        @scope_name = Devise::Mapping.find_scope!(record)
+        @resource   = instance_variable_set("@#{devise_mapping.name}", record)
+      end
+
+      def devise_mapping
+        @devise_mapping ||= Devise.mappings[scope_name]
+      end
+
+      def headers_for(action, opts)
+        headers = {
+          subject: subject_for(action),
+          to: resource.email,
+          from: mailer_sender(devise_mapping),
+          reply_to: mailer_reply_to(devise_mapping),
+          template_path: template_paths,
+          template_name: action
+        }.merge(opts)
+
+        @email = headers[:to]
+        headers
+      end
+
+      def mailer_reply_to(mapping)
+        mailer_sender(mapping, :reply_to)
+      end
+
+      def mailer_from(mapping)
+        mailer_sender(mapping, :from)
+      end
+
+      def mailer_sender(mapping, sender = :from)
+        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
+          Devise.mailer_sender
+        end
+      end
+
+      def template_paths
+        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 attempts to set a subject
+      # based on the current mapping:
+      #
+      #   en:
+      #     devise:
+      #       mailer:
+      #         confirmation_instructions:
+      #           user_subject: '...'
+      #
+      # If one does not exist, it fallbacks to ActionMailer default:
+      #
+      #   en:
+      #     devise:
+      #       mailer:
+      #         confirmation_instructions:
+      #           subject: '...'
+      #
+      def subject_for(key)
+        I18n.t(:"#{devise_mapping.name}_subject", scope: [:devise, :mailer, key],
+          default: [:subject, key.to_s.humanize])
+      end
+    end
+  end
+end
diff --git a/lib/devise/mapping.rb b/lib/devise/mapping.rb
new file mode 100644
index 0000000..5c40f76
--- /dev/null
+++ b/lib/devise/mapping.rb
@@ -0,0 +1,175 @@
+module Devise
+  # Responsible for handling devise mappings and routes configuration. Each
+  # resource configured by devise_for in routes is actually creating a mapping
+  # object. You can refer to devise_for in routes for usage options.
+  #
+  # The required value in devise_for is actually not used internally, but it's
+  # inflected to find all other values.
+  #
+  #   map.devise_for :users
+  #   mapping = Devise.mappings[:user]
+  #
+  #   mapping.name #=> :user
+  #   # is the scope used in controllers and warden, given in the route as :singular.
+  #
+  #   mapping.as   #=> "users"
+  #   # how the mapping should be search in the path, given in the route as :as.
+  #
+  #   mapping.to   #=> User
+  #   # is the class to be loaded from routes, given in the route as :class_name.
+  #
+  #   mapping.modules  #=> [:authenticatable]
+  #   # is the modules included in the class
+  #
+  class Mapping #:nodoc:
+    attr_reader :singular, :scoped_path, :path, :controllers, :path_names,
+                :class_name, :sign_out_via, :format, :used_routes, :used_helpers,
+                :failure_app, :router_name
+
+    alias :name :singular
+
+    # 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
+      when String, Symbol
+        return obj.to_sym
+      when Class
+        Devise.mappings.each_value { |m| return m.name if obj <= m.to }
+      else
+        Devise.mappings.each_value { |m| return m.name if obj.is_a?(m.to) }
+      end
+
+      raise "Could not find a valid mapping for #{obj.inspect}"
+    end
+
+    def self.find_by_path!(path, path_type=:fullpath)
+      Devise.mappings.each_value { |m| return m if path.include?(m.send(path_type)) }
+      raise "Could not find a valid mapping for path #{path.inspect}"
+    end
+
+    def initialize(name, options) #:nodoc:
+      @scoped_path = options[:as] ? "#{options[:as]}/#{name}" : name.to_s
+      @singular = (options[:singular] || @scoped_path.tr('/', '_').singularize).to_sym
+
+      @class_name = (options[:class_name] || name.to_s.classify).to_s
+      @klass = Devise.ref(@class_name)
+
+      @path = (options[:path] || name).to_s
+      @path_prefix = options[:path_prefix]
+
+      @sign_out_via = options[:sign_out_via] || Devise.sign_out_via
+      @format = options[:format]
+
+      @router_name = options[:router_name]
+
+      default_failure_app(options)
+      default_controllers(options)
+      default_path_names(options)
+      default_used_route(options)
+      default_used_helpers(options)
+    end
+
+    # Return modules for the mapping.
+    def modules
+      @modules ||= to.respond_to?(:devise_modules) ? to.devise_modules : []
+    end
+
+    # Gives the class the mapping points to.
+    def to
+      @klass.get
+    end
+
+    def strategies
+      @strategies ||= STRATEGIES.values_at(*self.modules).compact.uniq.reverse
+    end
+
+    def no_input_strategies
+      self.strategies & Devise::NO_INPUT
+    end
+
+    def routes
+      @routes ||= ROUTES.values_at(*self.modules).compact.uniq
+    end
+
+    def authenticatable?
+      @authenticatable ||= self.modules.any? { |m| m.to_s =~ /authenticatable/ }
+    end
+
+    def fullpath
+      "/#{@path_prefix}/#{@path}".squeeze("/")
+    end
+
+    # Create magic predicates for verifying what module is activated by this map.
+    # Example:
+    #
+    #   def confirmable?
+    #     self.modules.include?(:confirmable)
+    #   end
+    #
+    def self.add_module(m)
+      class_eval <<-METHOD, __FILE__, __LINE__ + 1
+        def #{m}?
+          self.modules.include?(:#{m})
+        end
+      METHOD
+    end
+
+    private
+
+    def default_failure_app(options)
+      @failure_app = options[:failure_app] || Devise::FailureApp
+      if @failure_app.is_a?(String)
+        ref = Devise.ref(@failure_app)
+        @failure_app = lambda { |env| ref.get.call(env) }
+      end
+    end
+
+    def default_controllers(options)
+      mod = options[:module] || "devise"
+      @controllers = Hash.new { |h,k| h[k] = "#{mod}/#{k}" }
+      @controllers.merge!(options[:controllers]) if options[:controllers]
+      @controllers.each { |k,v| @controllers[k] = v.to_s }
+    end
+
+    def default_path_names(options)
+      @path_names = Hash.new { |h,k| h[k] = k.to_s }
+      @path_names[:registration] = ""
+      @path_names.merge!(options[:path_names]) if options[:path_names]
+    end
+
+    def default_constraints(options)
+      @constraints = Hash.new
+      @constraints.merge!(options[:constraints]) if options[:constraints]
+    end
+
+    def default_defaults(options)
+      @defaults = Hash.new
+      @defaults.merge!(options[:defaults]) if options[:defaults]
+    end
+
+    def default_used_route(options)
+      singularizer = lambda { |s| s.to_s.singularize.to_sym }
+
+      if options.has_key?(:only)
+        @used_routes = self.routes & Array(options[:only]).map(&singularizer)
+      elsif options[:skip] == :all
+        @used_routes = []
+      else
+        @used_routes = self.routes - Array(options[:skip]).map(&singularizer)
+      end
+    end
+
+    def default_used_helpers(options)
+      singularizer = lambda { |s| s.to_s.singularize.to_sym }
+
+      if options[:skip_helpers] == true
+        @used_helpers = @used_routes
+      elsif skip = options[:skip_helpers]
+        @used_helpers = self.routes - Array(skip).map(&singularizer)
+      else
+        @used_helpers = self.routes
+      end
+    end
+  end
+end
diff --git a/lib/devise/models.rb b/lib/devise/models.rb
new file mode 100644
index 0000000..9893062
--- /dev/null
+++ b/lib/devise/models.rb
@@ -0,0 +1,119 @@
+module Devise
+  module Models
+    class MissingAttribute < StandardError
+      def initialize(attributes)
+        @attributes = attributes
+      end
+
+      def message
+        "The following attribute(s) is (are) missing on your model: #{@attributes.join(", ")}"
+      end
+    end
+
+    # Creates configuration values for Devise and for the given module.
+    #
+    #   Devise::Models.config(Devise::Authenticatable, :stretches, 10)
+    #
+    # The line above creates:
+    #
+    #   1) An accessor called Devise.stretches, which value is used by default;
+    #
+    #   2) Some class methods for your model Model.stretches and Model.stretches=
+    #      which have higher priority than Devise.stretches;
+    #
+    #   3) And an instance method stretches.
+    #
+    # To add the class methods you need to have a module ClassMethods defined
+    # inside the given class.
+    #
+    def self.config(mod, *accessors) #:nodoc:
+      class << mod; attr_accessor :available_configs; end
+      mod.available_configs = accessors
+
+      accessors.each do |accessor|
+        mod.class_eval <<-METHOD, __FILE__, __LINE__ + 1
+          def #{accessor}
+            if defined?(@#{accessor})
+              @#{accessor}
+            elsif superclass.respond_to?(:#{accessor})
+              superclass.#{accessor}
+            else
+              Devise.#{accessor}
+            end
+          end
+
+          def #{accessor}=(value)
+            @#{accessor} = value
+          end
+        METHOD
+      end
+    end
+
+    def self.check_fields!(klass)
+      failed_attributes = []
+      instance = klass.new
+
+      klass.devise_modules.each do |mod|
+        constant = const_get(mod.to_s.classify)
+
+        constant.required_fields(klass).each do |field|
+          failed_attributes << field unless instance.respond_to?(field)
+        end
+      end
+
+      if failed_attributes.any?
+        fail Devise::Models::MissingAttribute.new(failed_attributes)
+      end
+    end
+
+    # Include the chosen devise modules in your model:
+    #
+    #   devise :database_authenticatable, :confirmable, :recoverable
+    #
+    # You can also give any of the devise configuration values in form of a hash,
+    # with specific values for this model. Please check your Devise initializer
+    # for a complete description on those values.
+    #
+    def devise(*modules)
+      options = modules.extract_options!.dup
+
+      selected_modules = modules.map(&:to_sym).uniq.sort_by do |s|
+        Devise::ALL.index(s) || -1  # follow Devise::ALL order
+      end
+
+      devise_modules_hook! do
+        include Devise::Models::Authenticatable
+
+        selected_modules.each do |m|
+          mod = Devise::Models.const_get(m.to_s.classify)
+
+          if mod.const_defined?("ClassMethods")
+            class_mod = mod.const_get("ClassMethods")
+            extend class_mod
+
+            if class_mod.respond_to?(:available_configs)
+              available_configs = class_mod.available_configs
+              available_configs.each do |config|
+                next unless options.key?(config)
+                send(:"#{config}=", options.delete(config))
+              end
+            end
+          end
+
+          include mod
+        end
+
+        self.devise_modules |= selected_modules
+        options.each { |key, value| send(:"#{key}=", value) }
+      end
+    end
+
+    # The hook which is called inside devise.
+    # So your ORM can include devise compatibility stuff.
+    def devise_modules_hook!
+      yield
+    end
+  end
+end
+
+require 'devise/models/authenticatable'
diff --git a/lib/devise/models/authenticatable.rb b/lib/devise/models/authenticatable.rb
new file mode 100644
index 0000000..1b59049
--- /dev/null
+++ b/lib/devise/models/authenticatable.rb
@@ -0,0 +1,290 @@
+require 'devise/hooks/activatable'
+require 'devise/hooks/csrf_cleaner'
+
+module Devise
+  module Models
+    # Authenticatable module. Holds common settings for authentication.
+    #
+    # == Options
+    #
+    # Authenticatable adds the following options to devise_for:
+    #
+    #   * +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 specifying
+    #     if the value is required or not.
+    #
+    #   * +http_authenticatable+: if this model allows http authentication. By default false.
+    #     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.
+    #     It also accepts an array specifying the strategies that should allow params authentication.
+    #
+    #   * +skip_session_storage+: By default Devise will store the user in session.
+    #     By default is set to skip_session_storage: [:http_auth].
+    #
+    # == 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 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:
+    #
+    #   def active_for_authentication?
+    #     super && special_condition_is_valid?
+    #   end
+    #
+    # Whenever active_for_authentication? returns false, Devise asks the reason why your model is inactive using
+    # the inactive_message method. You can overwrite it as well:
+    #
+    #   def inactive_message
+    #     special_condition_is_valid? ? super : :special_condition_is_not_valid
+    #   end
+    #
+    module Authenticatable
+      extend ActiveSupport::Concern
+
+      BLACKLIST_FOR_SERIALIZATION = [:encrypted_password, :reset_password_token, :reset_password_sent_at,
+        :remember_created_at, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip,
+        :last_sign_in_ip, :password_salt, :confirmation_token, :confirmed_at, :confirmation_sent_at,
+        :remember_token, :unconfirmed_email, :failed_attempts, :unlock_token, :locked_at]
+
+      included do
+        class_attribute :devise_modules, instance_writer: false
+        self.devise_modules ||= []
+
+        before_validation :downcase_keys
+        before_validation :strip_whitespace
+      end
+
+      def self.required_fields(klass)
+        []
+      end
+
+      # Check if the current object is valid for authentication. This method and
+      # find_for_authentication are the methods used in a Warden::Strategy to check
+      # if a model should be signed in or not.
+      #
+      # However, you should not overwrite this method, you should overwrite active_for_authentication?
+      # and inactive_message instead.
+      def valid_for_authentication?
+        block_given? ? yield : true
+      end
+
+      def unauthenticated_message
+        :invalid
+      end
+
+      def active_for_authentication?
+        true
+      end
+
+      def inactive_message
+        :inactive
+      end
+
+      def authenticatable_salt
+      end
+
+      array = %w(serializable_hash)
+      # to_xml does not call serializable_hash on 3.1
+      array << "to_xml" if Rails::VERSION::STRING[0,3] == "3.1"
+
+      array.each do |method|
+        class_eval <<-RUBY, __FILE__, __LINE__
+          # Redefine to_xml and serializable_hash in models for more secure defaults.
+          # By default, it removes from the serializable model all attributes that
+          # are *not* accessible. You can remove this default by using :force_except
+          # and passing a new list of attributes you want to exempt. All attributes
+          # given to :except will simply add names to exempt to Devise internal list.
+          def #{method}(options=nil)
+            options ||= {}
+            options[:except] = Array(options[:except])
+
+            if options[:force_except]
+              options[:except].concat Array(options[:force_except])
+            else
+              options[:except].concat BLACKLIST_FOR_SERIALIZATION
+            end
+            super(options)
+          end
+        RUBY
+      end
+
+      protected
+
+      def devise_mailer
+        Devise.mailer
+      end
+
+      # This is an internal method called every time Devise needs
+      # to send a notification/mail. This can be overridden if you
+      # need to customize the e-mail delivery logic. For instance,
+      # if you are using a queue to deliver e-mails (delayed job,
+      # sidekiq, resque, etc), you must add the delivery to the queue
+      # just after the transaction was committed. To achieve this,
+      # you can override send_devise_notification to store the
+      # deliveries until the after_commit callback is triggered:
+      #
+      #     class User
+      #       devise :database_authenticatable, :confirmable
+      #
+      #       after_commit :send_pending_notifications
+      #
+      #       protected
+      #
+      #       def send_devise_notification(notification, *args)
+      #         # 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, args]
+      #         else
+      #           devise_mailer.send(notification, self, *args).deliver
+      #         end
+      #       end
+      #
+      #       def send_pending_notifications
+      #         pending_notifications.each do |notification, args|
+      #           devise_mailer.send(notification, self, *args).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
+      #         @pending_notifications ||= []
+      #       end
+      #     end
+      #
+      def send_devise_notification(notification, *args)
+        message = devise_mailer.send(notification, self, *args)
+        # Remove once we move to Rails 4.2+ only.
+        if message.respond_to?(:deliver_now)
+          message.deliver_now
+        else
+          message.deliver
+        end
+      end
+
+      def downcase_keys
+        self.class.case_insensitive_keys.each { |k| apply_to_attribute_or_variable(k, :downcase) }
+      end
+
+      def strip_whitespace
+        self.class.strip_whitespace_keys.each { |k| apply_to_attribute_or_variable(k, :strip) }
+      end
+
+      def apply_to_attribute_or_variable(attr, method)
+        if self[attr]
+          self[attr] = self[attr].try(method)
+
+        # Use respond_to? here to avoid a regression where globally
+        # configured strip_whitespace_keys or case_insensitive_keys were
+        # attempting to strip or downcase when a model didn't have the
+        # globally configured key.
+        elsif respond_to?(attr) && respond_to?("#{attr}=")
+          new_value = send(attr).try(method)
+          send("#{attr}=", new_value)
+        end
+      end
+
+      module ClassMethods
+        Devise::Models.config(self, :authentication_keys, :request_keys, :strip_whitespace_keys,
+          :case_insensitive_keys, :http_authenticatable, :params_authenticatable, :skip_session_storage,
+          :http_authentication_key)
+
+        def serialize_into_session(record)
+          [record.to_key, record.authenticatable_salt]
+        end
+
+        def serialize_from_session(key, salt)
+          record = to_adapter.get(key)
+          record if record && record.authenticatable_salt == salt
+        end
+
+        def params_authenticatable?(strategy)
+          params_authenticatable.is_a?(Array) ?
+            params_authenticatable.include?(strategy) : params_authenticatable
+        end
+
+        def http_authenticatable?(strategy)
+          http_authenticatable.is_a?(Array) ?
+            http_authenticatable.include?(strategy) : http_authenticatable
+        end
+
+        # Find first record based on conditions given (ie by the sign in form).
+        # This method is always called during an authentication process but
+        # it may be wrapped as well. For instance, database authenticatable
+        # provides a `find_for_database_authentication` that wraps a call to
+        # this method. This allows you to customize both database authenticatable
+        # or the whole authenticate stack by customize `find_for_authentication.`
+        #
+        # Overwrite to add customized conditions, create a join, or maybe use a
+        # namedscope to filter records while authenticating.
+        # Example:
+        #
+        #   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(tainted_conditions)
+          find_first_by_auth_conditions(tainted_conditions)
+        end
+
+        def find_first_by_auth_conditions(tainted_conditions, opts={})
+          to_adapter.find_first(devise_parameter_filter.filter(tainted_conditions).merge(opts))
+        end
+
+        # Find an initialize a record setting an error if it can't be found.
+        def find_or_initialize_with_error_by(attribute, value, error=:invalid) #:nodoc:
+          find_or_initialize_with_errors([attribute], { attribute => value }, error)
+        end
+
+        # Find an initialize a group of attributes based on a list of required attributes.
+        def find_or_initialize_with_errors(required_attributes, attributes, error=:invalid) #:nodoc:
+          attributes = attributes.slice(*required_attributes).with_indifferent_access
+          attributes.delete_if { |key, value| value.blank? }
+
+          if attributes.size == required_attributes.size
+            record = find_first_by_auth_conditions(attributes)
+          end
+
+          unless record
+            record = new
+
+            required_attributes.each do |key|
+              value = attributes[key]
+              record.send("#{key}=", value)
+              record.errors.add(key, value.present? ? error : :blank)
+            end
+          end
+
+          record
+        end
+
+        protected
+
+        def devise_parameter_filter
+          @devise_parameter_filter ||= Devise::ParameterFilter.new(case_insensitive_keys, strip_whitespace_keys)
+        end
+      end
+    end
+  end
+end
diff --git a/lib/devise/models/confirmable.rb b/lib/devise/models/confirmable.rb
new file mode 100644
index 0000000..dcac6d0
--- /dev/null
+++ b/lib/devise/models/confirmable.rb
@@ -0,0 +1,295 @@
+module Devise
+  module Models
+    # Confirmable is responsible to verify if an account is already confirmed to
+    # sign in, and to send emails with confirmation instructions.
+    # Confirmation instructions are sent to the user email after creating a
+    # record and when manually requested by a new confirmation instruction request.
+    #
+    # == Options
+    #
+    # Confirmable adds the following options to +devise+:
+    #
+    #   * +allow_unconfirmed_access_for+: the time you want to allow the user to access their account
+    #     before confirming it. After this period, the user access is denied. You can
+    #     use this to let your user access some features of your application without
+    #     confirming the account, but blocking it after a certain period (ie 7 days).
+    #     By default allow_unconfirmed_access_for is zero, it means users always have to confirm to sign in.
+    #   * +reconfirmable+: requires any email changes to be confirmed (exactly the same way as
+    #     initial account confirmation) to be applied. Requires additional unconfirmed_email
+    #     db field to be setup (t.reconfirmable in migrations). Until confirmed new email is
+    #     stored in unconfirmed email column, and copied to email column on successful
+    #     confirmation.
+    #   * +confirm_within+: the time before a sent confirmation token becomes invalid.
+    #     You can use this to force the user to confirm within a set period of time.
+    #
+    # == Examples
+    #
+    #   User.find(1).confirm!      # returns true unless it's already confirmed
+    #   User.find(1).confirmed?    # true/false
+    #   User.find(1).send_confirmation_instructions # manually send instructions
+    #
+    module Confirmable
+      extend ActiveSupport::Concern
+      include ActionView::Helpers::DateHelper
+
+      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?
+      end
+
+      def initialize(*args, &block)
+        @bypass_confirmation_postpone = false
+        @reconfirmation_required = false
+        @skip_confirmation_notification = false
+        @raw_confirmation_token = nil
+        super
+      end
+
+      def self.required_fields(klass)
+        required_methods = [:confirmation_token, :confirmed_at, :confirmation_sent_at]
+        required_methods << :unconfirmed_email if klass.reconfirmable
+        required_methods
+      end
+
+      # Confirm a user by setting it's confirmed_at to actual time. If the user
+      # is already confirmed, add an error to email field. If the user is invalid
+      # add errors
+      def confirm!
+        pending_any_confirmation do
+          if confirmation_period_expired?
+            self.errors.add(:email, :confirmation_period_expired,
+              period: Devise::TimeInflector.time_ago_in_words(self.class.confirm_within.ago))
+            return false
+          end
+
+          self.confirmation_token = nil
+          self.confirmed_at = Time.now.utc
+
+          saved = if self.class.reconfirmable && unconfirmed_email.present?
+            skip_reconfirmation!
+            self.email = unconfirmed_email
+            self.unconfirmed_email = nil
+
+            # We need to validate in such cases to enforce e-mail uniqueness
+            save(validate: true)
+          else
+            save(validate: false)
+          end
+
+          after_confirmation if saved
+          saved
+        end
+      end
+
+      # Verifies whether a user is confirmed or not
+      def confirmed?
+        !!confirmed_at
+      end
+
+      def pending_reconfirmation?
+        self.class.reconfirmable && unconfirmed_email.present?
+      end
+
+      # Send confirmation instructions by email
+      def send_confirmation_instructions
+        unless @raw_confirmation_token
+          generate_confirmation_token!
+        end
+
+        opts = pending_reconfirmation? ? { to: unconfirmed_email } : { }
+        send_devise_notification(:confirmation_instructions, @raw_confirmation_token, 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.
+      def resend_confirmation_instructions
+        pending_any_confirmation do
+          send_confirmation_instructions
+        end
+      end
+
+      # Overwrites active_for_authentication? for confirmation
+      # by verifying whether a user is active to sign in or not. If the user
+      # is already confirmed, it should never be blocked. Otherwise we need to
+      # calculate if the confirm time has not expired for this user.
+      def active_for_authentication?
+        super && (!confirmation_required? || confirmed? || confirmation_period_valid?)
+      end
+
+      # The message to be shown if the account is inactive.
+      def inactive_message
+        !confirmed? ? :unconfirmed : super
+      end
+
+      # If you don't want confirmation to be sent on create, neither a code
+      # to be generated, call skip_confirmation!
+      def skip_confirmation!
+        self.confirmed_at = Time.now.utc
+      end
+
+      # Skips sending the confirmation/reconfirmation notification email after_create/after_update. 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!
+        @bypass_confirmation_postpone = true
+      end
+
+      protected
+
+        # A callback method used to deliver confirmation
+        # instructions on creation. This can be overridden
+        # in models to map to a nice sign up e-mail.
+        def send_on_create_confirmation_instructions
+          send_confirmation_instructions
+        end
+
+        # Callback to overwrite if confirmation is required or not.
+        def confirmation_required?
+          !confirmed?
+        end
+
+        # Checks if the confirmation for the user is within the limit time.
+        # We do this by calculating if the difference between today and the
+        # confirmation sent date does not exceed the confirm in time configured.
+        # Confirm_within is a model configuration, must always be an integer value.
+        #
+        # Example:
+        #
+        #   # allow_unconfirmed_access_for = 1.day and confirmation_sent_at = today
+        #   confirmation_period_valid?   # returns true
+        #
+        #   # allow_unconfirmed_access_for = 5.days and confirmation_sent_at = 4.days.ago
+        #   confirmation_period_valid?   # returns true
+        #
+        #   # allow_unconfirmed_access_for = 5.days and confirmation_sent_at = 5.days.ago
+        #   confirmation_period_valid?   # returns false
+        #
+        #   # 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?
+          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
+        # Examples:
+        #
+        #   # confirm_within = 3.days and confirmation_sent_at = 2.days.ago
+        #   confirmation_period_expired?  # returns false
+        #
+        #   # confirm_within = 3.days and confirmation_sent_at = 4.days.ago
+        #   confirmation_period_expired?  # returns true
+        #
+        #   # confirm_within = nil
+        #   confirmation_period_expired?  # will always return false
+        #
+        def confirmation_period_expired?
+          self.class.confirm_within && (Time.now > self.confirmation_sent_at + self.class.confirm_within )
+        end
+
+        # Checks whether the record requires any confirmation.
+        def pending_any_confirmation
+          if (!confirmed? || pending_reconfirmation?)
+            yield
+          else
+            self.errors.add(:email, :already_confirmed)
+            false
+          end
+        end
+
+        # Generates a new random token for confirmation, and stores
+        # the time this token is being generated
+        def generate_confirmation_token
+          raw, enc = Devise.token_generator.generate(self.class, :confirmation_token)
+          @raw_confirmation_token   = raw
+          self.confirmation_token   = enc
+          self.confirmation_sent_at = Time.now.utc
+        end
+
+        def generate_confirmation_token!
+          generate_confirmation_token && save(validate: false)
+        end
+
+        def postpone_email_change_until_confirmation_and_regenerate_confirmation_token
+          @reconfirmation_required = true
+          self.unconfirmed_email = self.email
+          self.email = self.email_was
+          generate_confirmation_token
+        end
+
+        def postpone_email_change?
+          postpone = self.class.reconfirmable && email_changed? && !@bypass_confirmation_postpone && self.email.present?
+          @bypass_confirmation_postpone = false
+          postpone
+        end
+
+        def reconfirmation_required?
+          self.class.reconfirmable && @reconfirmation_required && self.email.present?
+        end
+
+        def send_confirmation_notification?
+          confirmation_required? && !@skip_confirmation_notification && self.email.present?
+        end
+
+        def after_confirmation
+        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
+        # field. If no user is found, returns a new user with an email not found error.
+        # Options must contain the user email
+        def send_confirmation_instructions(attributes={})
+          confirmable = find_by_unconfirmed_email_with_errors(attributes) if reconfirmable
+          unless confirmable.try(:persisted?)
+            confirmable = find_or_initialize_with_errors(confirmation_keys, attributes, :not_found)
+          end
+          confirmable.resend_confirmation_instructions if confirmable.persisted?
+          confirmable
+        end
+
+        # Find a user by its confirmation token and try to confirm it.
+        # If no user is found, returns a new user with an error.
+        # If the user is already confirmed, create an error for the user
+        # Options must have the confirmation_token
+        def confirm_by_token(confirmation_token)
+          original_token     = confirmation_token
+          confirmation_token = Devise.token_generator.digest(self, :confirmation_token, confirmation_token)
+
+          confirmable = find_or_initialize_with_error_by(:confirmation_token, confirmation_token)
+          confirmable.confirm! if confirmable.persisted?
+          confirmable.confirmation_token = original_token
+          confirmable
+        end
+
+        # Find a record for confirmation by unconfirmed email field
+        def find_by_unconfirmed_email_with_errors(attributes = {})
+          unconfirmed_required_attributes = confirmation_keys.map { |k| k == :email ? :unconfirmed_email : k }
+          unconfirmed_attributes = attributes.symbolize_keys
+          unconfirmed_attributes[:unconfirmed_email] = unconfirmed_attributes.delete(:email)
+          find_or_initialize_with_errors(unconfirmed_required_attributes, unconfirmed_attributes, :not_found)
+        end
+
+        Devise::Models.config(self, :allow_unconfirmed_access_for, :confirmation_keys, :reconfirmable, :confirm_within)
+      end
+    end
+  end
+end
diff --git a/lib/devise/models/database_authenticatable.rb b/lib/devise/models/database_authenticatable.rb
new file mode 100644
index 0000000..1eb2a81
--- /dev/null
+++ b/lib/devise/models/database_authenticatable.rb
@@ -0,0 +1,164 @@
+require 'devise/strategies/database_authenticatable'
+require 'bcrypt'
+
+module Devise
+  # Digests the password using bcrypt.
+  def self.bcrypt(klass, password)
+    ::BCrypt::Password.create("#{password}#{klass.pepper}", cost: klass.stretches).to_s
+  end
+
+  module Models
+    # Authenticatable Module, responsible for encrypting password and validating
+    # authenticity of a user while signing in.
+    #
+    # == Options
+    #
+    # DatabaseAuthenticable adds the following options to devise_for:
+    #
+    #   * +pepper+: a random string used to provide a more secure hash. Use
+    #     `rake secret` to generate new keys.
+    #
+    #   * +stretches+: the cost given to bcrypt.
+    #
+    # == Examples
+    #
+    #    User.find(1).valid_password?('password123')         # returns true/false
+    #
+    module DatabaseAuthenticatable
+      extend ActiveSupport::Concern
+
+      included do
+        attr_reader :password, :current_password
+        attr_accessor :password_confirmation
+      end
+
+      def self.required_fields(klass)
+        [:encrypted_password] + klass.authentication_keys
+      end
+
+      # Generates password encryption based on the given value.
+      def password=(new_password)
+        @password = new_password
+        self.encrypted_password = password_digest(@password) if @password.present?
+      end
+
+      # Verifies whether an password (ie from sign in) is the user password.
+      def valid_password?(password)
+        return false if encrypted_password.blank?
+        bcrypt   = ::BCrypt::Password.new(encrypted_password)
+        password = ::BCrypt::Engine.hash_secret("#{password}#{self.class.pepper}", bcrypt.salt)
+        Devise.secure_compare(password, encrypted_password)
+      end
+
+      # Set password and password confirmation to nil
+      def clean_up_passwords
+        self.password = self.password_confirmation = nil
+      end
+
+      # Update record attributes when :current_password matches, otherwise
+      # returns error on :current_password.
+      #
+      # This method also rejects the password field if it is blank (allowing
+      # users to change relevant information like the e-mail without changing
+      # their password). In case the password field is rejected, the confirmation
+      # is also rejected as long as it is also blank.
+      def update_with_password(params, *options)
+        current_password = params.delete(:current_password)
+
+        if params[:password].blank?
+          params.delete(:password)
+          params.delete(:password_confirmation) if params[:password_confirmation].blank?
+        end
+
+        result = if valid_password?(current_password)
+          update_attributes(params, *options)
+        else
+          self.assign_attributes(params, *options)
+          self.valid?
+          self.errors.add(:current_password, current_password.blank? ? :blank : :invalid)
+          false
+        end
+
+        clean_up_passwords
+        result
+      end
+
+      # Updates record attributes without asking for the current password.
+      # Never allows a change to the current password. If you are using this
+      # method, you should probably override this method to protect other
+      # attributes you would not like to be updated without a password.
+      #
+      # Example:
+      #
+      #   def update_without_password(params, *options)
+      #     params.delete(:email)
+      #     super(params)
+      #   end
+      #
+      def update_without_password(params, *options)
+        params.delete(:password)
+        params.delete(:password_confirmation)
+
+        result = update_attributes(params, *options)
+        clean_up_passwords
+        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
+
+      # A callback initiated after successfully authenticating. This can be
+      # used to insert your own logic that is only run after the user successfully
+      # authenticates.
+      #
+      # Example:
+      #
+      #   def after_database_authentication
+      #     self.update_attribute(:invite_code, nil)
+      #   end
+      #
+      def after_database_authentication
+      end
+
+      # A reliable way to expose the salt regardless of the implementation.
+      def authenticatable_salt
+        encrypted_password[0,29] if encrypted_password
+      end
+
+    protected
+
+      # Digests the password using bcrypt. Custom encryption should override
+      # this method to apply their own algorithm.
+      #
+      # See https://github.com/plataformatec/devise-encryptable for examples
+      # of other encryption engines.
+      def password_digest(password)
+        Devise.bcrypt(self.class, password)
+      end
+
+      module ClassMethods
+        Devise::Models.config(self, :pepper, :stretches)
+
+        # We assume this method already gets the sanitized values from the
+        # DatabaseAuthenticatable strategy. If you are using this method on
+        # your own, be sure to sanitize the conditions hash to only include
+        # the proper fields.
+        def find_for_database_authentication(conditions)
+          find_for_authentication(conditions)
+        end
+      end
+    end
+  end
+end
diff --git a/lib/devise/models/lockable.rb b/lib/devise/models/lockable.rb
new file mode 100644
index 0000000..803ea04
--- /dev/null
+++ b/lib/devise/models/lockable.rb
@@ -0,0 +1,196 @@
+require "devise/hooks/lockable"
+
+module Devise
+  module Models
+    # Handles blocking a user access after a certain number of attempts.
+    # Lockable accepts two different strategies to unlock a user after it's
+    # blocked: email and time. The former will send an email to the user when
+    # the lock happens, containing a link to unlock its account. The second
+    # will unlock the user automatically after some configured time (ie 2.hours).
+    # It's also possible to setup lockable to use both email and time strategies.
+    #
+    # == Options
+    #
+    # Lockable adds the following options to +devise+:
+    #
+    #   * +maximum_attempts+: how many attempts should be accepted before blocking the user.
+    #   * +lock_strategy+: lock the user account by :failed_attempts or :none.
+    #   * +unlock_strategy+: unlock the user account by :time, :email, :both or :none.
+    #   * +unlock_in+: the time you want to lock the user after to lock happens. Only available when unlock_strategy is :time or :both.
+    #   * +unlock_keys+: the keys you want to use when locking and unlocking an account
+    #
+    module Lockable
+      extend  ActiveSupport::Concern
+
+      delegate :lock_strategy_enabled?, :unlock_strategy_enabled?, to: "self.class"
+
+      def self.required_fields(klass)
+        attributes = []
+        attributes << :failed_attempts if klass.lock_strategy_enabled?(:failed_attempts)
+        attributes << :locked_at if klass.unlock_strategy_enabled?(:time)
+        attributes << :unlock_token if klass.unlock_strategy_enabled?(:email)
+
+        attributes
+      end
+
+      # Lock a user setting its locked_at to actual time.
+      # * +opts+: Hash options if you don't want to send email
+      #   when you lock access, you could pass the next hash
+      #   `{ send_instructions: false } as option`.
+      def lock_access!(opts = { })
+        self.locked_at = Time.now.utc
+
+        if unlock_strategy_enabled?(:email) && opts.fetch(:send_instructions, true)
+          send_unlock_instructions
+        else
+          save(validate: false)
+        end
+      end
+
+      # Unlock a user by cleaning locked_at and failed_attempts.
+      def unlock_access!
+        self.locked_at = nil
+        self.failed_attempts = 0 if respond_to?(:failed_attempts=)
+        self.unlock_token = nil  if respond_to?(:unlock_token=)
+        save(validate: false)
+      end
+
+      # Verifies whether a user is locked or not.
+      def access_locked?
+        !!locked_at && !lock_expired?
+      end
+
+      # Send unlock instructions by email
+      def send_unlock_instructions
+        raw, enc = Devise.token_generator.generate(self.class, :unlock_token)
+        self.unlock_token = enc
+        self.save(validate: false)
+        send_devise_notification(:unlock_instructions, raw, {})
+        raw
+      end
+
+      # Resend the unlock instructions if the user is locked.
+      def resend_unlock_instructions
+        if_access_locked { send_unlock_instructions }
+      end
+
+      # Overwrites active_for_authentication? from Devise::Models::Activatable for locking purposes
+      # by verifying whether a user is active to sign in or not based on locked?
+      def active_for_authentication?
+        super && !access_locked?
+      end
+
+      # Overwrites invalid_message from Devise::Models::Authenticatable to define
+      # the correct reason for blocking the sign in.
+      def inactive_message
+        access_locked? ? :locked : super
+      end
+
+      # Overwrites valid_for_authentication? from Devise::Models::Authenticatable
+      # for verifying whether a user is allowed to sign in or not. If the user
+      # is locked, it should never be allowed.
+      def valid_for_authentication?
+        return super unless persisted? && lock_strategy_enabled?(:failed_attempts)
+
+        # Unlock the user if the lock is expired, no matter
+        # if the user can login or not (wrong password, etc)
+        unlock_access! if lock_expired?
+
+        if super && !access_locked?
+          true
+        else
+          self.failed_attempts ||= 0
+          self.failed_attempts += 1
+          if attempts_exceeded?
+            lock_access! unless access_locked?
+          else
+            save(validate: false)
+          end
+          false
+        end
+      end
+
+      def unauthenticated_message
+        # If set to paranoid mode, do not show the locked message because it
+        # leaks the existence of an account.
+        if Devise.paranoid
+          super
+        elsif access_locked? || (lock_strategy_enabled?(:failed_attempts) && attempts_exceeded?)
+          :locked
+        elsif lock_strategy_enabled?(:failed_attempts) && last_attempt? && self.class.last_attempt_warning
+          :last_attempt
+        else
+          super
+        end
+      end
+
+      protected
+
+        def attempts_exceeded?
+          self.failed_attempts >= self.class.maximum_attempts
+        end
+
+        def last_attempt?
+          self.failed_attempts == self.class.maximum_attempts - 1
+        end
+
+        # Tells if the lock is expired if :time unlock strategy is active
+        def lock_expired?
+          if unlock_strategy_enabled?(:time)
+            locked_at && locked_at < self.class.unlock_in.ago
+          else
+            false
+          end
+        end
+
+        # Checks whether the record is locked or not, yielding to the block
+        # if it's locked, otherwise adds an error to email.
+        def if_access_locked
+          if access_locked?
+            yield
+          else
+            self.errors.add(Devise.unlock_keys.first, :not_locked)
+            false
+          end
+        end
+
+      module ClassMethods
+        # Attempt to find a user by its unlock keys. 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
+        def send_unlock_instructions(attributes={})
+          lockable = find_or_initialize_with_errors(unlock_keys, attributes, :not_found)
+          lockable.resend_unlock_instructions if lockable.persisted?
+          lockable
+        end
+
+        # Find a user by its unlock token and try to unlock it.
+        # If no user is found, returns a new user with an error.
+        # If the user is not locked, creates an error for the user
+        # Options must have the unlock_token
+        def unlock_access_by_token(unlock_token)
+          original_token = unlock_token
+          unlock_token   = Devise.token_generator.digest(self, :unlock_token, unlock_token)
+
+          lockable = find_or_initialize_with_error_by(:unlock_token, unlock_token)
+          lockable.unlock_access! if lockable.persisted?
+          lockable.unlock_token = original_token
+          lockable
+        end
+
+        # Is the unlock enabled for the given unlock strategy?
+        def unlock_strategy_enabled?(strategy)
+          [:both, strategy].include?(self.unlock_strategy)
+        end
+
+        # Is the lock enabled for the given lock strategy?
+        def lock_strategy_enabled?(strategy)
+          self.lock_strategy == strategy
+        end
+
+        Devise::Models.config(self, :maximum_attempts, :lock_strategy, :unlock_strategy, :unlock_in, :unlock_keys, :last_attempt_warning)
+      end
+    end
+  end
+end
diff --git a/lib/devise/models/omniauthable.rb b/lib/devise/models/omniauthable.rb
new file mode 100644
index 0000000..c1faf37
--- /dev/null
+++ b/lib/devise/models/omniauthable.rb
@@ -0,0 +1,27 @@
+require 'devise/omniauth'
+
+module Devise
+  module Models
+    # Adds OmniAuth support to your model.
+    #
+    # == Options
+    #
+    # Oauthable adds the following options to devise_for:
+    #
+    #   * +omniauth_providers+: Which providers are available to this model. It expects an array:
+    #
+    #       devise_for :database_authenticatable, :omniauthable, omniauth_providers: [:twitter]
+    #
+    module Omniauthable
+      extend ActiveSupport::Concern
+
+      def self.required_fields(klass)
+        []
+      end
+
+      module ClassMethods
+        Devise::Models.config(self, :omniauth_providers)
+      end
+    end
+  end
+end
diff --git a/lib/devise/models/recoverable.rb b/lib/devise/models/recoverable.rb
new file mode 100644
index 0000000..2694b33
--- /dev/null
+++ b/lib/devise/models/recoverable.rb
@@ -0,0 +1,147 @@
+module Devise
+  module Models
+
+    # Recoverable takes care of resetting the user password and send reset instructions.
+    #
+    # ==Options
+    #
+    # Recoverable adds the following options to devise_for:
+    #
+    #   * +reset_password_keys+: the keys you want to use when recovering the password for an account
+    #
+    # == Examples
+    #
+    #   # resets the user password and save the record, true if valid passwords are given, otherwise false
+    #   User.find(1).reset_password!('password123', 'password123')
+    #
+    #   # only resets the user password, without saving the record
+    #   user = User.find(1)
+    #   user.reset_password('password123', 'password123')
+    #
+    #   # creates a new token and send it with instructions about how to reset the password
+    #   User.find(1).send_reset_password_instructions
+    #
+    module Recoverable
+      extend ActiveSupport::Concern
+
+      def self.required_fields(klass)
+        [:reset_password_sent_at, :reset_password_token]
+      end
+
+      # Update password saving the record and clearing token. Returns true if
+      # the passwords are valid and the record was saved, false otherwise.
+      def reset_password!(new_password, new_password_confirmation)
+        self.password = new_password
+        self.password_confirmation = new_password_confirmation
+
+        if valid?
+          clear_reset_password_token
+          after_password_reset
+        end
+
+        save
+      end
+
+      # Resets reset password token and send reset password instructions by email.
+      # Returns the token sent in the e-mail.
+      def send_reset_password_instructions
+        token = set_reset_password_token
+        send_reset_password_instructions_notification(token)
+
+        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.
+      # Returns true if the resource is not responding to reset_password_sent_at at all.
+      # reset_password_within is a model configuration, must always be an integer value.
+      #
+      # Example:
+      #
+      #   # reset_password_within = 1.day and reset_password_sent_at = today
+      #   reset_password_period_valid?   # returns true
+      #
+      #   # reset_password_within = 5.days and reset_password_sent_at = 4.days.ago
+      #   reset_password_period_valid?   # returns true
+      #
+      #   # reset_password_within = 5.days and reset_password_sent_at = 5.days.ago
+      #   reset_password_period_valid?   # returns false
+      #
+      #   # reset_password_within = 0.days
+      #   reset_password_period_valid?   # will always return false
+      #
+      def reset_password_period_valid?
+        reset_password_sent_at && reset_password_sent_at.utc >= self.class.reset_password_within.ago
+      end
+
+      protected
+
+        # Removes reset_password token
+        def clear_reset_password_token
+          self.reset_password_token = nil
+          self.reset_password_sent_at = nil
+        end
+
+        def after_password_reset
+        end
+
+        def set_reset_password_token
+          raw, enc = Devise.token_generator.generate(self.class, :reset_password_token)
+
+          self.reset_password_token   = enc
+          self.reset_password_sent_at = Time.now.utc
+          self.save(validate: false)
+          raw
+        end
+
+        def send_reset_password_instructions_notification(token)
+          send_devise_notification(:reset_password_instructions, token, {})
+        end
+
+      module ClassMethods
+        # Attempt to find a user by password reset token. If a user is found, return it
+        # If a user is not found, return nil
+        def with_reset_password_token(token)
+          reset_password_token = Devise.token_generator.digest(self, :reset_password_token, token)
+          to_adapter.find_first(reset_password_token: reset_password_token)
+        end
+
+        # Attempt to find a user by its email. If a record is found, send new
+        # password instructions to it. If user is not found, returns a new user
+        # with an email not found error.
+        # Attributes must contain the user's email
+        def send_reset_password_instructions(attributes={})
+          recoverable = find_or_initialize_with_errors(reset_password_keys, attributes, :not_found)
+          recoverable.send_reset_password_instructions if recoverable.persisted?
+          recoverable
+        end
+
+        # Attempt to find a user by its reset_password_token to reset its
+        # password. If a user is found and token is still valid, reset its password and automatically
+        # try saving the record. If not user is found, returns a new user
+        # containing an error in reset_password_token attribute.
+        # Attributes must contain reset_password_token, password and confirmation
+        def reset_password_by_token(attributes={})
+          original_token       = attributes[:reset_password_token]
+          reset_password_token = Devise.token_generator.digest(self, :reset_password_token, original_token)
+
+          recoverable = find_or_initialize_with_error_by(:reset_password_token, reset_password_token)
+
+          if recoverable.persisted?
+            if recoverable.reset_password_period_valid?
+              recoverable.reset_password!(attributes[:password], attributes[:password_confirmation])
+            else
+              recoverable.errors.add(:reset_password_token, :expired)
+            end
+          end
+
+          recoverable.reset_password_token = original_token
+          recoverable
+        end
+
+        Devise::Models.config(self, :reset_password_keys, :reset_password_within)
+      end
+    end
+  end
+end
diff --git a/lib/devise/models/registerable.rb b/lib/devise/models/registerable.rb
new file mode 100644
index 0000000..1f10dd2
--- /dev/null
+++ b/lib/devise/models/registerable.rb
@@ -0,0 +1,25 @@
+module Devise
+  module Models
+    # Registerable is responsible for everything related to registering a new
+    # resource (ie user sign up).
+    module Registerable
+      extend ActiveSupport::Concern
+
+      def self.required_fields(klass)
+        []
+      end
+
+      module ClassMethods
+        # A convenience method that receives both parameters and session to
+        # initialize a user. This can be used by OAuth, for example, to send
+        # in the user token and be stored on initialization.
+        #
+        # By default discards all information sent by the session by calling
+        # new with params.
+        def new_with_session(params, session)
+          new(params)
+        end
+      end
+    end
+  end
+end
diff --git a/lib/devise/models/rememberable.rb b/lib/devise/models/rememberable.rb
new file mode 100644
index 0000000..e9326d2
--- /dev/null
+++ b/lib/devise/models/rememberable.rb
@@ -0,0 +1,129 @@
+require 'devise/strategies/rememberable'
+require 'devise/hooks/rememberable'
+require 'devise/hooks/forgetable'
+
+module Devise
+  module Models
+    # Rememberable manages generating and clearing token for remember the user
+    # from a saved cookie. Rememberable also has utility methods for dealing
+    # with serializing the user into the cookie and back from the cookie, trying
+    # to lookup the record based on the saved information.
+    # You probably wouldn't use rememberable methods directly, they are used
+    # mostly internally for handling the remember token.
+    #
+    # == Options
+    #
+    # Rememberable adds the following options in devise_for:
+    #
+    #   * +remember_for+: the time you want the user will be remembered without
+    #     asking for credentials. After this time the user will be blocked and
+    #     will have to enter their credentials again. This configuration is also
+    #     used to calculate the expires time for the cookie created to remember
+    #     the user. By default remember_for is 2.weeks.
+    #
+    #   * +extend_remember_period+: if true, extends the user's remember period
+    #     when remembered via cookie. False by default.
+    #
+    #   * +rememberable_options+: configuration options passed to the created cookie.
+    #
+    # == Examples
+    #
+    #   User.find(1).remember_me!  # regenerating the token
+    #   User.find(1).forget_me!    # clearing the token
+    #
+    #   # generating info to put into cookies
+    #   User.serialize_into_cookie(user)
+    #
+    #   # lookup the user based on the incoming cookie information
+    #   User.serialize_from_cookie(cookie_string)
+    module Rememberable
+      extend ActiveSupport::Concern
+
+      attr_accessor :remember_me, :extend_remember_period
+
+      def self.required_fields(klass)
+        [:remember_created_at]
+      end
+
+      # Generate a new remember token and save the record without validations
+      # unless remember_across_browsers is true and the user already has a valid token.
+      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?
+      end
+
+      # If the record is persisted, remove the remember token (but only if
+      # it exists), and save the record without validations.
+      def forget_me!
+        return unless persisted?
+        self.remember_token = nil if respond_to?(:remember_token=)
+        self.remember_created_at = nil if self.class.expire_all_remember_me_on_sign_out
+        save(validate: false)
+      end
+
+      # Remember token should be expired if expiration time not overpass now.
+      def remember_expired?
+        remember_created_at.nil? || (remember_expires_at <= Time.now.utc)
+      end
+
+      # Remember token expires at created time + remember_for configuration
+      def remember_expires_at
+        remember_created_at + self.class.remember_for
+      end
+
+      def rememberable_value
+        if respond_to?(:remember_token)
+          remember_token
+        elsif respond_to?(:authenticatable_salt) && (salt = authenticatable_salt)
+          salt
+        else
+          raise "authenticable_salt returned nil for the #{self.class.name} model. " \
+            "In order to use rememberable, you must ensure a password is always set " \
+            "or have a remember_token column in your model or implement your own " \
+            "rememberable_value in the model with custom logic."
+        end
+      end
+
+      def rememberable_options
+        self.class.rememberable_options
+      end
+
+    protected
+
+      def generate_remember_token? #:nodoc:
+        respond_to?(:remember_token) && remember_expired?
+      end
+
+      # Generate a timestamp if extend_remember_period is true, if no remember_token
+      # exists, or if an existing remember token has expired.
+      def generate_remember_timestamp?(extend_period) #:nodoc:
+        extend_period || remember_created_at.nil? || remember_expired?
+      end
+
+      module ClassMethods
+        # Create the cookie key using the record id and remember_token
+        def serialize_into_cookie(record)
+          [record.to_key, record.rememberable_value]
+        end
+
+        # Recreate the user based on the stored cookie
+        def serialize_from_cookie(id, remember_token)
+          record = to_adapter.get(id)
+          record if record && !record.remember_expired? &&
+                    Devise.secure_compare(record.rememberable_value, remember_token)
+        end
+
+        # Generate a token checking if one does not already exist in the database.
+        def remember_token #:nodoc:
+          loop do
+            token = Devise.friendly_token
+            break token unless to_adapter.find_first({ remember_token: token })
+          end
+        end
+
+        Devise::Models.config(self, :remember_for, :extend_remember_period, :rememberable_options, :expire_all_remember_me_on_sign_out)
+      end
+    end
+  end
+end
diff --git a/lib/devise/models/timeoutable.rb b/lib/devise/models/timeoutable.rb
new file mode 100644
index 0000000..bdc2abc
--- /dev/null
+++ b/lib/devise/models/timeoutable.rb
@@ -0,0 +1,49 @@
+require 'devise/hooks/timeoutable'
+
+module Devise
+  module Models
+    # Timeoutable takes care of verifying 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, they will be redirected
+    # to the sign in page.
+    #
+    # == Options
+    #
+    # Timeoutable adds the following options to devise_for:
+    #
+    #   * +timeout_in+: the interval to timeout the user session without activity.
+    #
+    # == Examples
+    #
+    #   user.timedout?(30.minutes.ago)
+    #
+    module Timeoutable
+      extend ActiveSupport::Concern
+
+      def self.required_fields(klass)
+        []
+      end
+
+      # Checks whether the user session has expired based on configured time.
+      def timedout?(last_access)
+        return false if remember_exists_and_not_expired?
+        !timeout_in.nil? && last_access && last_access <= timeout_in.ago
+      end
+
+      def timeout_in
+        self.class.timeout_in
+      end
+
+      private
+
+      def remember_exists_and_not_expired?
+        return false unless respond_to?(:remember_created_at) && respond_to?(:remember_expired?)
+        remember_created_at && !remember_expired?
+      end
+
+      module ClassMethods
+        Devise::Models.config(self, :timeout_in)
+      end
+    end
+  end
+end
diff --git a/lib/devise/models/trackable.rb b/lib/devise/models/trackable.rb
new file mode 100644
index 0000000..ae65c91
--- /dev/null
+++ b/lib/devise/models/trackable.rb
@@ -0,0 +1,38 @@
+require 'devise/hooks/trackable'
+
+module Devise
+  module Models
+    # Track information about your user sign in. It tracks the following columns:
+    #
+    # * sign_in_count      - Increased every time a sign in is made (by form, openid, oauth)
+    # * current_sign_in_at - A timestamp updated when the user signs in
+    # * last_sign_in_at    - Holds the timestamp of the previous sign in
+    # * current_sign_in_ip - The remote ip updated when the user sign in
+    # * last_sign_in_ip    - Holds the remote ip of the previous sign in
+    #
+    module Trackable
+      def self.required_fields(klass)
+        [:current_sign_in_at, :current_sign_in_ip, :last_sign_in_at, :last_sign_in_ip, :sign_in_count]
+      end
+
+      def update_tracked_fields(request)
+        old_current, new_current = self.current_sign_in_at, Time.now.utc
+        self.last_sign_in_at     = old_current || new_current
+        self.current_sign_in_at  = new_current
+
+        old_current, new_current = self.current_sign_in_ip, request.remote_ip
+        self.last_sign_in_ip     = old_current || new_current
+        self.current_sign_in_ip  = new_current
+
+        self.sign_in_count ||= 0
+        self.sign_in_count += 1
+      end
+
+      def update_tracked_fields!(request)
+        update_tracked_fields(request)
+        save(validate: false) or raise "Devise trackable could not save #{inspect}." \
+          "Please make sure a model using trackable can be saved at sign in."
+      end
+    end
+  end
+end
diff --git a/lib/devise/models/validatable.rb b/lib/devise/models/validatable.rb
new file mode 100644
index 0000000..2bfdf45
--- /dev/null
+++ b/lib/devise/models/validatable.rb
@@ -0,0 +1,66 @@
+module Devise
+  module Models
+    # Validatable creates all needed validations for a user email and password.
+    # It's optional, given you may want to create the validations by yourself.
+    # Automatically validate if the email is present, unique and its format is
+    # valid. Also tests presence of password, confirmation and length.
+    #
+    # == Options
+    #
+    # Validatable adds the following options to devise_for:
+    #
+    #   * +email_regexp+: the regular expression used to validate e-mails;
+    #   * +password_length+: a range expressing password length. Defaults to 8..128.
+    #
+    module Validatable
+      # All validations used by this module.
+      VALIDATIONS = [ :validates_presence_of, :validates_uniqueness_of, :validates_format_of,
+                      :validates_confirmation_of, :validates_length_of ].freeze
+
+      def self.required_fields(klass)
+        []
+      end
+
+      def self.included(base)
+        base.extend ClassMethods
+        assert_validations_api!(base)
+
+        base.class_eval do
+          validates_presence_of   :email, if: :email_required?
+          validates_uniqueness_of :email, allow_blank: true, if: :email_changed?
+          validates_format_of     :email, with: email_regexp, allow_blank: true, if: :email_changed?
+
+          validates_presence_of     :password, if: :password_required?
+          validates_confirmation_of :password, if: :password_required?
+          validates_length_of       :password, within: password_length, allow_blank: true
+        end
+      end
+
+      def self.assert_validations_api!(base) #:nodoc:
+        unavailable_validations = VALIDATIONS.select { |v| !base.respond_to?(v) }
+
+        unless unavailable_validations.empty?
+          raise "Could not use :validatable module since #{base} does not respond " <<
+                "to the following methods: #{unavailable_validations.to_sentence}."
+        end
+      end
+
+    protected
+
+      # Checks whether a password is needed or not. For validations only.
+      # Passwords are always required if it's a new record, or if the password
+      # or confirmation are being set somewhere.
+      def password_required?
+        !persisted? || !password.nil? || !password_confirmation.nil?
+      end
+
+      def email_required?
+        true
+      end
+
+      module ClassMethods
+        Devise::Models.config(self, :email_regexp, :password_length)
+      end
+    end
+  end
+end
diff --git a/lib/devise/modules.rb b/lib/devise/modules.rb
new file mode 100644
index 0000000..2af8820
--- /dev/null
+++ b/lib/devise/modules.rb
@@ -0,0 +1,28 @@
+require 'active_support/core_ext/object/with_options'
+
+Devise.with_options model: true do |d|
+  # Strategies first
+  d.with_options strategy: true do |s|
+    routes = [nil, :new, :destroy]
+    s.add_module :database_authenticatable, controller: :sessions, route: { session: routes }
+    s.add_module :rememberable, no_input: true
+  end
+
+  # Other authentications
+  d.add_module :omniauthable, controller: :omniauth_callbacks,  route: :omniauth_callback
+
+  # Misc after
+  routes = [nil, :new, :edit]
+  d.add_module :recoverable,  controller: :passwords,     route: { password: routes }
+  d.add_module :registerable, controller: :registrations, route: { registration: (routes << :cancel) }
+  d.add_module :validatable
+
+  # The ones which can sign out after
+  routes = [nil, :new]
+  d.add_module :confirmable,  controller: :confirmations, route: { confirmation: routes }
+  d.add_module :lockable,     controller: :unlocks,       route: { unlock: routes }
+  d.add_module :timeoutable
+
+  # Stats for last, so we make sure the user is really signed in
+  d.add_module :trackable
+end
diff --git a/lib/devise/omniauth.rb b/lib/devise/omniauth.rb
new file mode 100644
index 0000000..ff342fd
--- /dev/null
+++ b/lib/devise/omniauth.rb
@@ -0,0 +1,28 @@
+begin
+  require "omniauth"
+  require "omniauth/version"
+rescue LoadError
+  warn "Could not load 'omniauth'. Please ensure you have the omniauth gem >= 1.0.0 installed and listed in your Gemfile."
+  raise
+end
+
+unless OmniAuth::VERSION =~ /^1\./
+  raise "You are using an old OmniAuth version, please ensure you have 1.0.0.pr2 version or later installed."
+end
+
+# Clean up the default path_prefix. It will be automatically set by Devise.
+OmniAuth.config.path_prefix = nil
+
+OmniAuth.config.on_failure = Proc.new do |env|
+  env['devise.mapping'] = Devise::Mapping.find_by_path!(env['PATH_INFO'], :path)
+  controller_name  = ActiveSupport::Inflector.camelize(env['devise.mapping'].controllers[:omniauth_callbacks])
+  controller_klass = ActiveSupport::Inflector.constantize("#{controller_name}Controller")
+  controller_klass.action(:failure).call(env)
+end
+
+module Devise
+  module OmniAuth
+    autoload :Config,      "devise/omniauth/config"
+    autoload :UrlHelpers,  "devise/omniauth/url_helpers"
+  end
+end
diff --git a/lib/devise/omniauth/config.rb b/lib/devise/omniauth/config.rb
new file mode 100644
index 0000000..e22d701
--- /dev/null
+++ b/lib/devise/omniauth/config.rb
@@ -0,0 +1,45 @@
+module Devise
+  module OmniAuth
+    class StrategyNotFound < NameError
+      def initialize(strategy)
+        @strategy = strategy
+        super("Could not find a strategy with name `#{strategy}'. " \
+          "Please ensure it is required or explicitly set it using the :strategy_class option.")
+      end
+    end
+
+    class Config
+      attr_accessor :strategy
+      attr_reader :args, :options, :provider, :strategy_name
+
+      def initialize(provider, args)
+        @provider       = provider
+        @args           = args
+        @options        = @args.last.is_a?(Hash) ? @args.last : {}
+        @strategy       = nil
+        @strategy_name  = options[:name] || @provider
+        @strategy_class = options.delete(:strategy_class)
+      end
+
+      def strategy_class
+        @strategy_class ||= find_strategy || autoload_strategy
+      end
+
+      def find_strategy
+        ::OmniAuth.strategies.find do |strategy_class|
+          strategy_class.to_s =~ /#{::OmniAuth::Utils.camelize(strategy_name)}$/ ||
+            strategy_class.default_options[:name] == strategy_name
+        end
+      end
+
+      def autoload_strategy
+        name = ::OmniAuth::Utils.camelize(provider.to_s)
+        if ::OmniAuth::Strategies.const_defined?(name)
+          ::OmniAuth::Strategies.const_get(name)
+        else
+          raise StrategyNotFound, name
+        end
+      end
+    end
+  end
+end
diff --git a/lib/devise/omniauth/url_helpers.rb b/lib/devise/omniauth/url_helpers.rb
new file mode 100644
index 0000000..dd123f6
--- /dev/null
+++ b/lib/devise/omniauth/url_helpers.rb
@@ -0,0 +1,18 @@
+module Devise
+  module OmniAuth
+    module UrlHelpers
+      def self.define_helpers(mapping)
+      end
+
+      def omniauth_authorize_path(resource_or_scope, *args)
+        scope = Devise::Mapping.find_scope!(resource_or_scope)
+        _devise_route_context.send("#{scope}_omniauth_authorize_path", *args)
+      end
+
+      def omniauth_callback_path(resource_or_scope, *args)
+        scope = Devise::Mapping.find_scope!(resource_or_scope)
+        _devise_route_context.send("#{scope}_omniauth_callback_path", *args)
+      end
+    end
+  end
+end
diff --git a/lib/devise/orm/active_record.rb b/lib/devise/orm/active_record.rb
new file mode 100644
index 0000000..0935cda
--- /dev/null
+++ b/lib/devise/orm/active_record.rb
@@ -0,0 +1,3 @@
+require 'orm_adapter/adapters/active_record'
+
+ActiveRecord::Base.extend Devise::Models
diff --git a/lib/devise/orm/mongoid.rb b/lib/devise/orm/mongoid.rb
new file mode 100644
index 0000000..31a0736
--- /dev/null
+++ b/lib/devise/orm/mongoid.rb
@@ -0,0 +1,3 @@
+require 'orm_adapter/adapters/mongoid'
+
+Mongoid::Document::ClassMethods.send :include, Devise::Models
diff --git a/lib/devise/parameter_filter.rb b/lib/devise/parameter_filter.rb
new file mode 100644
index 0000000..63d06f9
--- /dev/null
+++ b/lib/devise/parameter_filter.rb
@@ -0,0 +1,40 @@
+module Devise
+  class ParameterFilter
+    def initialize(case_insensitive_keys, strip_whitespace_keys)
+      @case_insensitive_keys = case_insensitive_keys || []
+      @strip_whitespace_keys = strip_whitespace_keys || []
+    end
+
+    def filter(conditions)
+      conditions = stringify_params(conditions.dup)
+
+      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))
+
+      conditions
+    end
+
+    def filtered_hash_by_method_for_given_keys(conditions, method, condition_keys)
+      condition_keys.each do |k|
+        value = conditions[k]
+        conditions[k] = value.send(method) if value.respond_to?(method)
+      end
+
+      conditions
+    end
+
+    # Force keys to be string to avoid injection on mongoid related database.
+    def stringify_params(conditions)
+      return conditions unless conditions.is_a?(Hash)
+      conditions.each do |k, v|
+        conditions[k] = v.to_s if param_requires_string_conversion?(v)
+      end
+    end
+
+    private
+
+    def param_requires_string_conversion?(value)
+      true
+    end
+  end
+end
diff --git a/lib/devise/parameter_sanitizer.rb b/lib/devise/parameter_sanitizer.rb
new file mode 100644
index 0000000..7b10cf5
--- /dev/null
+++ b/lib/devise/parameter_sanitizer.rb
@@ -0,0 +1,99 @@
+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
+        default_for(kind)
+      end
+    end
+
+    def sanitize(kind)
+      if block = @blocks[kind]
+        block.call(default_params)
+      else
+        default_sanitize(kind)
+      end
+    end
+
+    private
+
+    def default_for(kind)
+      raise ArgumentError, "a block is expected in Devise base sanitizer"
+    end
+
+    def default_sanitize(kind)
+      default_params
+    end
+
+    def default_params
+      params.fetch(resource_name, {})
+    end
+  end
+
+  class ParameterSanitizer < BaseSanitizer
+    def initialize(*)
+      super
+      @permitted = Hash.new { |h,k| h[k] = attributes_for(k) }
+    end
+
+    def sign_in
+      permit self.for(:sign_in)
+    end
+
+    def sign_up
+      permit self.for(:sign_up)
+    end
+
+    def account_update
+      permit self.for(:account_update)
+    end
+
+    private
+
+    # TODO: We do need to flatten so it works with strong_parameters
+    # gem. We should drop it once we move to Rails 4 only support.
+    def permit(keys)
+      default_params.permit(*Array(keys))
+    end
+
+    # Change for(kind) to return the values in the @permitted
+    # hash, allowing the developer to customize at runtime.
+    def default_for(kind)
+      @permitted[kind] || raise("No sanitizer provided for #{kind}")
+    end
+
+    def default_sanitize(kind)
+      if respond_to?(kind, true)
+        send(kind)
+      else
+        raise NotImplementedError, "Devise doesn't know how to sanitize parameters for #{kind}"
+      end
+    end
+
+    def attributes_for(kind)
+      case kind
+      when :sign_in
+        auth_keys + [:password, :remember_me]
+      when :sign_up
+        auth_keys + [:password, :password_confirmation]
+      when :account_update
+        auth_keys + [:password, :password_confirmation, :current_password]
+      end
+    end
+
+    def auth_keys
+      @auth_keys ||= @resource_class.authentication_keys.respond_to?(:keys) ?
+                       @resource_class.authentication_keys.keys : @resource_class.authentication_keys
+    end
+  end
+end
diff --git a/lib/devise/rails.rb b/lib/devise/rails.rb
new file mode 100644
index 0000000..14de237
--- /dev/null
+++ b/lib/devise/rails.rb
@@ -0,0 +1,56 @@
+require 'devise/rails/routes'
+require 'devise/rails/warden_compat'
+
+module Devise
+  class Engine < ::Rails::Engine
+    config.devise = Devise
+
+    # Initialize Warden and copy its configurations.
+    config.app_middleware.use Warden::Manager do |config|
+      Devise.warden_config = config
+    end
+
+    # Force routes to be loaded if we are doing any eager load.
+    config.before_eager_load { |app| app.reload_routes! }
+
+    initializer "devise.url_helpers" do
+      Devise.include_helpers(Devise::Controllers)
+    end
+
+    initializer "devise.omniauth" do |app|
+      Devise.omniauth_configs.each do |provider, config|
+        app.middleware.use config.strategy_class, *config.args do |strategy|
+          config.strategy = strategy
+        end
+      end
+
+      if Devise.omniauth_configs.any?
+        Devise.include_helpers(Devise::OmniAuth)
+      end
+    end
+
+    initializer "devise.secret_key" do |app|
+      if app.respond_to?(:secrets)
+        Devise.secret_key ||= app.secrets.secret_key_base
+      elsif app.config.respond_to?(:secret_key_base)
+        Devise.secret_key ||= app.config.secret_key_base
+      end
+
+      Devise.token_generator ||=
+        if secret_key = Devise.secret_key
+          Devise::TokenGenerator.new(
+            Devise::CachingKeyGenerator.new(Devise::KeyGenerator.new(secret_key))
+          )
+        end
+    end
+
+    initializer "devise.fix_routes_proxy_missing_respond_to_bug" do
+      # Deprecate: Remove once we move to Rails 4 only.
+      ActionDispatch::Routing::RoutesProxy.class_eval do
+        def respond_to?(method, include_private = false)
+          super || routes.url_helpers.respond_to?(method)
+        end
+      end
+    end
+  end
+end
diff --git a/lib/devise/rails/routes.rb b/lib/devise/rails/routes.rb
new file mode 100644
index 0000000..8048f99
--- /dev/null
+++ b/lib/devise/rails/routes.rb
@@ -0,0 +1,495 @@
+require "active_support/core_ext/object/try"
+require "active_support/core_ext/hash/slice"
+
+module ActionDispatch::Routing
+  class RouteSet #:nodoc:
+    # Ensure Devise modules are included only after loading routes, because we
+    # need devise_for mappings already declared to create filters and helpers.
+    def finalize_with_devise!
+      result = finalize_without_devise!
+
+      @devise_finalized ||= begin
+        if Devise.router_name.nil? && defined?(@devise_finalized) && self != Rails.application.try(:routes)
+          warn "[DEVISE] We have detected that you are using devise_for inside engine routes. " \
+            "In this case, you probably want to set Devise.router_name = MOUNT_POINT, where "   \
+            "MOUNT_POINT is a symbol representing where this engine will be mounted at. For "   \
+            "now Devise will default the mount point to :main_app. You can explicitly set it"   \
+            " to :main_app as well in case you want to keep the current behavior."
+        end
+
+        Devise.configure_warden!
+        Devise.regenerate_helpers!
+        true
+      end
+
+      result
+    end
+    alias_method_chain :finalize!, :devise
+  end
+
+  class Mapper
+    # Includes devise_for method for routes. This method is responsible to
+    # generate all needed routes for devise, based on what modules you have
+    # defined in your model.
+    #
+    # ==== Examples
+    #
+    # Let's say you have an User model configured to use authenticatable,
+    # confirmable and recoverable modules. After creating this inside your routes:
+    #
+    #   devise_for :users
+    #
+    # This method is going to look inside your User model and create the
+    # needed routes:
+    #
+    #  # Session routes for Authenticatable (default)
+    #       new_user_session GET    /users/sign_in                    {controller:"devise/sessions", action:"new"}
+    #           user_session POST   /users/sign_in                    {controller:"devise/sessions", action:"create"}
+    #   destroy_user_session DELETE /users/sign_out                   {controller:"devise/sessions", action:"destroy"}
+    #
+    #  # Password routes for Recoverable, if User model has :recoverable configured
+    #      new_user_password GET    /users/password/new(.:format)     {controller:"devise/passwords", action:"new"}
+    #     edit_user_password GET    /users/password/edit(.:format)    {controller:"devise/passwords", action:"edit"}
+    #          user_password PUT    /users/password(.:format)         {controller:"devise/passwords", action:"update"}
+    #                        POST   /users/password(.:format)         {controller:"devise/passwords", action:"create"}
+    #
+    #  # Confirmation routes for Confirmable, if User model has :confirmable configured
+    #  new_user_confirmation GET    /users/confirmation/new(.:format) {controller:"devise/confirmations", action:"new"}
+    #      user_confirmation GET    /users/confirmation(.:format)     {controller:"devise/confirmations", action:"show"}
+    #                        POST   /users/confirmation(.:format)     {controller:"devise/confirmations", action:"create"}
+    #
+    # ==== Routes integration
+    #
+    # +devise_for+ is meant to play nicely with other routes methods. For example,
+    # by calling +devise_for+ inside a namespace, it automatically nests your devise
+    # controllers:
+    #
+    #     namespace :publisher do
+    #       devise_for :account
+    #     end
+    #
+    # The snippet above will use publisher/sessions controller instead of devise/sessions
+    # controller. You can revert this change or configure it directly by passing the :module
+    # option described below to +devise_for+.
+    #
+    # Also note that when you use a namespace it will affect all the helpers and methods
+    # for controllers and views. For example, using the above setup you'll end with
+    # following methods: current_publisher_account, authenticate_publisher_account!,
+    # publisher_account_signed_in, etc.
+    #
+    # The only aspect not affect by the router configuration is the model name. The
+    # model name can be explicitly set via the :class_name option.
+    #
+    # ==== Options
+    #
+    # You can configure your routes with some options:
+    #
+    #  * class_name: setup a different class to be looked up by devise, if it cannot be
+    #    properly found by the route name.
+    #
+    #      devise_for :users, class_name: 'Account'
+    #
+    #  * path: allows you to setup path name that will be used, as rails routes does.
+    #    The following route configuration would setup your route as /accounts instead of /users:
+    #
+    #      devise_for :users, path: 'accounts'
+    #
+    #  * singular: setup the singular name for the given resource. This is used as the instance variable
+    #    name in controller, as the name in routes and the scope given to warden.
+    #
+    #      devise_for :users, singular: :user
+    #
+    #  * path_names: configure different path names to overwrite defaults :sign_in, :sign_out, :sign_up,
+    #    :password, :confirmation, :unlock.
+    #
+    #      devise_for :users, path_names: {
+    #        sign_in: 'login', sign_out: 'logout',
+    #        password: 'secret', confirmation: 'verification',
+    #        registration: 'register', edit: 'edit/profile'
+    #      }
+    #
+    #  * controllers: the controller which should be used. All routes by default points to Devise controllers.
+    #    However, if you want them to point to custom controller, you should do:
+    #
+    #      devise_for :users, controllers: { sessions: "users/sessions" }
+    #
+    #  * failure_app: a rack app which is invoked whenever there is a failure. Strings representing a given
+    #    are also allowed as parameter.
+    #
+    #  * sign_out_via: the HTTP method(s) accepted for the :sign_out action (default: :get),
+    #    if you wish to restrict this to accept only :post or :delete requests you should do:
+    #
+    #      devise_for :users, sign_out_via: [ :post, :delete ]
+    #
+    #    You need to make sure that your sign_out controls trigger a request with a matching HTTP method.
+    #
+    #  * module: the namespace to find controllers (default: "devise", thus
+    #    accessing devise/sessions, devise/registrations, and so on). If you want
+    #    to namespace all at once, use module:
+    #
+    #      devise_for :users, module: "users"
+    #
+    #  * skip: tell which controller you want to skip routes from being created.
+    #    It accepts :all as an option, meaning it will not generate any route at all:
+    #
+    #      devise_for :users, skip: :sessions
+    #
+    #  * only: the opposite of :skip, tell which controllers only to generate routes to:
+    #
+    #      devise_for :users, only: :sessions
+    #
+    #  * skip_helpers: skip generating Devise url helpers like new_session_path(@user).
+    #    This is useful to avoid conflicts with previous routes and is false by default.
+    #    It accepts true as option, meaning it will skip all the helpers for the controllers
+    #    given in :skip but it also accepts specific helpers to be skipped:
+    #
+    #      devise_for :users, skip: [:registrations, :confirmations], skip_helpers: true
+    #      devise_for :users, skip_helpers: [:registrations, :confirmations]
+    #
+    #  * format: include "(.:format)" in the generated routes? true by default, set to false to disable:
+    #
+    #      devise_for :users, format: false
+    #
+    #  * constraints: works the same as Rails' constraints
+    #
+    #  * defaults: works the same as Rails' defaults
+    #
+    #  * router_name: allows application level router name to be overwritten for the current scope
+    #
+    # ==== Scoping
+    #
+    # Following Rails 3 routes DSL, you can nest devise_for calls inside a scope:
+    #
+    #   scope "/my" do
+    #     devise_for :users
+    #   end
+    #
+    # However, since Devise uses the request path to retrieve the current user,
+    # this has one caveat: If you are using a dynamic segment, like so ...
+    #
+    #   scope ":locale" do
+    #     devise_for :users
+    #   end
+    #
+    # you are required to configure default_url_options in your
+    # ApplicationController class, so Devise can pick it:
+    #
+    #   class ApplicationController < ActionController::Base
+    #     def self.default_url_options
+    #       { locale: I18n.locale }
+    #     end
+    #   end
+    #
+    # ==== Adding custom actions to override controllers
+    #
+    # You can pass a block to devise_for that will add any routes defined in the block to Devise's
+    # list of known actions.  This is important if you add a custom action to a controller that
+    # overrides an out of the box Devise controller.
+    # For example:
+    #
+    #    class RegistrationsController < Devise::RegistrationsController
+    #      def update
+    #         # do something different here
+    #      end
+    #
+    #      def deactivate
+    #        # not a standard action
+    #        # deactivate code here
+    #      end
+    #    end
+    #
+    # In order to get Devise to recognize the deactivate action, your devise_scope entry should look like this:
+    #
+    #     devise_scope :owner do
+    #       post "deactivate", to: "registrations#deactivate", as: "deactivate_registration"
+    #     end
+    #
+    def devise_for(*resources)
+      @devise_finalized = false
+      raise_no_secret_key unless Devise.secret_key
+      options = resources.extract_options!
+
+      options[:as]          ||= @scope[:as]     if @scope[:as].present?
+      options[:module]      ||= @scope[:module] if @scope[:module].present?
+      options[:path_prefix] ||= @scope[:path]   if @scope[:path].present?
+      options[:path_names]    = (@scope[:path_names] || {}).merge(options[:path_names] || {})
+      options[:constraints]   = (@scope[:constraints] || {}).merge(options[:constraints] || {})
+      options[:defaults]      = (@scope[:defaults] || {}).merge(options[:defaults] || {})
+      options[:options]       = @scope[:options] || {}
+      options[:options][:format] = false if options[:format] == false
+
+      resources.map!(&:to_sym)
+
+      resources.each do |resource|
+        mapping = Devise.add_mapping(resource, options)
+
+        begin
+          raise_no_devise_method_error!(mapping.class_name) unless mapping.to.respond_to?(:devise)
+        rescue NameError => e
+          raise unless mapping.class_name == resource.to_s.classify
+          warn "[WARNING] You provided devise_for #{resource.inspect} but there is " \
+            "no model #{mapping.class_name} defined in your application"
+          next
+        rescue NoMethodError => e
+          raise unless e.message.include?("undefined method `devise'")
+          raise_no_devise_method_error!(mapping.class_name)
+        end
+
+        if options[:controllers] && options[:controllers][:omniauth_callbacks]
+          unless mapping.omniauthable?
+            raise ArgumentError, "Mapping omniauth_callbacks on a resource that is not omniauthable\n" \
+              "Please add `devise :omniauthable` to the `#{mapping.class_name}` model"
+          end
+        end
+
+        routes = mapping.used_routes
+
+        devise_scope mapping.name do
+          with_devise_exclusive_scope mapping.fullpath, mapping.name, options do
+            routes.each { |mod| send("devise_#{mod}", mapping, mapping.controllers) }
+          end
+        end
+      end
+    end
+
+    # Allow you to add authentication request from the router.
+    # Takes an optional scope and block to provide constraints
+    # on the model instance itself.
+    #
+    #   authenticate do
+    #     resources :post
+    #   end
+    #
+    #   authenticate(:admin) do
+    #     resources :users
+    #   end
+    #
+    #   authenticate :user, lambda {|u| u.role == "admin"} do
+    #     root to: "admin/dashboard#show", as: :user_root
+    #   end
+    #
+    def authenticate(scope=nil, block=nil)
+      constraints_for(:authenticate!, scope, block) do
+        yield
+      end
+    end
+
+    # Allow you to route based on whether a scope is authenticated. You
+    # can optionally specify which scope and a block. The block accepts
+    # a model and allows extra constraints to be done on the instance.
+    #
+    #   authenticated :admin do
+    #     root to: 'admin/dashboard#show', as: :admin_root
+    #   end
+    #
+    #   authenticated do
+    #     root to: 'dashboard#show', as: :authenticated_root
+    #   end
+    #
+    #   authenticated :user, lambda {|u| u.role == "admin"} do
+    #     root to: "admin/dashboard#show", as: :user_root
+    #   end
+    #
+    #   root to: 'landing#show'
+    #
+    def authenticated(scope=nil, block=nil)
+      constraints_for(:authenticate?, scope, block) do
+        yield
+      end
+    end
+
+    # Allow you to route based on whether a scope is *not* authenticated.
+    # You can optionally specify which scope.
+    #
+    #   unauthenticated do
+    #     as :user do
+    #       root to: 'devise/registrations#new'
+    #     end
+    #   end
+    #
+    #   root to: 'dashboard#show'
+    #
+    def unauthenticated(scope=nil)
+      constraint = lambda do |request|
+        not request.env["warden"].authenticate? scope: scope
+      end
+
+      constraints(constraint) do
+        yield
+      end
+    end
+
+    # Sets the devise scope to be used in the controller. If you have custom routes,
+    # you are required to call this method (also aliased as :as) in order to specify
+    # to which controller it is targetted.
+    #
+    #   as :user do
+    #     get "sign_in", to: "devise/sessions#new"
+    #   end
+    #
+    # Notice you cannot have two scopes mapping to the same URL. And remember, if
+    # you try to access a devise controller without specifying a scope, it will
+    # raise ActionNotFound error.
+    #
+    # Also be aware of that 'devise_scope' and 'as' use the singular form of the
+    # noun where other devise route commands expect the plural form. This would be a
+    # good and working example.
+    #
+    #  devise_scope :user do
+    #    get "/some/route" => "some_devise_controller"
+    #  end
+    #  devise_for :users
+    #
+    # Notice and be aware of the differences above between :user and :users
+    def devise_scope(scope)
+      constraint = lambda do |request|
+        request.env["devise.mapping"] = Devise.mappings[scope]
+        true
+      end
+
+      constraints(constraint) do
+        yield
+      end
+    end
+    alias :as :devise_scope
+
+    protected
+
+      def devise_session(mapping, controllers) #:nodoc:
+        resource :session, only: [], controller: controllers[:sessions], path: "" do
+          get   :new,     path: mapping.path_names[:sign_in],  as: "new"
+          post  :create,  path: mapping.path_names[:sign_in]
+          match :destroy, path: mapping.path_names[:sign_out], as: "destroy", via: mapping.sign_out_via
+        end
+      end
+
+      def devise_password(mapping, controllers) #:nodoc:
+        resource :password, only: [:new, :create, :edit, :update],
+          path: mapping.path_names[:password], controller: controllers[:passwords]
+      end
+
+      def devise_confirmation(mapping, controllers) #:nodoc:
+        resource :confirmation, only: [:new, :create, :show],
+          path: mapping.path_names[:confirmation], controller: controllers[:confirmations]
+      end
+
+      def devise_unlock(mapping, controllers) #:nodoc:
+        if mapping.to.unlock_strategy_enabled?(:email)
+          resource :unlock, only: [:new, :create, :show],
+            path: mapping.path_names[:unlock], controller: controllers[:unlocks]
+        end
+      end
+
+      def devise_registration(mapping, controllers) #:nodoc:
+        path_names = {
+          new: mapping.path_names[:sign_up],
+          edit: mapping.path_names[:edit],
+          cancel: mapping.path_names[:cancel]
+        }
+
+        options = {
+          only: [:new, :create, :edit, :update, :destroy],
+          path: mapping.path_names[:registration],
+          path_names: path_names,
+          controller: controllers[:registrations]
+        }
+
+        resource :registration, options do
+          get :cancel
+        end
+      end
+
+      def devise_omniauth_callback(mapping, controllers) #:nodoc:
+        if mapping.fullpath =~ /:[a-zA-Z_]/
+          raise <<-ERROR
+Devise does not support scoping omniauth callbacks under a dynamic segment
+and you have set #{mapping.fullpath.inspect}. You can work around by passing
+`skip: :omniauth_callbacks` and manually defining the routes. Here is an example:
+
+    match "/users/auth/:provider",
+      constraints: { provider: /google|facebook/ },
+      to: "devise/omniauth_callbacks#passthru",
+      as: :omniauth_authorize,
+      via: [:get, :post]
+
+    match "/users/auth/:action/callback",
+      constraints: { action: /google|facebook/ },
+      to: "devise/omniauth_callbacks",
+      as: :omniauth_callback,
+      via: [:get, :post]
+ERROR
+        end
+
+        path, @scope[:path] = @scope[:path], nil
+        path_prefix = Devise.omniauth_path_prefix || "/#{mapping.fullpath}/auth".squeeze("/")
+
+        set_omniauth_path_prefix!(path_prefix)
+
+        providers = Regexp.union(mapping.to.omniauth_providers.map(&:to_s))
+
+        match "#{path_prefix}/:provider",
+          constraints: { provider: providers },
+          to: "#{controllers[:omniauth_callbacks]}#passthru",
+          as: :omniauth_authorize,
+          via: [:get, :post]
+
+        match "#{path_prefix}/:action/callback",
+          constraints: { action: providers },
+          to: "#{controllers[:omniauth_callbacks]}#:action",
+          as: :omniauth_callback,
+          via: [:get, :post]
+      ensure
+        @scope[:path] = path
+      end
+
+      def with_devise_exclusive_scope(new_path, new_as, options) #:nodoc:
+        current_scope = @scope.dup
+
+        exclusive = { as: new_as, path: new_path, module: nil }
+        exclusive.merge!(options.slice(:constraints, :defaults, :options))
+
+        exclusive.each_pair { |key, value| @scope[key] = value }
+        yield
+      ensure
+        @scope = current_scope
+      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" \
+            "1) You are manually setting OmniAuth.config.path_prefix and it doesn't match the Devise one\n" \
+            "2) You are setting :omniauthable in more than one model\n" \
+            "3) You changed your Devise routes/OmniAuth setting and haven't restarted your server"
+        else
+          ::OmniAuth.config.path_prefix = path_prefix
+        end
+      end
+
+      def raise_no_secret_key #:nodoc:
+        raise <<-ERROR
+Devise.secret_key was not set. Please add the following to your Devise initializer:
+
+  config.secret_key = '#{SecureRandom.hex(64)}'
+
+Please ensure you restarted your application after installing Devise or setting the key.
+ERROR
+      end
+
+      def raise_no_devise_method_error!(klass) #:nodoc:
+        raise "#{klass} does not respond to 'devise' method. This usually means you haven't " \
+          "loaded your ORM file or it's being loaded too late. To fix it, be sure to require 'devise/orm/YOUR_ORM' " \
+          "inside 'config/initializers/devise.rb' or before your application definition in 'config/application.rb'"
+      end
+  end
+end
diff --git a/lib/devise/rails/warden_compat.rb b/lib/devise/rails/warden_compat.rb
new file mode 100644
index 0000000..79bed40
--- /dev/null
+++ b/lib/devise/rails/warden_compat.rb
@@ -0,0 +1,22 @@
+module Warden::Mixins::Common
+  def request
+    @request ||= ActionDispatch::Request.new(env)
+  end
+
+  # Deprecate: Remove this check once we move to Rails 4 only.
+  NULL_STORE =
+    defined?(ActionController::RequestForgeryProtection::ProtectionMethods::NullSession::NullSessionHash) ?
+      ActionController::RequestForgeryProtection::ProtectionMethods::NullSession::NullSessionHash : nil
+
+  def reset_session!
+    # Calling reset_session on NULL_STORE causes it fail.
+    # This is a bug that needs to be fixed in Rails.
+    unless NULL_STORE && request.session.is_a?(NULL_STORE)
+      request.reset_session
+    end
+  end
+
+  def cookies
+    request.cookie_jar
+  end
+end
diff --git a/lib/devise/strategies/authenticatable.rb b/lib/devise/strategies/authenticatable.rb
new file mode 100644
index 0000000..1e2055e
--- /dev/null
+++ b/lib/devise/strategies/authenticatable.rb
@@ -0,0 +1,173 @@
+require 'devise/strategies/base'
+
+module Devise
+  module Strategies
+    # This strategy should be used as basis for authentication strategies. It retrieves
+    # parameters both from params or from http authorization headers. See database_authenticatable
+    # for an example.
+    class Authenticatable < Base
+      attr_accessor :authentication_hash, :authentication_type, :password
+
+      def store?
+        super && !mapping.to.skip_session_storage.include?(authentication_type)
+      end
+
+      def valid?
+        valid_for_params_auth? || valid_for_http_auth?
+      end
+
+      # Override and set to false for things like OmniAuth that technically
+      # run through Authentication (user_set) very often, which would normally
+      # reset CSRF data in the session
+      def clean_up_csrf?
+        true
+      end
+
+    private
+
+      # Receives a resource and check if it is valid by calling valid_for_authentication?
+      # An optional block that will be triggered while validating can be optionally
+      # given as parameter. Check Devise::Models::Authenticable.valid_for_authentication?
+      # for more information.
+      #
+      # In case the resource can't be validated, it will fail with the given
+      # unauthenticated_message.
+      def validate(resource, &block)
+        result = resource && resource.valid_for_authentication?(&block)
+
+        if result
+          true
+        else
+          if resource
+            fail!(resource.unauthenticated_message)
+          end
+          false
+        end
+      end
+
+      # Get values from params and set in the resource.
+      def remember_me(resource)
+        resource.remember_me = remember_me? if resource.respond_to?(:remember_me=)
+      end
+
+      # Should this resource be marked to be remembered?
+      def remember_me?
+        valid_params? && Devise::TRUE_VALUES.include?(params_auth_hash[:remember_me])
+      end
+
+      # Check if this is a valid strategy for http authentication by:
+      #
+      #   * Validating if the model allows params authentication;
+      #   * If any of the authorization headers were sent;
+      #   * If all authentication keys are present;
+      #
+      def valid_for_http_auth?
+        http_authenticatable? && request.authorization && with_authentication_hash(:http_auth, http_auth_hash)
+      end
+
+      # Check if this is a valid strategy for params authentication by:
+      #
+      #   * Validating if the model allows params authentication;
+      #   * If the request hits the sessions controller through POST;
+      #   * If the params[scope] returns a hash with credentials;
+      #   * If all authentication keys are present;
+      #
+      def valid_for_params_auth?
+        params_authenticatable? && valid_params_request? &&
+          valid_params? && with_authentication_hash(:params_auth, params_auth_hash)
+      end
+
+      # Check if the model accepts this strategy as http authenticatable.
+      def http_authenticatable?
+        mapping.to.http_authenticatable?(authenticatable_name)
+      end
+
+      # Check if the model accepts this strategy as params authenticatable.
+      def params_authenticatable?
+        mapping.to.params_authenticatable?(authenticatable_name)
+      end
+
+      # Extract the appropriate subhash for authentication from params.
+      def params_auth_hash
+        params[scope]
+      end
+
+      # Extract a hash with attributes:values from the http params.
+      def http_auth_hash
+        keys = [http_authentication_key, :password]
+        Hash[*keys.zip(decode_credentials).flatten]
+      end
+
+      # By default, a request is valid if the controller set the proper env variable.
+      def valid_params_request?
+        !!env["devise.allow_params_authentication"]
+      end
+
+      # If the request is valid, finally check if params_auth_hash returns a hash.
+      def valid_params?
+        params_auth_hash.is_a?(Hash)
+      end
+
+      # Check if password is present.
+      def valid_password?
+        password.present?
+      end
+
+      # Helper to decode credentials from HTTP.
+      def decode_credentials
+        return [] unless request.authorization && request.authorization =~ /^Basic (.*)/m
+        Base64.decode64($1).split(/:/, 2)
+      end
+
+      # Sets the authentication hash and the password from params_auth_hash or http_auth_hash.
+      def with_authentication_hash(auth_type, auth_values)
+        self.authentication_hash, self.authentication_type = {}, auth_type
+        self.password = auth_values[:password]
+
+        parse_authentication_key_values(auth_values, authentication_keys) &&
+        parse_authentication_key_values(request_values, request_keys)
+      end
+
+      def authentication_keys
+        @authentication_keys ||= mapping.to.authentication_keys
+      end
+
+      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
+
+      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
+
+      def parse_authentication_key_values(hash, keys)
+        keys.each do |key, enforce|
+          value = hash[key].presence
+          if value
+            self.authentication_hash[key] = value
+          else
+            return false unless enforce == false
+          end
+        end
+        true
+      end
+
+      # Holds the authenticatable name for this class. Devise::Strategies::DatabaseAuthenticatable
+      # becomes simply :database.
+      def authenticatable_name
+        @authenticatable_name ||=
+          ActiveSupport::Inflector.underscore(self.class.name.split("::").last).
+            sub("_authenticatable", "").to_sym
+      end
+    end
+  end
+end
diff --git a/lib/devise/strategies/base.rb b/lib/devise/strategies/base.rb
new file mode 100644
index 0000000..ee5c8c7
--- /dev/null
+++ b/lib/devise/strategies/base.rb
@@ -0,0 +1,20 @@
+module Devise
+  module Strategies
+    # Base strategy for Devise. Responsible for verifying correct scope and mapping.
+    class Base < ::Warden::Strategies::Base
+      # Whenever CSRF cannot be verified, we turn off any kind of storage
+      def store?
+        !env["devise.skip_storage"]
+      end
+
+      # Checks if a valid scope was given for devise and find mapping based on this scope.
+      def mapping
+        @mapping ||= begin
+          mapping = Devise.mappings[scope]
+          raise "Could not find mapping for #{scope}" unless mapping
+          mapping
+        end
+      end
+    end
+  end
+end
diff --git a/lib/devise/strategies/database_authenticatable.rb b/lib/devise/strategies/database_authenticatable.rb
new file mode 100644
index 0000000..2a8e91d
--- /dev/null
+++ b/lib/devise/strategies/database_authenticatable.rb
@@ -0,0 +1,24 @@
+require 'devise/strategies/authenticatable'
+
+module Devise
+  module Strategies
+    # Default strategy for signing in a user, based on their email and password in the database.
+    class DatabaseAuthenticatable < Authenticatable
+      def authenticate!
+        resource  = valid_password? && mapping.to.find_for_database_authentication(authentication_hash)
+        encrypted = false
+
+        if validate(resource){ encrypted = true; resource.valid_password?(password) }
+          remember_me(resource)
+          resource.after_database_authentication
+          success!(resource)
+        end
+
+        mapping.to.new.password = password if !encrypted && Devise.paranoid
+        fail(:not_found_in_database) unless resource
+      end
+    end
+  end
+end
+
+Warden::Strategies.add(:database_authenticatable, Devise::Strategies::DatabaseAuthenticatable)
diff --git a/lib/devise/strategies/rememberable.rb b/lib/devise/strategies/rememberable.rb
new file mode 100644
index 0000000..6906627
--- /dev/null
+++ b/lib/devise/strategies/rememberable.rb
@@ -0,0 +1,58 @@
+require 'devise/strategies/authenticatable'
+
+module Devise
+  module Strategies
+    # Remember the user through the remember token. This strategy is responsible
+    # to verify whether there is a cookie with the remember token, and to
+    # recreate the user from this cookie if it exists. Must be called *before*
+    # authenticatable.
+    class Rememberable < Authenticatable
+      # A valid strategy for rememberable needs a remember token in the cookies.
+      def valid?
+        @remember_cookie = nil
+        remember_cookie.present?
+      end
+
+      # To authenticate a user we deserialize the cookie and attempt finding
+      # the record in the database. If the attempt fails, we pass to another
+      # strategy handle the authentication.
+      def authenticate!
+        resource = mapping.to.serialize_from_cookie(*remember_cookie)
+
+        unless resource
+          cookies.delete(remember_key)
+          return pass
+        end
+
+        if validate(resource)
+          remember_me(resource)
+          extend_remember_me_period(resource)
+          success!(resource)
+        end
+      end
+
+    private
+
+      def extend_remember_me_period(resource)
+        if resource.respond_to?(:extend_remember_period=)
+          resource.extend_remember_period = mapping.to.extend_remember_period
+        end
+      end
+
+      def remember_me?
+        true
+      end
+
+      def remember_key
+        mapping.to.rememberable_options.fetch(:key, "remember_#{scope}_token")
+      end
+
+      def remember_cookie
+        @remember_cookie ||= cookies.signed[remember_key]
+      end
+
+    end
+  end
+end
+
+Warden::Strategies.add(:rememberable, Devise::Strategies::Rememberable)
diff --git a/lib/devise/test_helpers.rb b/lib/devise/test_helpers.rb
new file mode 100644
index 0000000..65adb60
--- /dev/null
+++ b/lib/devise/test_helpers.rb
@@ -0,0 +1,132 @@
+module Devise
+  # Devise::TestHelpers provides a facility to test controllers in isolation
+  # when using ActionController::TestCase allowing you to quickly sign_in or
+  # sign_out a user. Do not use Devise::TestHelpers in integration tests.
+  #
+  # Notice you should not test Warden specific behavior (like Warden callbacks)
+  # using Devise::TestHelpers since it is a stub of the actual behavior. Such
+  # callbacks should be tested in your integration suite instead.
+  module TestHelpers
+    def self.included(base)
+      base.class_eval do
+        setup :setup_controller_for_warden, :warden if respond_to?(:setup)
+      end
+    end
+
+    # Override process to consider warden.
+    def process(*)
+      # Make sure we always return @response, a la ActionController::TestCase::Behaviour#process, even if warden interrupts
+      _catch_warden { super } || @response
+    end
+
+    # We need to setup the environment variables and the response in the controller.
+    def setup_controller_for_warden #:nodoc:
+      @request.env['action_controller.instance'] = @controller
+    end
+
+    # Quick access to Warden::Proxy.
+    def warden #:nodoc:
+      @warden ||= begin
+        manager = Warden::Manager.new(nil) do |config|
+          config.merge! Devise.warden_config
+        end
+        @request.env['warden'] = Warden::Proxy.new(@request.env, manager)
+      end
+    end
+
+    # sign_in a given resource by storing its keys in the session.
+    # This method bypass any warden authentication callback.
+    #
+    # Examples:
+    #
+    #   sign_in :user, @user   # sign_in(scope, resource)
+    #   sign_in @user          # sign_in(resource)
+    #
+    def sign_in(resource_or_scope, resource=nil)
+      scope    ||= Devise::Mapping.find_scope!(resource_or_scope)
+      resource ||= resource_or_scope
+      warden.instance_variable_get(:@users).delete(scope)
+      warden.session_serializer.store(resource, scope)
+    end
+
+    # Sign out a given resource or scope by calling logout on Warden.
+    # This method bypass any warden logout callback.
+    #
+    # Examples:
+    #
+    #   sign_out :user     # sign_out(scope)
+    #   sign_out @user     # sign_out(resource)
+    #
+    def sign_out(resource_or_scope)
+      scope = Devise::Mapping.find_scope!(resource_or_scope)
+      @controller.instance_variable_set(:"@current_#{scope}", nil)
+      user = warden.instance_variable_get(:@users).delete(scope)
+      warden.session_serializer.delete(scope, user)
+    end
+
+    protected
+
+    # Catch warden continuations and handle like the middleware would.
+    # Returns nil when interrupted, otherwise the normal result of the block.
+    def _catch_warden(&block)
+      result = catch(:warden, &block)
+
+      env = @controller.request.env
+
+      result ||= {}
+
+      # Set the response. In production, the rack result is returned
+      # from Warden::Manager#call, which the following is modelled on.
+      case result
+      when Array
+        if result.first == 401 && intercept_401?(env) # does this happen during testing?
+          _process_unauthenticated(env)
+        else
+          result
+        end
+      when Hash
+        _process_unauthenticated(env, result)
+      else
+        result
+      end
+    end
+
+    def _process_unauthenticated(env, options = {})
+      options[:action] ||= :unauthenticated
+      proxy = env['warden']
+      result = options[:result] || proxy.result
+
+      ret = case result
+      when :redirect
+        body = proxy.message || "You are being redirected to #{proxy.headers['Location']}"
+        [proxy.status, proxy.headers, [body]]
+      when :custom
+        proxy.custom_response
+      else
+        env["PATH_INFO"] = "/#{options[:action]}"
+        env["warden.options"] = options
+        Warden::Manager._run_callbacks(:before_failure, env, options)
+
+        status, headers, response = Devise.warden_config[:failure_app].call(env).to_a
+        @controller.response.headers.merge!(headers)
+        @controller.send :render, status: status, text: response.body,
+          content_type: headers["Content-Type"], location: headers["Location"]
+        nil # causes process return @response
+      end
+
+      # ensure that the controller response is set up. In production, this is
+      # not necessary since warden returns the results to rack. However, at
+      # testing time, we want the response to be available to the testing
+      # framework to verify what would be returned to rack.
+      if ret.is_a?(Array)
+        # ensure the controller response is set to our response.
+        @controller.response ||= @response
+        @response.status = ret.first
+        @response.headers = ret.second
+        @response.body = ret.third
+      end
+
+      ret
+    end
+  end
+end
diff --git a/lib/devise/time_inflector.rb b/lib/devise/time_inflector.rb
new file mode 100644
index 0000000..94795af
--- /dev/null
+++ b/lib/devise/time_inflector.rb
@@ -0,0 +1,14 @@
+require "active_support/core_ext/module/delegation"
+
+module Devise
+  class TimeInflector
+    include ActionView::Helpers::DateHelper
+
+    class << self
+      attr_reader :instance
+      delegate :time_ago_in_words, to: :instance
+    end
+
+    @instance = new
+  end
+end
diff --git a/lib/devise/token_generator.rb b/lib/devise/token_generator.rb
new file mode 100644
index 0000000..2a4b89f
--- /dev/null
+++ b/lib/devise/token_generator.rb
@@ -0,0 +1,70 @@
+# Deprecate: Copied verbatim from Rails source, remove once we move to Rails 4 only.
+require 'thread_safe'
+require 'openssl'
+require 'securerandom'
+
+module Devise
+  class TokenGenerator
+    def initialize(key_generator, digest="SHA256")
+      @key_generator = key_generator
+      @digest = digest
+    end
+
+    def digest(klass, column, value)
+      value.present? && OpenSSL::HMAC.hexdigest(@digest, key_for(column), value.to_s)
+    end
+
+    def generate(klass, column)
+      key = key_for(column)
+
+      loop do
+        raw = Devise.friendly_token
+        enc = OpenSSL::HMAC.hexdigest(@digest, key, raw)
+        break [raw, enc] unless klass.to_adapter.find_first({ column => enc })
+      end
+    end
+
+    private
+
+    def key_for(column)
+      @key_generator.generate_key("Devise #{column}")
+    end
+  end
+
+  # KeyGenerator is a simple wrapper around OpenSSL's implementation of PBKDF2
+  # It can be used to derive a number of keys for various purposes from a given secret.
+  # This lets Rails applications have a single secure secret, but avoid reusing that
+  # key in multiple incompatible contexts.
+  class KeyGenerator
+    def initialize(secret, options = {})
+      @secret = secret
+      # The default iterations are higher than required for our key derivation uses
+      # on the off chance someone uses this for password storage
+      @iterations = options[:iterations] || 2**16
+    end
+
+    # Returns a derived key suitable for use.  The default key_size is chosen
+    # to be compatible with the default settings of ActiveSupport::MessageVerifier.
+    # i.e. OpenSSL::Digest::SHA1#block_length
+    def generate_key(salt, key_size=64)
+      OpenSSL::PKCS5.pbkdf2_hmac_sha1(@secret, salt, @iterations, key_size)
+    end
+  end
+
+  # CachingKeyGenerator is a wrapper around KeyGenerator which allows users to avoid
+  # re-executing the key generation process when it's called using the same salt and
+  # key_size
+  class CachingKeyGenerator
+    def initialize(key_generator)
+      @key_generator = key_generator
+      @cache_keys = ThreadSafe::Cache.new
+    end
+
+    # Returns a derived key suitable for use.  The default key_size is chosen
+    # to be compatible with the default settings of ActiveSupport::MessageVerifier.
+    # i.e. OpenSSL::Digest::SHA1#block_length
+    def generate_key(salt, key_size=64)
+      @cache_keys["#{salt}#{key_size}"] ||= @key_generator.generate_key(salt, key_size)
+    end
+  end
+end
diff --git a/lib/devise/version.rb b/lib/devise/version.rb
new file mode 100644
index 0000000..04bd7ec
--- /dev/null
+++ b/lib/devise/version.rb
@@ -0,0 +1,3 @@
+module Devise
+  VERSION = "3.4.0".freeze
+end
diff --git a/lib/generators/active_record/devise_generator.rb b/lib/generators/active_record/devise_generator.rb
new file mode 100644
index 0000000..7394bd8
--- /dev/null
+++ b/lib/generators/active_record/devise_generator.rb
@@ -0,0 +1,91 @@
+require 'rails/generators/active_record'
+require 'generators/devise/orm_helpers'
+
+module ActiveRecord
+  module Generators
+    class DeviseGenerator < ActiveRecord::Generators::Base
+      argument :attributes, type: :array, default: [], banner: "field:type field:type"
+
+      include Devise::Generators::OrmHelpers
+      source_root File.expand_path("../templates", __FILE__)
+
+      def copy_devise_migration
+        if (behavior == :invoke && model_exists?) || (behavior == :revoke && migration_exists?(table_name))
+          migration_template "migration_existing.rb", "db/migrate/add_devise_to_#{table_name}.rb"
+        else
+          migration_template "migration.rb", "db/migrate/devise_create_#{table_name}.rb"
+        end
+      end
+
+      def generate_model
+        invoke "active_record:model", [name], migration: false unless model_exists? && behavior == :invoke
+      end
+
+      def inject_devise_content
+        content = model_contents
+
+        class_path = if namespaced?
+          class_name.to_s.split("::")
+        else
+          [class_name]
+        end
+
+        indent_depth = class_path.size - 1
+        content = content.split("\n").map { |line| "  " * indent_depth + line } .join("\n") << "\n"
+
+        inject_into_class(model_path, class_path.last, content) if model_exists?
+      end
+
+      def migration_data
+<<RUBY
+      ## Database authenticatable
+      t.string :email,              null: false, default: ""
+      t.string :encrypted_password, null: false, default: ""
+
+      ## Recoverable
+      t.string   :reset_password_token
+      t.datetime :reset_password_sent_at
+
+      ## Rememberable
+      t.datetime :remember_created_at
+
+      ## Trackable
+      t.integer  :sign_in_count, default: 0, null: false
+      t.datetime :current_sign_in_at
+      t.datetime :last_sign_in_at
+      t.#{ip_column} :current_sign_in_ip
+      t.#{ip_column} :last_sign_in_ip
+
+      ## Confirmable
+      # t.string   :confirmation_token
+      # t.datetime :confirmed_at
+      # t.datetime :confirmation_sent_at
+      # t.string   :unconfirmed_email # Only if using reconfirmable
+
+      ## Lockable
+      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
+      # t.string   :unlock_token # Only if unlock strategy is :email or :both
+      # t.datetime :locked_at
+RUBY
+      end
+
+      def ip_column
+        # Padded with spaces so it aligns nicely with the rest of the columns.
+        "%-8s" % (inet? ? "inet" : "string")
+      end
+
+      def inet?
+        rails4? && postgresql?
+      end
+
+      def rails4?
+        Rails.version.start_with? '4'
+      end
+
+      def postgresql?
+        config = ActiveRecord::Base.configurations[Rails.env]
+        config && config['adapter'] == 'postgresql'
+      end
+    end
+  end
+end
diff --git a/lib/generators/active_record/templates/migration.rb b/lib/generators/active_record/templates/migration.rb
new file mode 100644
index 0000000..7145422
--- /dev/null
+++ b/lib/generators/active_record/templates/migration.rb
@@ -0,0 +1,18 @@
+class DeviseCreate<%= table_name.camelize %> < ActiveRecord::Migration
+  def change
+    create_table(:<%= table_name %>) do |t|
+<%= migration_data -%>
+
+<% attributes.each do |attribute| -%>
+      t.<%= attribute.type %> :<%= attribute.name %>
+<% end -%>
+
+      t.timestamps
+    end
+
+    add_index :<%= table_name %>, :email,                unique: true
+    add_index :<%= table_name %>, :reset_password_token, unique: true
+    # add_index :<%= table_name %>, :confirmation_token,   unique: true
+    # add_index :<%= table_name %>, :unlock_token,         unique: true
+  end
+end
diff --git a/lib/generators/active_record/templates/migration_existing.rb b/lib/generators/active_record/templates/migration_existing.rb
new file mode 100644
index 0000000..1b0ff5d
--- /dev/null
+++ b/lib/generators/active_record/templates/migration_existing.rb
@@ -0,0 +1,25 @@
+class AddDeviseTo<%= table_name.camelize %> < ActiveRecord::Migration
+  def self.up
+    change_table(:<%= table_name %>) do |t|
+<%= migration_data -%>
+
+<% attributes.each do |attribute| -%>
+      t.<%= attribute.type %> :<%= attribute.name %>
+<% end -%>
+
+      # Uncomment below if timestamps were not included in your original model.
+      # t.timestamps
+    end
+
+    add_index :<%= table_name %>, :email,                unique: true
+    add_index :<%= table_name %>, :reset_password_token, unique: true
+    # add_index :<%= table_name %>, :confirmation_token,   unique: true
+    # add_index :<%= table_name %>, :unlock_token,         unique: true
+  end
+
+  def self.down
+    # By default, we don't want to make any assumption about how to roll back a migration when your
+    # model already existed. Please edit below which fields you would like to remove in this migration.
+    raise ActiveRecord::IrreversibleMigration
+  end
+end
diff --git a/lib/generators/devise/controllers_generator.rb b/lib/generators/devise/controllers_generator.rb
new file mode 100644
index 0000000..921c21c
--- /dev/null
+++ b/lib/generators/devise/controllers_generator.rb
@@ -0,0 +1,44 @@
+require 'rails/generators/base'
+
+module Devise
+  module Generators
+    class ControllersGenerator < Rails::Generators::Base
+      CONTROLLERS = %w(confirmations passwords registrations sessions unlocks omniauth_callbacks).freeze
+
+      desc <<-DESC.strip_heredoc
+        Create inherited Devise controllers in your app/controllers folder.
+
+        User -c to specify which controller you want to overwrite.
+        If you do no specify a controller, all controllers will be created.
+        For example:
+
+          rails generate devise:controllers users -c=sessions
+
+        This will create a controller class at app/controllers/users/sessions_controller.rb like this:
+
+          class Users::ConfirmationsController < Devise::ConfirmationsController
+            content...
+          end
+      DESC
+
+      source_root File.expand_path("../../templates/controllers", __FILE__)
+      argument :scope, required: true,
+        desc: "The scope to create controllers in, e.g. users, admins"
+      class_option :controllers, aliases: "-c", type: :array,
+        desc: "Select specific controllers to generate (#{CONTROLLERS.join(', ')})"
+
+      def create_controllers
+        @scope_prefix = scope.blank? ? '' : (scope.camelize + '::')
+        controllers = options[:controllers] || CONTROLLERS
+        controllers.each do |name|
+          template "#{name}_controller.rb",
+                   "app/controllers/#{scope}/#{name}_controller.rb"
+        end
+      end
+
+      def show_readme
+        readme "README" if behavior == :invoke
+      end
+    end
+  end
+end
diff --git a/lib/generators/devise/devise_generator.rb b/lib/generators/devise/devise_generator.rb
new file mode 100644
index 0000000..8050395
--- /dev/null
+++ b/lib/generators/devise/devise_generator.rb
@@ -0,0 +1,26 @@
+require 'rails/generators/named_base'
+
+module Devise
+  module Generators
+    class DeviseGenerator < Rails::Generators::NamedBase
+      include Rails::Generators::ResourceHelpers
+
+      namespace "devise"
+      source_root File.expand_path("../templates", __FILE__)
+
+      desc "Generates a model with the given NAME (if one does not exist) with devise " <<
+           "configuration plus a migration file and devise routes."
+
+      hook_for :orm
+
+      class_option :routes, desc: "Generate routes", type: :boolean, default: true
+
+      def add_devise_routes
+        devise_route  = "devise_for :#{plural_name}"
+        devise_route << %Q(, class_name: "#{class_name}") if class_name.include?("::")
+        devise_route << %Q(, skip: :all) unless options.routes?
+        route devise_route
+      end
+    end
+  end
+end
diff --git a/lib/generators/devise/install_generator.rb b/lib/generators/devise/install_generator.rb
new file mode 100644
index 0000000..d3eabbe
--- /dev/null
+++ b/lib/generators/devise/install_generator.rb
@@ -0,0 +1,29 @@
+require 'rails/generators/base'
+require 'securerandom'
+
+module Devise
+  module Generators
+    class InstallGenerator < Rails::Generators::Base
+      source_root File.expand_path("../../templates", __FILE__)
+
+      desc "Creates a Devise initializer and copy locale files to your application."
+      class_option :orm
+
+      def copy_initializer
+        template "devise.rb", "config/initializers/devise.rb"
+      end
+
+      def copy_locale
+        copy_file "../../../config/locales/en.yml", "config/locales/devise.en.yml"
+      end
+
+      def show_readme
+        readme "README" if behavior == :invoke
+      end
+
+      def rails_4?
+        Rails::VERSION::MAJOR == 4
+      end
+    end
+  end
+end
diff --git a/lib/generators/devise/orm_helpers.rb b/lib/generators/devise/orm_helpers.rb
new file mode 100644
index 0000000..f8f59e4
--- /dev/null
+++ b/lib/generators/devise/orm_helpers.rb
@@ -0,0 +1,51 @@
+module Devise
+  module Generators
+    module OrmHelpers
+      def model_contents
+        buffer = <<-CONTENT
+  # Include default devise modules. Others available are:
+  # :confirmable, :lockable, :timeoutable and :omniauthable
+  devise :database_authenticatable, :registerable,
+         :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
+
+      def model_path
+        @model_path ||= File.join("app", "models", "#{file_path}.rb")
+      end
+    end
+  end
+end
diff --git a/lib/generators/devise/views_generator.rb b/lib/generators/devise/views_generator.rb
new file mode 100644
index 0000000..beac238
--- /dev/null
+++ b/lib/generators/devise/views_generator.rb
@@ -0,0 +1,135 @@
+require 'rails/generators/base'
+
+module Devise
+  module Generators
+    # Include this module in your generator to generate Devise views.
+    # `copy_views` is the main method and by default copies all views
+    # with forms.
+    module ViewPathTemplates #:nodoc:
+      extend ActiveSupport::Concern
+
+      included do
+        argument :scope, required: false, default: nil,
+                         desc: "The scope to copy views to"
+
+        # Le sigh, ensure Thor won't handle opts as args
+        # It should be fixed in future Rails releases
+        class_option :form_builder, aliases: "-b"
+        class_option :markerb
+        class_option :views, aliases: "-v", type: :array, desc: "Select specific view directories to generate (confirmations, passwords, registrations, sessions, unlocks, mailer)"
+
+        public_task :copy_views
+      end
+
+      # TODO: Add this to Rails itself
+      module ClassMethods
+        def hide!
+          Rails::Generators.hide_namespace self.namespace
+        end
+      end
+
+      def copy_views
+        if options[:views]
+          options[:views].each do |directory|
+            view_directory directory.to_sym
+          end
+        else
+          view_directory :confirmations
+          view_directory :passwords
+          view_directory :registrations
+          view_directory :sessions
+          view_directory :unlocks
+        end
+      end
+
+      protected
+
+      def view_directory(name, _target_path = nil)
+        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
+        @target_path ||= "app/views/#{scope || :devise}"
+      end
+    end
+
+    class SharedViewsGenerator < Rails::Generators::Base #:nodoc:
+      include ViewPathTemplates
+      source_root File.expand_path("../../../../app/views/devise", __FILE__)
+      desc "Copies shared Devise views to your application."
+      hide!
+
+      # Override copy_views to just copy mailer and shared.
+      def copy_views
+        view_directory :shared
+      end
+    end
+
+    class FormForGenerator < Rails::Generators::Base #:nodoc:
+      include ViewPathTemplates
+      source_root File.expand_path("../../../../app/views/devise", __FILE__)
+      desc "Copies default Devise views to your application."
+      hide!
+    end
+
+    class SimpleFormForGenerator < Rails::Generators::Base #:nodoc:
+      include ViewPathTemplates
+      source_root File.expand_path("../../templates/simple_form_for", __FILE__)
+      desc "Copies simple form enabled views to your application."
+      hide!
+    end
+
+    class ErbGenerator < Rails::Generators::Base #:nodoc:
+      include ViewPathTemplates
+      source_root File.expand_path("../../../../app/views/devise", __FILE__)
+      desc "Copies Devise mail erb views to your application."
+      hide!
+
+      def copy_views
+        if !options[:views] || options[:views].include?('mailer')
+          view_directory :mailer
+        end
+      end
+    end
+
+    class MarkerbGenerator < Rails::Generators::Base #:nodoc:
+      include ViewPathTemplates
+      source_root File.expand_path("../../templates", __FILE__)
+      desc "Copies Devise mail markerb views to your application."
+      hide!
+
+      def copy_views
+        if !options[:views] || options[:views].include?('mailer')
+          view_directory :markerb, target_path
+        end
+      end
+
+      def target_path
+        "app/views/#{scope || :devise}/mailer"
+      end
+    end
+
+    class ViewsGenerator < Rails::Generators::Base
+      desc "Copies Devise views to your application."
+
+      argument :scope, required: false, default: nil,
+                       desc: "The scope to copy views to"
+
+      invoke SharedViewsGenerator
+
+      hook_for :form_builder, aliases: "-b",
+                              desc: "Form builder to be used",
+                              default: defined?(SimpleForm) ? "simple_form_for" : "form_for"
+
+      hook_for :markerb,  desc: "Generate markerb instead of erb mail views",
+                          default: defined?(Markerb) ? :markerb : :erb,
+                          type: :boolean
+    end
+  end
+end
diff --git a/lib/generators/mongoid/devise_generator.rb b/lib/generators/mongoid/devise_generator.rb
new file mode 100644
index 0000000..4ff57f0
--- /dev/null
+++ b/lib/generators/mongoid/devise_generator.rb
@@ -0,0 +1,55 @@
+require 'rails/generators/named_base'
+require 'generators/devise/orm_helpers'
+
+module Mongoid
+  module Generators
+    class DeviseGenerator < Rails::Generators::NamedBase
+      include Devise::Generators::OrmHelpers
+
+      def generate_model
+        invoke "mongoid:model", [name] unless model_exists? && behavior == :invoke
+      end
+
+      def inject_field_types
+        inject_into_file model_path, migration_data, after: "include Mongoid::Document\n" if model_exists?
+      end
+
+      def inject_devise_content
+        inject_into_file model_path, model_contents, after: "include Mongoid::Document\n" if model_exists?
+      end
+
+      def migration_data
+<<RUBY
+  ## 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
+
+  ## Rememberable
+  field :remember_created_at, type: Time
+
+  ## Trackable
+  field :sign_in_count,      type: Integer, default: 0
+  field :current_sign_in_at, type: Time
+  field :last_sign_in_at,    type: Time
+  field :current_sign_in_ip, type: String
+  field :last_sign_in_ip,    type: String
+
+  ## Confirmable
+  # field :confirmation_token,   type: String
+  # field :confirmed_at,         type: Time
+  # field :confirmation_sent_at, type: Time
+  # field :unconfirmed_email,    type: String # Only if using reconfirmable
+
+  ## Lockable
+  # field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
+  # field :unlock_token,    type: String # Only if unlock strategy is :email or :both
+  # field :locked_at,       type: Time
+RUBY
+      end
+    end
+  end
+end
diff --git a/lib/generators/templates/README b/lib/generators/templates/README
new file mode 100644
index 0000000..001e6e5
--- /dev/null
+++ b/lib/generators/templates/README
@@ -0,0 +1,35 @@
+===============================================================================
+
+Some setup you must do manually if you haven't yet:
+
+  1. Ensure you have defined default url options in your environments files. Here
+     is an example of default_url_options appropriate for a development environment
+     in config/environments/development.rb:
+
+       config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
+
+     In production, :host should be set to the actual host of your application.
+
+  2. Ensure you have defined root_url to *something* in your config/routes.rb.
+     For example:
+
+       root to: "home#index"
+
+  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
+     For example:
+
+       <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:
+
+       config.assets.initialize_on_precompile = false
+
+     On config/application.rb forcing your application to not access the DB
+     or load models when precompiling your assets.
+
+  5. You can copy Devise views (for customization) to your app by running:
+
+       rails g devise:views
+
+===============================================================================
diff --git a/lib/generators/templates/controllers/README b/lib/generators/templates/controllers/README
new file mode 100644
index 0000000..d8fa757
--- /dev/null
+++ b/lib/generators/templates/controllers/README
@@ -0,0 +1,14 @@
+===============================================================================
+
+Some setup you must do manually if you haven't yet:
+
+  Ensure you have overridden routes for generated controllers in your route.rb.
+  For example:
+
+    Rails.application.routes.draw do
+      devise_for :users, controllers: {
+        sessions: 'sessions'
+      }
+    end
+
+===============================================================================
diff --git a/lib/generators/templates/controllers/confirmations_controller.rb b/lib/generators/templates/controllers/confirmations_controller.rb
new file mode 100644
index 0000000..480ee9a
--- /dev/null
+++ b/lib/generators/templates/controllers/confirmations_controller.rb
@@ -0,0 +1,28 @@
+class <%= @scope_prefix %>ConfirmationsController < Devise::ConfirmationsController
+  # GET /resource/confirmation/new
+  # def new
+  #   super
+  # end
+
+  # POST /resource/confirmation
+  # def create
+  #   super
+  # end
+
+  # GET /resource/confirmation?confirmation_token=abcdef
+  # def show
+  #   super
+  # end
+
+  # protected
+
+  # The path used after resending confirmation instructions.
+  # def after_resending_confirmation_instructions_path_for(resource_name)
+  #   super(resource_name)
+  # end
+
+  # The path used after confirmation.
+  # def after_confirmation_path_for(resource_name, resource)
+  #   super(resource_name, resource)
+  # end
+end
diff --git a/lib/generators/templates/controllers/omniauth_callbacks_controller.rb b/lib/generators/templates/controllers/omniauth_callbacks_controller.rb
new file mode 100644
index 0000000..6516213
--- /dev/null
+++ b/lib/generators/templates/controllers/omniauth_callbacks_controller.rb
@@ -0,0 +1,28 @@
+class <%= @scope_prefix %>OmniauthCallbacksController < Devise::OmniauthCallbacksController
+  # You should configure your model like this:
+  # devise :omniauthable, omniauth_providers: [:twitter]
+
+  # You should also create an action method in this controller like this:
+  # def twitter
+  # end
+
+  # More info at:
+  # https://github.com/plataformatec/devise#omniauth
+
+  # GET|POST /resource/auth/twitter
+  # def passthru
+  #   super
+  # end
+
+  # GET|POST /users/auth/twitter/callback
+  # def failure
+  #   super
+  # end
+
+  # protected
+
+  # The path used when omniauth fails
+  # def after_omniauth_failure_path_for(scope)
+  #   super(scope)
+  # end
+end
diff --git a/lib/generators/templates/controllers/passwords_controller.rb b/lib/generators/templates/controllers/passwords_controller.rb
new file mode 100644
index 0000000..3409d43
--- /dev/null
+++ b/lib/generators/templates/controllers/passwords_controller.rb
@@ -0,0 +1,32 @@
+class <%= @scope_prefix %>PasswordsController < Devise::PasswordsController
+  # GET /resource/password/new
+  # def new
+  #   super
+  # end
+
+  # POST /resource/password
+  # def create
+  #   super
+  # end
+
+  # GET /resource/password/edit?reset_password_token=abcdef
+  # def edit
+  #   super
+  # end
+
+  # PUT /resource/password
+  # def update
+  #   super
+  # end
+
+  # protected
+
+  # def after_resetting_password_path_for(resource)
+  #   super(resource)
+  # end
+
+  # The path used after sending reset password instructions
+  # def after_sending_reset_password_instructions_path_for(resource_name)
+  #   super(resource_name)
+  # end
+end
diff --git a/lib/generators/templates/controllers/registrations_controller.rb b/lib/generators/templates/controllers/registrations_controller.rb
new file mode 100644
index 0000000..3566e45
--- /dev/null
+++ b/lib/generators/templates/controllers/registrations_controller.rb
@@ -0,0 +1,60 @@
+class <%= @scope_prefix %>RegistrationsController < Devise::RegistrationsController
+# before_filter :configure_sign_up_params, only: [:create]
+# before_filter :configure_account_update_params, only: [:update]
+
+  # GET /resource/sign_up
+  # def new
+  #   super
+  # end
+
+  # POST /resource
+  # def create
+  #   super
+  # end
+
+  # GET /resource/edit
+  # def edit
+  #   super
+  # end
+
+  # PUT /resource
+  # def update
+  #   super
+  # end
+
+  # DELETE /resource
+  # def destroy
+  #   super
+  # end
+
+  # GET /resource/cancel
+  # Forces the session data which is usually expired after sign
+  # in to be expired now. This is useful if the user wants to
+  # cancel oauth signing in/up in the middle of the process,
+  # removing all OAuth session data.
+  # def cancel
+  #   super
+  # end
+
+  # protected
+
+  # You can put the params you want to permit in the empty array.
+  # def configure_sign_up_params
+  #   devise_parameter_sanitizer.for(:sign_up) << :attribute
+  # end
+
+  # You can put the params you want to permit in the empty array.
+  # def configure_account_update_params
+  #   devise_parameter_sanitizer.for(:account_update) << :attribute
+  # end
+
+  # The path used after sign up.
+  # def after_sign_up_path_for(resource)
+  #   super(resource)
+  # end
+
+  # The path used after sign up for inactive accounts.
+  # def after_inactive_sign_up_path_for(resource)
+  #   super(resource)
+  # end
+end
diff --git a/lib/generators/templates/controllers/sessions_controller.rb b/lib/generators/templates/controllers/sessions_controller.rb
new file mode 100644
index 0000000..7a243f4
--- /dev/null
+++ b/lib/generators/templates/controllers/sessions_controller.rb
@@ -0,0 +1,25 @@
+class <%= @scope_prefix %>SessionsController < Devise::SessionsController
+# before_filter :configure_sign_in_params, only: [:create]
+
+  # GET /resource/sign_in
+  # def new
+  #   super
+  # end
+
+  # POST /resource/sign_in
+  # def create
+  #   super
+  # end
+
+  # DELETE /resource/sign_out
+  # def destroy
+  #   super
+  # end
+
+  # protected
+
+  # You can put the params you want to permit in the empty array.
+  # def configure_sign_in_params
+  #   devise_parameter_sanitizer.for(:sign_in) << :attribute
+  # end
+end
diff --git a/lib/generators/templates/controllers/unlocks_controller.rb b/lib/generators/templates/controllers/unlocks_controller.rb
new file mode 100644
index 0000000..0e2cced
--- /dev/null
+++ b/lib/generators/templates/controllers/unlocks_controller.rb
@@ -0,0 +1,28 @@
+class <%= @scope_prefix %>UnlocksController < Devise::UnlocksController
+  # GET /resource/unlock/new
+  # def new
+  #   super
+  # end
+
+  # POST /resource/unlock
+  # def create
+  #   super
+  # end
+
+  # GET /resource/unlock?unlock_token=abcdef
+  # def show
+  #   super
+  # end
+
+  # protected
+
+  # The path used after sending unlock password instructions
+  # def after_sending_unlock_instructions_path_for(resource)
+  #   super(resource)
+  # end
+
+  # The path used after unlocking the resource
+  # def after_unlock_path_for(resource)
+  #   super(resource)
+  # end
+end
diff --git a/lib/generators/templates/devise.rb b/lib/generators/templates/devise.rb
new file mode 100644
index 0000000..90e138c
--- /dev/null
+++ b/lib/generators/templates/devise.rb
@@ -0,0 +1,263 @@
+# Use this hook to configure devise mailer, warden hooks and so forth.
+# Many of these configuration options can be set straight in your model.
+Devise.setup do |config|
+  # The secret key used by Devise. Devise uses this key to generate
+  # random tokens. Changing this key will render invalid all existing
+  # confirmation, reset password and unlock tokens in the database.
+<% if rails_4? -%>
+  # config.secret_key = '<%= SecureRandom.hex(64) %>'
+<% else -%>
+  config.secret_key = '<%= SecureRandom.hex(64) %>'
+<% end -%>
+
+  # ==> Mailer Configuration
+  # Configure the e-mail address which will be shown in Devise::Mailer,
+  # note that it will be overwritten if you use your own mailer class
+  # with default "from" parameter.
+  config.mailer_sender = 'please-change-me-at-config-initializers-devise at example.com'
+
+  # Configure the class responsible to send e-mails.
+  # config.mailer = 'Devise::Mailer'
+
+  # ==> ORM configuration
+  # Load and configure the ORM. Supports :active_record (default) and
+  # :mongoid (bson_ext recommended) by default. Other ORMs may be
+  # available as additional gems.
+  require 'devise/orm/<%= options[:orm] %>'
+
+  # ==> Configuration for any authentication mechanism
+  # Configure which keys are used when authenticating a user. The default is
+  # just :email. You can configure it to use [:username, :subdomain], so for
+  # authenticating a user, both parameters are required. Remember that those
+  # parameters are used only when authenticating and not when retrieving from
+  # session. If you need permissions, you should implement that in a before filter.
+  # You can also supply a hash where the value is a boolean determining whether
+  # or not authentication should be aborted when the value is not present.
+  # config.authentication_keys = [ :email ]
+
+  # Configure parameters from the request object used for authentication. Each entry
+  # given should be a request method and it will automatically be passed to the
+  # find_for_authentication method and considered in your model lookup. For instance,
+  # if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
+  # The same considerations mentioned for authentication_keys also apply to request_keys.
+  # config.request_keys = []
+
+  # Configure which authentication keys should be case-insensitive.
+  # These keys will be downcased upon creating or modifying a user and when used
+  # to authenticate or find a user. Default is :email.
+  config.case_insensitive_keys = [ :email ]
+
+  # Configure which authentication keys should have whitespace stripped.
+  # These keys will have whitespace before and after removed upon creating or
+  # modifying a user and when used to authenticate or find a user. Default is :email.
+  config.strip_whitespace_keys = [ :email ]
+
+  # Tell if authentication through request.params is enabled. True by default.
+  # It can be set to an array that will enable params authentication only for the
+  # given strategies, for example, `config.params_authenticatable = [:database]` will
+  # enable it only for database (email + password) authentication.
+  # config.params_authenticatable = true
+
+  # 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 = [:database]` will
+  # enable it only for database authentication. The supported strategies are:
+  # :database      = Support basic authentication with authentication key + password
+  # config.http_authenticatable = false
+
+  # If 401 status code should be returned for AJAX requests. True by default.
+  # config.http_authenticatable_on_xhr = true
+
+  # The realm used in Http Basic Authentication. 'Application' by default.
+  # config.http_authentication_realm = 'Application'
+
+  # It will change confirmation, password recovery and other workflows
+  # to behave the same regardless if the e-mail provided was right or wrong.
+  # Does not affect registerable.
+  # config.paranoid = true
+
+  # By default Devise will store the user in session. You can skip storage for
+  # particular strategies by setting this option.
+  # Notice that if you are skipping storage for all authentication paths, you
+  # may want to disable generating routes to Devise's sessions controller by
+  # passing skip: :sessions to `devise_for` in your config/routes.rb
+  config.skip_session_storage = [:http_auth]
+
+  # By default, Devise cleans up the CSRF token on authentication to
+  # avoid CSRF token fixation attacks. This means that, when using AJAX
+  # requests for sign in and sign up, you need to get a new CSRF token
+  # from the server. You can disable this option at your own risk.
+  # config.clean_up_csrf_token_on_authentication = true
+
+  # ==> Configuration for :database_authenticatable
+  # For bcrypt, this is the cost for hashing the password and defaults to 10. If
+  # using other encryptors, it sets how many times you want the password re-encrypted.
+  #
+  # Limiting the stretches to just one in testing will increase the performance of
+  # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
+  # a value less than 10 in other environments. Note that, for bcrypt (the default
+  # encryptor), the cost increases exponentially with the number of stretches (e.g.
+  # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
+  config.stretches = Rails.env.test? ? 1 : 10
+
+  # Setup a pepper to generate the encrypted password.
+  # config.pepper = '<%= SecureRandom.hex(64) %>'
+
+  # ==> Configuration for :confirmable
+  # A period that the user is allowed to access the website even without
+  # confirming their account. For instance, if set to 2.days, the user will be
+  # able to access the website for two days without confirming their account,
+  # access will be blocked just in the third day. Default is 0.days, meaning
+  # the user cannot access the website without confirming their account.
+  # config.allow_unconfirmed_access_for = 2.days
+
+  # A period that the user is allowed to confirm their account before their
+  # token becomes invalid. For example, if set to 3.days, the user can confirm
+  # their account within 3 days after the mail was sent, but on the fourth day
+  # their account can't be confirmed with the token any more.
+  # Default is nil, meaning there is no restriction on how long a user can take
+  # before confirming their account.
+  # config.confirm_within = 3.days
+
+  # If true, requires any email changes to be confirmed (exactly the same way as
+  # initial account confirmation) to be applied. Requires additional unconfirmed_email
+  # db field (see migrations). Until confirmed, new email is stored in
+  # unconfirmed_email column, and copied to email column on successful confirmation.
+  config.reconfirmable = true
+
+  # Defines which key will be used when confirming an account
+  # config.confirmation_keys = [ :email ]
+
+  # ==> Configuration for :rememberable
+  # The time the user will be remembered without asking for credentials again.
+  # config.remember_for = 2.weeks
+
+  # Invalidates all the remember me tokens when the user signs out.
+  config.expire_all_remember_me_on_sign_out = true
+
+  # If true, extends the user's remember period when remembered via cookie.
+  # config.extend_remember_period = false
+
+  # Options to be passed to the created cookie. For instance, you can set
+  # secure: true in order to force SSL only cookies.
+  # config.rememberable_options = {}
+
+  # ==> Configuration for :validatable
+  # Range for password length.
+  config.password_length = 8..128
+
+  # Email regex used to validate email formats. It simply asserts that
+  # 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/
+
+  # ==> Configuration for :timeoutable
+  # The time you want to timeout the user session without activity. After this
+  # time the user will be asked for credentials again. Default is 30 minutes.
+  # config.timeout_in = 30.minutes
+
+  # If true, expires auth token on session timeout.
+  # config.expire_auth_token_on_timeout = false
+
+  # ==> Configuration for :lockable
+  # Defines which strategy will be used to lock an account.
+  # :failed_attempts = Locks an account after a number of failed attempts to sign in.
+  # :none            = No lock strategy. You should handle locking by yourself.
+  # config.lock_strategy = :failed_attempts
+
+  # Defines which key will be used when locking and unlocking an account
+  # config.unlock_keys = [ :email ]
+
+  # Defines which strategy will be used to unlock an account.
+  # :email = Sends an unlock link to the user email
+  # :time  = Re-enables login after a certain amount of time (see :unlock_in below)
+  # :both  = Enables both strategies
+  # :none  = No unlock strategy. You should handle unlocking by yourself.
+  # config.unlock_strategy = :both
+
+  # Number of authentication tries before locking an account if lock_strategy
+  # is failed attempts.
+  # config.maximum_attempts = 20
+
+  # Time interval to unlock the account if :time is enabled as unlock_strategy.
+  # config.unlock_in = 1.hour
+
+  # Warn on the last attempt before the account is locked.
+  # config.last_attempt_warning = true
+
+  # ==> Configuration for :recoverable
+  #
+  # Defines which key will be used when recovering the password for an account
+  # config.reset_password_keys = [ :email ]
+
+  # Time interval you can reset your password with a reset password key.
+  # Don't put a too small interval or your users won't have the time to
+  # change their passwords.
+  config.reset_password_within = 6.hours
+
+  # ==> Configuration for :encryptable
+  # Allow you to use another encryption algorithm besides bcrypt (default). You can use
+  # :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).
+  #
+  # Require the `devise-encryptable` gem when using anything other than bcrypt
+  # config.encryptor = :sha512
+
+  # ==> Scopes configuration
+  # Turn scoped views on. Before rendering "sessions/new", it will first check for
+  # "users/sessions/new". It's turned off by default because it's slower if you
+  # are using only default views.
+  # config.scoped_views = false
+
+  # Configure the default scope given to Warden. By default it's the first
+  # devise role declared in your routes (usually :user).
+  # config.default_scope = :user
+
+  # Set this configuration to false if you want /users/sign_out to sign out
+  # only the current scope. By default, Devise signs out all scopes.
+  # config.sign_out_all_scopes = true
+
+  # ==> Navigation configuration
+  # Lists the formats that should be treated as navigational. Formats like
+  # :html, should redirect to the sign in page when the user does not have
+  # access, but formats like :xml or :json, should return 401.
+  #
+  # If you have any extra navigational formats, like :iphone or :mobile, you
+  # should add them to the navigational formats lists.
+  #
+  # The "*/*" below is required to match Internet Explorer requests.
+  # config.navigational_formats = ['*/*', :html]
+
+  # The default HTTP method used to sign out a resource. Default is :delete.
+  config.sign_out_via = :delete
+
+  # ==> OmniAuth
+  # Add a new OmniAuth provider. Check the wiki for more information on setting
+  # up on your models and hooks.
+  # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
+
+  # ==> Warden configuration
+  # If you want to use other strategies, that are not supported by Devise, or
+  # change the failure app, you can configure them inside the config.warden block.
+  #
+  # config.warden do |manager|
+  #   manager.intercept_401 = false
+  #   manager.default_strategies(scope: :user).unshift :some_external_strategy
+  # end
+
+  # ==> Mountable engine configurations
+  # When using Devise inside an engine, let's call it `MyEngine`, and this engine
+  # is mountable, there are some extra configurations to be taken into account.
+  # The following options are available, assuming the engine is mounted as:
+  #
+  #     mount MyEngine, at: '/my_engine'
+  #
+  # The router that invoked `devise_for`, in the example above, would be:
+  # config.router_name = :my_engine
+  #
+  # When using omniauth, Devise cannot automatically set Omniauth path,
+  # so you need to do it manually. For the users scope, it would be:
+  # config.omniauth_path_prefix = '/my_engine/users/auth'
+end
diff --git a/lib/generators/templates/markerb/confirmation_instructions.markerb b/lib/generators/templates/markerb/confirmation_instructions.markerb
new file mode 100644
index 0000000..fe73f00
--- /dev/null
+++ b/lib/generators/templates/markerb/confirmation_instructions.markerb
@@ -0,0 +1,5 @@
+Welcome <%= @email %>!
+
+You can confirm your account through the link below:
+
+<%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %>
diff --git a/lib/generators/templates/markerb/reset_password_instructions.markerb b/lib/generators/templates/markerb/reset_password_instructions.markerb
new file mode 100644
index 0000000..b1ca47a
--- /dev/null
+++ b/lib/generators/templates/markerb/reset_password_instructions.markerb
@@ -0,0 +1,8 @@
+Hello <%= @resource.email %>!
+
+Someone has requested a link to change your password, and you can do this through the link below.
+
+<%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %>
+
+If you didn't request this, please ignore this email.
+Your password won't change until you access the link above and create a new one.
diff --git a/lib/generators/templates/markerb/unlock_instructions.markerb b/lib/generators/templates/markerb/unlock_instructions.markerb
new file mode 100644
index 0000000..e3ed33d
--- /dev/null
+++ b/lib/generators/templates/markerb/unlock_instructions.markerb
@@ -0,0 +1,7 @@
+Hello <%= @resource.email %>!
+
+Your account has been locked due to an excessive number of unsuccessful sign in attempts.
+
+Click the link below to unlock your account:
+
+<%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %>
diff --git a/lib/generators/templates/simple_form_for/confirmations/new.html.erb b/lib/generators/templates/simple_form_for/confirmations/new.html.erb
new file mode 100644
index 0000000..949b172
--- /dev/null
+++ b/lib/generators/templates/simple_form_for/confirmations/new.html.erb
@@ -0,0 +1,16 @@
+<h2>Resend confirmation instructions</h2>
+
+<%= simple_form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %>
+  <%= f.error_notification %>
+  <%= f.full_error :confirmation_token %>
+
+  <div class="form-inputs">
+    <%= f.input :email, required: true, autofocus: true %>
+  </div>
+
+  <div class="form-actions">
+    <%= f.button :submit, "Resend confirmation instructions" %>
+  </div>
+<% end %>
+
+<%= render "devise/shared/links" %>
diff --git a/lib/generators/templates/simple_form_for/passwords/edit.html.erb b/lib/generators/templates/simple_form_for/passwords/edit.html.erb
new file mode 100644
index 0000000..8f995ed
--- /dev/null
+++ b/lib/generators/templates/simple_form_for/passwords/edit.html.erb
@@ -0,0 +1,19 @@
+<h2>Change your password</h2>
+
+<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %>
+  <%= f.error_notification %>
+
+  <%= f.input :reset_password_token, as: :hidden %>
+  <%= f.full_error :reset_password_token %>
+
+  <div class="form-inputs">
+    <%= f.input :password, label: "New password", required: true, autofocus: true %>
+    <%= f.input :password_confirmation, label: "Confirm your new password", required: true %>
+  </div>
+
+  <div class="form-actions">
+    <%= f.button :submit, "Change my password" %>
+  </div>
+<% end %>
+
+<%= render "devise/shared/links" %>
diff --git a/lib/generators/templates/simple_form_for/passwords/new.html.erb b/lib/generators/templates/simple_form_for/passwords/new.html.erb
new file mode 100644
index 0000000..d1503e7
--- /dev/null
+++ b/lib/generators/templates/simple_form_for/passwords/new.html.erb
@@ -0,0 +1,15 @@
+<h2>Forgot your password?</h2>
+
+<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %>
+  <%= f.error_notification %>
+
+  <div class="form-inputs">
+    <%= f.input :email, required: true, autofocus: true %>
+  </div>
+
+  <div class="form-actions">
+    <%= f.button :submit, "Send me reset password instructions" %>
+  </div>
+<% end %>
+
+<%= render "devise/shared/links" %>
diff --git a/lib/generators/templates/simple_form_for/registrations/edit.html.erb b/lib/generators/templates/simple_form_for/registrations/edit.html.erb
new file mode 100644
index 0000000..5db350b
--- /dev/null
+++ b/lib/generators/templates/simple_form_for/registrations/edit.html.erb
@@ -0,0 +1,27 @@
+<h2>Edit <%= resource_name.to_s.humanize %></h2>
+
+<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
+  <%= f.error_notification %>
+
+  <div class="form-inputs">
+    <%= f.input :email, required: true, autofocus: true %>
+
+    <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
+      <p>Currently waiting confirmation for: <%= resource.unconfirmed_email %></p>
+    <% end %>
+
+    <%= f.input :password, autocomplete: "off", hint: "leave it blank if you don't want to change it", required: false %>
+    <%= f.input :password_confirmation, required: false %>
+    <%= f.input :current_password, hint: "we need your current password to confirm your changes", required: true %>
+  </div>
+
+  <div class="form-actions">
+    <%= f.button :submit, "Update" %>
+  </div>
+<% end %>
+
+<h3>Cancel my account</h3>
+
+<p>Unhappy? <%= link_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>
+
+<%= link_to "Back", :back %>
diff --git a/lib/generators/templates/simple_form_for/registrations/new.html.erb b/lib/generators/templates/simple_form_for/registrations/new.html.erb
new file mode 100644
index 0000000..4ea8fb9
--- /dev/null
+++ b/lib/generators/templates/simple_form_for/registrations/new.html.erb
@@ -0,0 +1,17 @@
+<h2>Sign up</h2>
+
+<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
+  <%= f.error_notification %>
+
+  <div class="form-inputs">
+    <%= f.input :email, required: true, autofocus: true %>
+    <%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @validatable) %>
+    <%= f.input :password_confirmation, required: true %>
+  </div>
+
+  <div class="form-actions">
+    <%= f.button :submit, "Sign up" %>
+  </div>
+<% end %>
+
+<%= render "devise/shared/links" %>
diff --git a/lib/generators/templates/simple_form_for/sessions/new.html.erb b/lib/generators/templates/simple_form_for/sessions/new.html.erb
new file mode 100644
index 0000000..31f8a4d
--- /dev/null
+++ b/lib/generators/templates/simple_form_for/sessions/new.html.erb
@@ -0,0 +1,15 @@
+<h2>Log in</h2>
+
+<%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
+  <div class="form-inputs">
+    <%= f.input :email, required: false, autofocus: true %>
+    <%= f.input :password, required: false %>
+    <%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %>
+  </div>
+
+  <div class="form-actions">
+    <%= f.button :submit, "Log in" %>
+  </div>
+<% end %>
+
+<%= render "devise/shared/links" %>
diff --git a/lib/generators/templates/simple_form_for/unlocks/new.html.erb b/lib/generators/templates/simple_form_for/unlocks/new.html.erb
new file mode 100644
index 0000000..788f62e
--- /dev/null
+++ b/lib/generators/templates/simple_form_for/unlocks/new.html.erb
@@ -0,0 +1,16 @@
+<h2>Resend unlock instructions</h2>
+
+<%= simple_form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %>
+  <%= f.error_notification %>
+  <%= f.full_error :unlock_token %>
+
+  <div class="form-inputs">
+    <%= f.input :email, required: true, autofocus: true %>
+  </div>
+
+  <div class="form-actions">
+    <%= f.button :submit, "Resend unlock instructions" %>
+  </div>
+<% end %>
+
+<%= render "devise/shared/links" %>
diff --git a/metadata.yml b/metadata.yml
new file mode 100644
index 0000000..09fffb1
--- /dev/null
+++ b/metadata.yml
@@ -0,0 +1,501 @@
+--- !ruby/object:Gem::Specification
+name: devise
+version: !ruby/object:Gem::Version
+  version: 3.4.0
+platform: ruby
+authors:
+- José Valim
+- Carlos Antônio
+autorequire: 
+bindir: bin
+cert_chain: []
+date: 2014-10-03 00:00:00.000000000 Z
+dependencies:
+- !ruby/object:Gem::Dependency
+  name: warden
+  requirement: !ruby/object:Gem::Requirement
+    requirements:
+    - - "~>"
+      - !ruby/object:Gem::Version
+        version: 1.2.3
+  type: :runtime
+  prerelease: false
+  version_requirements: !ruby/object:Gem::Requirement
+    requirements:
+    - - "~>"
+      - !ruby/object:Gem::Version
+        version: 1.2.3
+- !ruby/object:Gem::Dependency
+  name: orm_adapter
+  requirement: !ruby/object:Gem::Requirement
+    requirements:
+    - - "~>"
+      - !ruby/object:Gem::Version
+        version: '0.1'
+  type: :runtime
+  prerelease: false
+  version_requirements: !ruby/object:Gem::Requirement
+    requirements:
+    - - "~>"
+      - !ruby/object:Gem::Version
+        version: '0.1'
+- !ruby/object:Gem::Dependency
+  name: bcrypt
+  requirement: !ruby/object:Gem::Requirement
+    requirements:
+    - - "~>"
+      - !ruby/object:Gem::Version
+        version: '3.0'
+  type: :runtime
+  prerelease: false
+  version_requirements: !ruby/object:Gem::Requirement
+    requirements:
+    - - "~>"
+      - !ruby/object:Gem::Version
+        version: '3.0'
+- !ruby/object:Gem::Dependency
+  name: thread_safe
+  requirement: !ruby/object:Gem::Requirement
+    requirements:
+    - - "~>"
+      - !ruby/object:Gem::Version
+        version: '0.1'
+  type: :runtime
+  prerelease: false
+  version_requirements: !ruby/object:Gem::Requirement
+    requirements:
+    - - "~>"
+      - !ruby/object:Gem::Version
+        version: '0.1'
+- !ruby/object:Gem::Dependency
+  name: railties
+  requirement: !ruby/object:Gem::Requirement
+    requirements:
+    - - ">="
+      - !ruby/object:Gem::Version
+        version: 3.2.6
+    - - "<"
+      - !ruby/object:Gem::Version
+        version: '5'
+  type: :runtime
+  prerelease: false
+  version_requirements: !ruby/object:Gem::Requirement
+    requirements:
+    - - ">="
+      - !ruby/object:Gem::Version
+        version: 3.2.6
+    - - "<"
+      - !ruby/object:Gem::Version
+        version: '5'
+- !ruby/object:Gem::Dependency
+  name: responders
+  requirement: !ruby/object:Gem::Requirement
+    requirements:
+    - - ">="
+      - !ruby/object:Gem::Version
+        version: '0'
+  type: :runtime
+  prerelease: false
+  version_requirements: !ruby/object:Gem::Requirement
+    requirements:
+    - - ">="
+      - !ruby/object:Gem::Version
+        version: '0'
+description: Flexible authentication solution for Rails with Warden
+email: contact at plataformatec.com.br
+executables: []
+extensions: []
+extra_rdoc_files: []
+files:
+- ".gitignore"
+- ".travis.yml"
+- ".yardopts"
+- CHANGELOG.md
+- CONTRIBUTING.md
+- Gemfile
+- Gemfile.lock
+- MIT-LICENSE
+- README.md
+- Rakefile
+- app/controllers/devise/confirmations_controller.rb
+- app/controllers/devise/omniauth_callbacks_controller.rb
+- app/controllers/devise/passwords_controller.rb
+- app/controllers/devise/registrations_controller.rb
+- app/controllers/devise/sessions_controller.rb
+- app/controllers/devise/unlocks_controller.rb
+- app/controllers/devise_controller.rb
+- app/helpers/devise_helper.rb
+- app/mailers/devise/mailer.rb
+- app/views/devise/confirmations/new.html.erb
+- app/views/devise/mailer/confirmation_instructions.html.erb
+- app/views/devise/mailer/reset_password_instructions.html.erb
+- app/views/devise/mailer/unlock_instructions.html.erb
+- app/views/devise/passwords/edit.html.erb
+- app/views/devise/passwords/new.html.erb
+- app/views/devise/registrations/edit.html.erb
+- app/views/devise/registrations/new.html.erb
+- app/views/devise/sessions/new.html.erb
+- app/views/devise/shared/_links.html.erb
+- app/views/devise/unlocks/new.html.erb
+- config/locales/en.yml
+- devise.gemspec
+- devise.png
+- gemfiles/Gemfile.rails-3.2-stable
+- gemfiles/Gemfile.rails-3.2-stable.lock
+- gemfiles/Gemfile.rails-4.0-stable
+- gemfiles/Gemfile.rails-4.0-stable.lock
+- gemfiles/Gemfile.rails-4.1-stable
+- gemfiles/Gemfile.rails-4.1-stable.lock
+- lib/devise.rb
+- lib/devise/controllers/helpers.rb
+- lib/devise/controllers/rememberable.rb
+- lib/devise/controllers/scoped_views.rb
+- lib/devise/controllers/sign_in_out.rb
+- lib/devise/controllers/store_location.rb
+- lib/devise/controllers/url_helpers.rb
+- lib/devise/delegator.rb
+- lib/devise/failure_app.rb
+- lib/devise/hooks/activatable.rb
+- lib/devise/hooks/csrf_cleaner.rb
+- lib/devise/hooks/forgetable.rb
+- lib/devise/hooks/lockable.rb
+- lib/devise/hooks/proxy.rb
+- lib/devise/hooks/rememberable.rb
+- lib/devise/hooks/timeoutable.rb
+- lib/devise/hooks/trackable.rb
+- lib/devise/mailers/helpers.rb
+- lib/devise/mapping.rb
+- lib/devise/models.rb
+- lib/devise/models/authenticatable.rb
+- lib/devise/models/confirmable.rb
+- lib/devise/models/database_authenticatable.rb
+- lib/devise/models/lockable.rb
+- lib/devise/models/omniauthable.rb
+- lib/devise/models/recoverable.rb
+- lib/devise/models/registerable.rb
+- lib/devise/models/rememberable.rb
+- lib/devise/models/timeoutable.rb
+- lib/devise/models/trackable.rb
+- lib/devise/models/validatable.rb
+- lib/devise/modules.rb
+- lib/devise/omniauth.rb
+- lib/devise/omniauth/config.rb
+- lib/devise/omniauth/url_helpers.rb
+- lib/devise/orm/active_record.rb
+- lib/devise/orm/mongoid.rb
+- lib/devise/parameter_filter.rb
+- lib/devise/parameter_sanitizer.rb
+- lib/devise/rails.rb
+- lib/devise/rails/routes.rb
+- lib/devise/rails/warden_compat.rb
+- lib/devise/strategies/authenticatable.rb
+- lib/devise/strategies/base.rb
+- lib/devise/strategies/database_authenticatable.rb
+- lib/devise/strategies/rememberable.rb
+- lib/devise/test_helpers.rb
+- lib/devise/time_inflector.rb
+- lib/devise/token_generator.rb
+- lib/devise/version.rb
+- lib/generators/active_record/devise_generator.rb
+- lib/generators/active_record/templates/migration.rb
+- lib/generators/active_record/templates/migration_existing.rb
+- lib/generators/devise/controllers_generator.rb
+- lib/generators/devise/devise_generator.rb
+- lib/generators/devise/install_generator.rb
+- lib/generators/devise/orm_helpers.rb
+- lib/generators/devise/views_generator.rb
+- lib/generators/mongoid/devise_generator.rb
+- lib/generators/templates/README
+- lib/generators/templates/controllers/README
+- lib/generators/templates/controllers/confirmations_controller.rb
+- lib/generators/templates/controllers/omniauth_callbacks_controller.rb
+- lib/generators/templates/controllers/passwords_controller.rb
+- lib/generators/templates/controllers/registrations_controller.rb
+- lib/generators/templates/controllers/sessions_controller.rb
+- lib/generators/templates/controllers/unlocks_controller.rb
+- lib/generators/templates/devise.rb
+- lib/generators/templates/markerb/confirmation_instructions.markerb
+- lib/generators/templates/markerb/reset_password_instructions.markerb
+- lib/generators/templates/markerb/unlock_instructions.markerb
+- lib/generators/templates/simple_form_for/confirmations/new.html.erb
+- lib/generators/templates/simple_form_for/passwords/edit.html.erb
+- lib/generators/templates/simple_form_for/passwords/new.html.erb
+- lib/generators/templates/simple_form_for/registrations/edit.html.erb
+- lib/generators/templates/simple_form_for/registrations/new.html.erb
+- lib/generators/templates/simple_form_for/sessions/new.html.erb
+- lib/generators/templates/simple_form_for/unlocks/new.html.erb
+- script/cached-bundle
+- script/s3-put
+- test/controllers/custom_registrations_controller_test.rb
+- test/controllers/custom_strategy_test.rb
+- test/controllers/helpers_test.rb
+- test/controllers/internal_helpers_test.rb
+- test/controllers/passwords_controller_test.rb
+- test/controllers/sessions_controller_test.rb
+- test/controllers/url_helpers_test.rb
+- test/delegator_test.rb
+- test/devise_test.rb
+- test/failure_app_test.rb
+- test/generators/active_record_generator_test.rb
+- test/generators/controllers_generator_test.rb
+- test/generators/devise_generator_test.rb
+- test/generators/install_generator_test.rb
+- test/generators/mongoid_generator_test.rb
+- test/generators/views_generator_test.rb
+- test/helpers/devise_helper_test.rb
+- test/integration/authenticatable_test.rb
+- test/integration/confirmable_test.rb
+- test/integration/database_authenticatable_test.rb
+- test/integration/http_authenticatable_test.rb
+- test/integration/lockable_test.rb
+- test/integration/omniauthable_test.rb
+- test/integration/recoverable_test.rb
+- test/integration/registerable_test.rb
+- test/integration/rememberable_test.rb
+- test/integration/timeoutable_test.rb
+- test/integration/trackable_test.rb
+- test/mailers/confirmation_instructions_test.rb
+- test/mailers/reset_password_instructions_test.rb
+- test/mailers/unlock_instructions_test.rb
+- test/mapping_test.rb
+- test/models/authenticatable_test.rb
+- test/models/confirmable_test.rb
+- test/models/database_authenticatable_test.rb
+- test/models/lockable_test.rb
+- test/models/omniauthable_test.rb
+- test/models/recoverable_test.rb
+- test/models/registerable_test.rb
+- test/models/rememberable_test.rb
+- test/models/serializable_test.rb
+- test/models/timeoutable_test.rb
+- test/models/trackable_test.rb
+- test/models/validatable_test.rb
+- test/models_test.rb
+- test/omniauth/config_test.rb
+- test/omniauth/url_helpers_test.rb
+- test/orm/active_record.rb
+- test/orm/mongoid.rb
+- test/parameter_sanitizer_test.rb
+- test/rails_app/Rakefile
+- test/rails_app/app/active_record/admin.rb
+- test/rails_app/app/active_record/shim.rb
+- test/rails_app/app/active_record/user.rb
+- test/rails_app/app/active_record/user_on_engine.rb
+- test/rails_app/app/active_record/user_on_main_app.rb
+- test/rails_app/app/controllers/admins/sessions_controller.rb
+- test/rails_app/app/controllers/admins_controller.rb
+- test/rails_app/app/controllers/application_controller.rb
+- test/rails_app/app/controllers/application_with_fake_engine.rb
+- test/rails_app/app/controllers/custom/registrations_controller.rb
+- test/rails_app/app/controllers/home_controller.rb
+- test/rails_app/app/controllers/publisher/registrations_controller.rb
+- test/rails_app/app/controllers/publisher/sessions_controller.rb
+- test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb
+- test/rails_app/app/controllers/users_controller.rb
+- test/rails_app/app/helpers/application_helper.rb
+- test/rails_app/app/mailers/users/from_proc_mailer.rb
+- test/rails_app/app/mailers/users/mailer.rb
+- test/rails_app/app/mailers/users/reply_to_mailer.rb
+- test/rails_app/app/mongoid/admin.rb
+- test/rails_app/app/mongoid/shim.rb
+- test/rails_app/app/mongoid/user.rb
+- test/rails_app/app/mongoid/user_on_engine.rb
+- test/rails_app/app/mongoid/user_on_main_app.rb
+- test/rails_app/app/views/admins/index.html.erb
+- test/rails_app/app/views/admins/sessions/new.html.erb
+- test/rails_app/app/views/home/admin_dashboard.html.erb
+- test/rails_app/app/views/home/index.html.erb
+- test/rails_app/app/views/home/join.html.erb
+- test/rails_app/app/views/home/private.html.erb
+- test/rails_app/app/views/home/user_dashboard.html.erb
+- test/rails_app/app/views/layouts/application.html.erb
+- test/rails_app/app/views/users/edit_form.html.erb
+- test/rails_app/app/views/users/index.html.erb
+- test/rails_app/app/views/users/mailer/confirmation_instructions.erb
+- test/rails_app/app/views/users/sessions/new.html.erb
+- test/rails_app/bin/bundle
+- test/rails_app/bin/rails
+- test/rails_app/bin/rake
+- test/rails_app/config.ru
+- test/rails_app/config/application.rb
+- test/rails_app/config/boot.rb
+- test/rails_app/config/database.yml
+- test/rails_app/config/environment.rb
+- test/rails_app/config/environments/development.rb
+- test/rails_app/config/environments/production.rb
+- test/rails_app/config/environments/test.rb
+- test/rails_app/config/initializers/backtrace_silencers.rb
+- test/rails_app/config/initializers/devise.rb
+- test/rails_app/config/initializers/inflections.rb
+- test/rails_app/config/initializers/secret_token.rb
+- test/rails_app/config/initializers/session_store.rb
+- test/rails_app/config/routes.rb
+- test/rails_app/db/migrate/20100401102949_create_tables.rb
+- test/rails_app/db/schema.rb
+- test/rails_app/lib/shared_admin.rb
+- test/rails_app/lib/shared_user.rb
+- test/rails_app/lib/shared_user_without_omniauth.rb
+- test/rails_app/public/404.html
+- test/rails_app/public/422.html
+- test/rails_app/public/500.html
+- test/rails_app/public/favicon.ico
+- test/routes_test.rb
+- test/support/action_controller/record_identifier.rb
+- test/support/assertions.rb
+- test/support/helpers.rb
+- test/support/integration.rb
+- test/support/locale/en.yml
+- test/support/mongoid.yml
+- test/support/webrat/integrations/rails.rb
+- test/test_helper.rb
+- test/test_helpers_test.rb
+- test/test_models.rb
+homepage: https://github.com/plataformatec/devise
+licenses:
+- MIT
+metadata: {}
+post_install_message: 
+rdoc_options: []
+require_paths:
+- lib
+required_ruby_version: !ruby/object:Gem::Requirement
+  requirements:
+  - - ">="
+    - !ruby/object:Gem::Version
+      version: '0'
+required_rubygems_version: !ruby/object:Gem::Requirement
+  requirements:
+  - - ">="
+    - !ruby/object:Gem::Version
+      version: '0'
+requirements: []
+rubyforge_project: devise
+rubygems_version: 2.2.2
+signing_key: 
+specification_version: 4
+summary: Flexible authentication solution for Rails with Warden
+test_files:
+- test/controllers/custom_registrations_controller_test.rb
+- test/controllers/custom_strategy_test.rb
+- test/controllers/helpers_test.rb
+- test/controllers/internal_helpers_test.rb
+- test/controllers/passwords_controller_test.rb
+- test/controllers/sessions_controller_test.rb
+- test/controllers/url_helpers_test.rb
+- test/delegator_test.rb
+- test/devise_test.rb
+- test/failure_app_test.rb
+- test/generators/active_record_generator_test.rb
+- test/generators/controllers_generator_test.rb
+- test/generators/devise_generator_test.rb
+- test/generators/install_generator_test.rb
+- test/generators/mongoid_generator_test.rb
+- test/generators/views_generator_test.rb
+- test/helpers/devise_helper_test.rb
+- test/integration/authenticatable_test.rb
+- test/integration/confirmable_test.rb
+- test/integration/database_authenticatable_test.rb
+- test/integration/http_authenticatable_test.rb
+- test/integration/lockable_test.rb
+- test/integration/omniauthable_test.rb
+- test/integration/recoverable_test.rb
+- test/integration/registerable_test.rb
+- test/integration/rememberable_test.rb
+- test/integration/timeoutable_test.rb
+- test/integration/trackable_test.rb
+- test/mailers/confirmation_instructions_test.rb
+- test/mailers/reset_password_instructions_test.rb
+- test/mailers/unlock_instructions_test.rb
+- test/mapping_test.rb
+- test/models/authenticatable_test.rb
+- test/models/confirmable_test.rb
+- test/models/database_authenticatable_test.rb
+- test/models/lockable_test.rb
+- test/models/omniauthable_test.rb
+- test/models/recoverable_test.rb
+- test/models/registerable_test.rb
+- test/models/rememberable_test.rb
+- test/models/serializable_test.rb
+- test/models/timeoutable_test.rb
+- test/models/trackable_test.rb
+- test/models/validatable_test.rb
+- test/models_test.rb
+- test/omniauth/config_test.rb
+- test/omniauth/url_helpers_test.rb
+- test/orm/active_record.rb
+- test/orm/mongoid.rb
+- test/parameter_sanitizer_test.rb
+- test/rails_app/Rakefile
+- test/rails_app/app/active_record/admin.rb
+- test/rails_app/app/active_record/shim.rb
+- test/rails_app/app/active_record/user.rb
+- test/rails_app/app/active_record/user_on_engine.rb
+- test/rails_app/app/active_record/user_on_main_app.rb
+- test/rails_app/app/controllers/admins/sessions_controller.rb
+- test/rails_app/app/controllers/admins_controller.rb
+- test/rails_app/app/controllers/application_controller.rb
+- test/rails_app/app/controllers/application_with_fake_engine.rb
+- test/rails_app/app/controllers/custom/registrations_controller.rb
+- test/rails_app/app/controllers/home_controller.rb
+- test/rails_app/app/controllers/publisher/registrations_controller.rb
+- test/rails_app/app/controllers/publisher/sessions_controller.rb
+- test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb
+- test/rails_app/app/controllers/users_controller.rb
+- test/rails_app/app/helpers/application_helper.rb
+- test/rails_app/app/mailers/users/from_proc_mailer.rb
+- test/rails_app/app/mailers/users/mailer.rb
+- test/rails_app/app/mailers/users/reply_to_mailer.rb
+- test/rails_app/app/mongoid/admin.rb
+- test/rails_app/app/mongoid/shim.rb
+- test/rails_app/app/mongoid/user.rb
+- test/rails_app/app/mongoid/user_on_engine.rb
+- test/rails_app/app/mongoid/user_on_main_app.rb
+- test/rails_app/app/views/admins/index.html.erb
+- test/rails_app/app/views/admins/sessions/new.html.erb
+- test/rails_app/app/views/home/admin_dashboard.html.erb
+- test/rails_app/app/views/home/index.html.erb
+- test/rails_app/app/views/home/join.html.erb
+- test/rails_app/app/views/home/private.html.erb
+- test/rails_app/app/views/home/user_dashboard.html.erb
+- test/rails_app/app/views/layouts/application.html.erb
+- test/rails_app/app/views/users/edit_form.html.erb
+- test/rails_app/app/views/users/index.html.erb
+- test/rails_app/app/views/users/mailer/confirmation_instructions.erb
+- test/rails_app/app/views/users/sessions/new.html.erb
+- test/rails_app/bin/bundle
+- test/rails_app/bin/rails
+- test/rails_app/bin/rake
+- test/rails_app/config.ru
+- test/rails_app/config/application.rb
+- test/rails_app/config/boot.rb
+- test/rails_app/config/database.yml
+- test/rails_app/config/environment.rb
+- test/rails_app/config/environments/development.rb
+- test/rails_app/config/environments/production.rb
+- test/rails_app/config/environments/test.rb
+- test/rails_app/config/initializers/backtrace_silencers.rb
+- test/rails_app/config/initializers/devise.rb
+- test/rails_app/config/initializers/inflections.rb
+- test/rails_app/config/initializers/secret_token.rb
+- test/rails_app/config/initializers/session_store.rb
+- test/rails_app/config/routes.rb
+- test/rails_app/db/migrate/20100401102949_create_tables.rb
+- test/rails_app/db/schema.rb
+- test/rails_app/lib/shared_admin.rb
+- test/rails_app/lib/shared_user.rb
+- test/rails_app/lib/shared_user_without_omniauth.rb
+- test/rails_app/public/404.html
+- test/rails_app/public/422.html
+- test/rails_app/public/500.html
+- test/rails_app/public/favicon.ico
+- test/routes_test.rb
+- test/support/action_controller/record_identifier.rb
+- test/support/assertions.rb
+- test/support/helpers.rb
+- test/support/integration.rb
+- test/support/locale/en.yml
+- test/support/mongoid.yml
+- test/support/webrat/integrations/rails.rb
+- test/test_helper.rb
+- test/test_helpers_test.rb
+- test/test_models.rb
diff --git a/script/cached-bundle b/script/cached-bundle
new file mode 100755
index 0000000..5142778
--- /dev/null
+++ b/script/cached-bundle
@@ -0,0 +1,49 @@
+#!/usr/bin/env bash
+# Usage: cached-bundle install --deployment
+#
+# After running `bundle`, caches the `vendor/bundle` directory to S3.
+# On the next run, restores the cached directory before running `bundle`.
+# When `Gemfile.lock` changes, the cache gets rebuilt.
+#
+# Requirements:
+# - Gemfile.lock
+# - TRAVIS_REPO_SLUG
+# - TRAVIS_RUBY_VERSION
+# - AMAZON_S3_BUCKET
+# - script/s3-put
+# - bundle
+# - curl
+#
+# Author: Mislav Marohnić
+
+set -e
+
+compute_md5() {
+  local output="$(openssl md5)"
+  echo "${output##* }"
+}
+
+download() {
+  curl --tcp-nodelay -qsfL "$1" -o "$2"
+}
+
+
+gemfile="${BUNDLE_GEMFILE:-Gemfile}"
+bundle_fullpath="$(dirname $gemfile)/vendor/bundle"
+bundle_path=${bundle_fullpath#$PWD/}
+gemfile_hash="$(compute_md5 <"${gemfile}.lock")"
+cache_name="${TRAVIS_RUBY_VERSION}-${gemfile_hash}.tgz"
+fetch_url="http://${AMAZON_S3_BUCKET}.s3.amazonaws.com/${TRAVIS_REPO_SLUG}/${cache_name}"
+
+if download "$fetch_url" "$cache_name"; then
+  echo "Reusing cached bundle ${cache_name}"
+  tar xzf "$cache_name"
+fi
+
+bundle "$@"
+
+if [ ! -f "$cache_name" ] && [ -n "$AMAZON_SECRET_ACCESS_KEY" ]; then
+  echo "Caching \`${bundle_path}' to S3"
+  tar czf "$cache_name" "$bundle_path"
+  script/s3-put "$cache_name" "${AMAZON_S3_BUCKET}:${TRAVIS_REPO_SLUG}/${cache_name}"
+fi
diff --git a/script/s3-put b/script/s3-put
new file mode 100755
index 0000000..036e845
--- /dev/null
+++ b/script/s3-put
@@ -0,0 +1,71 @@
+#!/usr/bin/env bash
+# Usage: s3-put <FILE> <S3_BUCKET>[:<PATH>] [<CONTENT_TYPE>]
+#
+# Uploads a file to the Amazon S3 service.
+# Outputs the URL for the newly uploaded file.
+#
+# Requirements:
+# - AMAZON_ACCESS_KEY_ID
+# - AMAZON_SECRET_ACCESS_KEY
+# - openssl
+# - curl
+#
+# Author: Mislav Marohnić
+
+set -e
+
+authorization() {
+  local signature="$(string_to_sign | hmac_sha1 | base64)"
+  echo "AWS ${AMAZON_ACCESS_KEY_ID?}:${signature}"
+}
+
+hmac_sha1() {
+  openssl dgst -binary -sha1 -hmac "${AMAZON_SECRET_ACCESS_KEY?}"
+}
+
+base64() {
+  openssl enc -base64
+}
+
+bin_md5() {
+  openssl dgst -binary -md5
+}
+
+string_to_sign() {
+  echo "$http_method"
+  echo "$content_md5"
+  echo "$content_type"
+  echo "$date"
+  echo "x-amz-acl:$acl"
+  printf "/$bucket/$remote_path"
+}
+
+date_string() {
+  LC_TIME=C date "+%a, %d %h %Y %T %z"
+}
+
+file="$1"
+bucket="${2%%:*}"
+remote_path="${2#*:}"
+content_type="$3"
+
+if [ -z "$remote_path" ] || [ "$remote_path" = "$bucket" ]; then
+  remote_path="${file##*/}"
+fi
+
+http_method=PUT
+acl="public-read"
+content_md5="$(bin_md5 < "$file" | base64)"
+date="$(date_string)"
+
+url="https://$bucket.s3.amazonaws.com/$remote_path"
+
+curl -qsSf -T "$file" \
+  -H "Authorization: $(authorization)" \
+  -H "x-amz-acl: $acl" \
+  -H "Date: $date" \
+  -H "Content-MD5: $content_md5" \
+  -H "Content-Type: $content_type" \
+  "$url"
+
+echo "$url"
diff --git a/test/controllers/custom_registrations_controller_test.rb b/test/controllers/custom_registrations_controller_test.rb
new file mode 100644
index 0000000..31a93b8
--- /dev/null
+++ b/test/controllers/custom_registrations_controller_test.rb
@@ -0,0 +1,35 @@
+require 'test_helper'
+
+class CustomRegistrationsControllerTest < ActionController::TestCase
+  tests Custom::RegistrationsController
+
+  include Devise::TestHelpers
+
+  setup do
+    request.env["devise.mapping"] = Devise.mappings[:user]
+    @password = 'password'
+    @user = create_user(password: @password, password_confirmation: @password).tap(&:confirm!)
+  end
+
+  test "yield resource to block on create success" do
+    post :create, { user: { email: "user at example.org", password: "password", password_confirmation: "password" } }
+    assert @controller.create_block_called?, "create failed to yield resource to provided block"
+  end
+
+  test "yield resource to block on create failure" do
+    post :create, { user: { } }
+    assert @controller.create_block_called?, "create failed to yield resource to provided block"
+  end
+
+  test "yield resource to block on update success" do
+    sign_in @user
+    put :update, { user: { current_password: @password } }
+    assert @controller.update_block_called?, "update failed to yield resource to provided block"
+  end
+
+  test "yield resource to block on update failure" do
+    sign_in @user
+    put :update, { user: { } }
+    assert @controller.update_block_called?, "update failed to yield resource to provided block"
+  end
+end
diff --git a/test/controllers/custom_strategy_test.rb b/test/controllers/custom_strategy_test.rb
new file mode 100644
index 0000000..798ca77
--- /dev/null
+++ b/test/controllers/custom_strategy_test.rb
@@ -0,0 +1,62 @@
+require 'test_helper'
+require 'ostruct'
+require 'warden/strategies/base'
+require 'devise/test_helpers'
+
+class CustomStrategyController < ActionController::Base
+  def new
+    warden.authenticate!(:custom_strategy)
+  end
+end
+
+# These tests are to prove that a warden strategy can successfully
+# return a custom response, including a specific status code and
+# custom http response headers. This does work in production,
+# however, at the time of writing this, the Devise test helpers do
+# not recognise the custom response and proceed to calling the
+# Failure App. This makes it impossible to write tests for a
+# strategy that return a custom response with Devise.
+class CustomStrategy < Warden::Strategies::Base
+  def authenticate!
+    custom_headers = { "X-FOO" => "BAR" }
+    response = Rack::Response.new("BAD REQUEST", 400, custom_headers)
+    custom! response.finish
+  end
+end
+
+class CustomStrategyTest < ActionController::TestCase
+  tests CustomStrategyController
+
+  include Devise::TestHelpers
+
+  setup do
+    Warden::Strategies.add(:custom_strategy, CustomStrategy)
+  end
+
+  teardown do
+    Warden::Strategies._strategies.delete(:custom_strategy)
+  end
+
+  test "custom strategy can return its own status code" do
+    ret = get :new
+
+    # check the returned rack array
+    assert ret.is_a?(Array)
+    assert_equal 400, ret.first
+
+    # check the saved response as well. This is purely so that the response is available to the testing framework
+    # for verification. In production, the above array would be delivered directly to Rack.
+    assert_response 400
+  end
+
+  test "custom strategy can return custom headers" do
+    ret = get :new
+
+    # check the returned rack array
+    assert ret.is_a?(Array)
+    assert_equal ret.third['X-FOO'], 'BAR'
+
+    # check the saved response headers as well.
+    assert_equal response.headers['X-FOO'], 'BAR'
+  end
+end
diff --git a/test/controllers/helpers_test.rb b/test/controllers/helpers_test.rb
new file mode 100644
index 0000000..4563b66
--- /dev/null
+++ b/test/controllers/helpers_test.rb
@@ -0,0 +1,311 @@
+require 'test_helper'
+require 'ostruct'
+
+class ControllerAuthenticatableTest < ActionController::TestCase
+  tests ApplicationController
+
+  def setup
+    @mock_warden = OpenStruct.new
+    @controller.request.env['warden'] = @mock_warden
+  end
+
+  test 'provide access to warden instance' do
+    assert_equal @mock_warden, @controller.warden
+  end
+
+  test 'proxy signed_in?(scope) to authenticate?' do
+    @mock_warden.expects(:authenticate?).with(scope: :my_scope)
+    @controller.signed_in?(:my_scope)
+  end
+
+  test 'proxy signed_in?(nil) to authenticate?' do
+    Devise.mappings.keys.each do |scope| # :user, :admin, :manager
+      @mock_warden.expects(:authenticate?).with(scope: scope)
+    end
+    @controller.signed_in?
+  end
+
+  test 'proxy [group]_signed_in? to authenticate? with each scope' do
+    [:user, :admin].each do |scope|
+      @mock_warden.expects(:authenticate?).with(scope: scope).returns(false)
+    end
+    @controller.commenter_signed_in?
+  end
+
+  test 'proxy current_user to authenticate with user scope' do
+    @mock_warden.expects(:authenticate).with(scope: :user)
+    @controller.current_user
+  end
+
+  test 'proxy current_admin to authenticate with admin scope' do
+    @mock_warden.expects(:authenticate).with(scope: :admin)
+    @controller.current_admin
+  end
+
+  test 'proxy current_[group] to authenticate with each scope' do
+    [:user, :admin].each do |scope|
+      @mock_warden.expects(:authenticate).with(scope: scope).returns(nil)
+    end
+    @controller.current_commenter
+  end
+
+  test 'proxy current_[plural_group] to authenticate with each scope' do
+    [:user, :admin].each do |scope|
+      @mock_warden.expects(:authenticate).with(scope: scope)
+    end
+    @controller.current_commenters
+  end
+
+  test 'proxy current_publisher_account to authenticate with namespaced publisher account scope' do
+    @mock_warden.expects(:authenticate).with(scope: :publisher_account)
+    @controller.current_publisher_account
+  end
+
+  test 'proxy authenticate_user! to authenticate with user scope' do
+    @mock_warden.expects(:authenticate!).with(scope: :user)
+    @controller.authenticate_user!
+  end
+
+  test 'proxy authenticate_user! options to authenticate with user scope' do
+    @mock_warden.expects(:authenticate!).with(scope: :user, recall: "foo")
+    @controller.authenticate_user!(recall: "foo")
+  end
+
+  test 'proxy authenticate_admin! to authenticate with admin scope' do
+    @mock_warden.expects(:authenticate!).with(scope: :admin)
+    @controller.authenticate_admin!
+  end
+
+  test 'proxy authenticate_[group]! to authenticate!? with each scope' do
+    [:user, :admin].each do |scope|
+      @mock_warden.expects(:authenticate!).with(scope: scope)
+      @mock_warden.expects(:authenticate?).with(scope: scope).returns(false)
+    end
+    @controller.authenticate_commenter!
+  end
+
+  test 'proxy authenticate_publisher_account! to authenticate with namespaced publisher account scope' do
+    @mock_warden.expects(:authenticate!).with(scope: :publisher_account)
+    @controller.authenticate_publisher_account!
+  end
+
+  test 'proxy user_signed_in? to authenticate with user scope' do
+    @mock_warden.expects(:authenticate).with(scope: :user).returns("user")
+    assert @controller.user_signed_in?
+  end
+
+  test 'proxy admin_signed_in? to authenticatewith admin scope' do
+    @mock_warden.expects(:authenticate).with(scope: :admin)
+    assert_not @controller.admin_signed_in?
+  end
+
+  test 'proxy publisher_account_signed_in? to authenticate with namespaced publisher account scope' do
+    @mock_warden.expects(:authenticate).with(scope: :publisher_account)
+    @controller.publisher_account_signed_in?
+  end
+
+  test 'proxy user_session to session scope in warden' do
+    @mock_warden.expects(:authenticate).with(scope: :user).returns(true)
+    @mock_warden.expects(:session).with(:user).returns({})
+    @controller.user_session
+  end
+
+  test 'proxy admin_session to session scope in warden' do
+    @mock_warden.expects(:authenticate).with(scope: :admin).returns(true)
+    @mock_warden.expects(:session).with(:admin).returns({})
+    @controller.admin_session
+  end
+
+  test 'proxy publisher_account_session from namespaced scope to session scope in warden' do
+    @mock_warden.expects(:authenticate).with(scope: :publisher_account).returns(true)
+    @mock_warden.expects(:session).with(:publisher_account).returns({})
+    @controller.publisher_account_session
+  end
+
+  test 'sign in proxy to set_user on warden' do
+    user = User.new
+    @mock_warden.expects(:user).returns(nil)
+    @mock_warden.expects(:set_user).with(user, scope: :user).returns(true)
+    @controller.sign_in(:user, user)
+  end
+
+  test 'sign in accepts a resource as argument' do
+    user = User.new
+    @mock_warden.expects(:user).returns(nil)
+    @mock_warden.expects(:set_user).with(user, scope: :user).returns(true)
+    @controller.sign_in(user)
+  end
+
+  test 'does not sign in again if the user is already in' do
+    user = User.new
+    @mock_warden.expects(:user).returns(user)
+    @mock_warden.expects(:set_user).never
+    assert @controller.sign_in(user)
+  end
+
+  test 'sign in again when the user is already in only if force is given' do
+    user = User.new
+    @mock_warden.expects(:user).returns(user)
+    @mock_warden.expects(:set_user).with(user, scope: :user).returns(true)
+    @controller.sign_in(user, force: true)
+  end
+
+  test 'sign in accepts bypass as option' do
+    user = User.new
+    @mock_warden.expects(:session_serializer).returns(serializer = mock())
+    serializer.expects(:store).with(user, :user)
+    @controller.sign_in(user, bypass: true)
+  end
+
+  test 'sign out clears up any signed in user from all scopes' do
+    user = User.new
+    @mock_warden.expects(:user).times(Devise.mappings.size)
+    @mock_warden.expects(:logout).with().returns(true)
+    @controller.instance_variable_set(:@current_user, user)
+    @controller.instance_variable_set(:@current_admin, user)
+    @controller.sign_out
+    assert_equal nil, @controller.instance_variable_get(:@current_user)
+    assert_equal nil, @controller.instance_variable_get(:@current_admin)
+  end
+
+  test 'sign out logs out and clears up any signed in user by scope' do
+    user = User.new
+    @mock_warden.expects(:user).with(scope: :user, run_callbacks: false).returns(user)
+    @mock_warden.expects(:logout).with(:user).returns(true)
+    @mock_warden.expects(:clear_strategies_cache!).with(scope: :user).returns(true)
+    @controller.instance_variable_set(:@current_user, user)
+    @controller.sign_out(:user)
+    assert_equal nil, @controller.instance_variable_get(:@current_user)
+  end
+
+  test 'sign out accepts a resource as argument' do
+    @mock_warden.expects(:user).with(scope: :user, run_callbacks: false).returns(true)
+    @mock_warden.expects(:logout).with(:user).returns(true)
+    @mock_warden.expects(:clear_strategies_cache!).with(scope: :user).returns(true)
+    @controller.sign_out(User.new)
+  end
+
+  test 'sign out without args proxy to sign out all scopes' do
+    @mock_warden.expects(:user).times(Devise.mappings.size)
+    @mock_warden.expects(:logout).with().returns(true)
+    @mock_warden.expects(:clear_strategies_cache!).with().returns(true)
+    @controller.sign_out
+  end
+
+  test 'sign out everybody proxy to logout on warden' do
+    @mock_warden.expects(:user).times(Devise.mappings.size)
+    @mock_warden.expects(:logout).with().returns(true)
+    @controller.sign_out_all_scopes
+  end
+
+  test 'stored location for returns the location for a given scope' do
+    assert_nil @controller.stored_location_for(:user)
+    @controller.session[:"user_return_to"] = "/foo.bar"
+    assert_equal "/foo.bar", @controller.stored_location_for(:user)
+  end
+
+  test 'stored location for accepts a resource as argument' do
+    assert_nil @controller.stored_location_for(:user)
+    @controller.session[:"user_return_to"] = "/foo.bar"
+    assert_equal "/foo.bar", @controller.stored_location_for(User.new)
+  end
+
+  test 'stored location cleans information after reading' do
+    @controller.session[:"user_return_to"] = "/foo.bar"
+    assert_equal "/foo.bar", @controller.stored_location_for(:user)
+    assert_nil @controller.session[:"user_return_to"]
+  end
+
+  test 'store location for stores a location to redirect back to' do
+    assert_nil @controller.stored_location_for(:user)
+    @controller.store_location_for(:user, "/foo.bar")
+    assert_equal "/foo.bar", @controller.stored_location_for(:user)
+  end
+
+  test 'store bad location for stores a location to redirect back to' do
+    assert_nil @controller.stored_location_for(:user)
+    @controller.store_location_for(:user, "/foo.bar\">Carry")
+    assert_nil @controller.stored_location_for(:user)
+  end
+
+  test 'store location for accepts a resource as argument' do
+    @controller.store_location_for(User.new, "/foo.bar")
+    assert_equal "/foo.bar", @controller.stored_location_for(User.new)
+  end
+
+  test 'store location for stores paths' do
+    @controller.store_location_for(:user, "//host/foo.bar")
+    assert_equal "/foo.bar", @controller.stored_location_for(:user)
+    @controller.store_location_for(:user, "///foo.bar")
+    assert_equal "/foo.bar", @controller.stored_location_for(:user)
+  end
+
+  test 'store location for stores query string' do
+    @controller.store_location_for(:user, "/foo?bar=baz")
+    assert_equal "/foo?bar=baz", @controller.stored_location_for(:user)
+  end
+
+  test 'after sign in path defaults to root path if none by was specified for the given scope' do
+    assert_equal root_path, @controller.after_sign_in_path_for(:user)
+  end
+
+  test 'after sign in path defaults to the scoped root path' do
+    assert_equal admin_root_path, @controller.after_sign_in_path_for(:admin)
+  end
+
+  test 'after sign out path defaults to the root path' do
+    assert_equal root_path, @controller.after_sign_out_path_for(:admin)
+    assert_equal root_path, @controller.after_sign_out_path_for(:user)
+  end
+
+  test 'sign in and redirect uses the stored location' do
+    user = User.new
+    @controller.session[:user_return_to] = "/foo.bar"
+    @mock_warden.expects(:user).with(:user).returns(nil)
+    @mock_warden.expects(:set_user).with(user, scope: :user).returns(true)
+    @controller.expects(:redirect_to).with("/foo.bar")
+    @controller.sign_in_and_redirect(user)
+  end
+
+  test 'sign in and redirect uses the configured after sign in path' do
+    admin = Admin.new
+    @mock_warden.expects(:user).with(:admin).returns(nil)
+    @mock_warden.expects(:set_user).with(admin, scope: :admin).returns(true)
+    @controller.expects(:redirect_to).with(admin_root_path)
+    @controller.sign_in_and_redirect(admin)
+  end
+
+  test 'sign in and redirect does not sign in again if user is already signed' do
+    admin = Admin.new
+    @mock_warden.expects(:user).with(:admin).returns(admin)
+    @mock_warden.expects(:set_user).never
+    @controller.expects(:redirect_to).with(admin_root_path)
+    @controller.sign_in_and_redirect(admin)
+  end
+
+  test 'sign out and redirect uses the configured after sign out path when signing out only the current scope' do
+    swap Devise, sign_out_all_scopes: false do
+      @mock_warden.expects(:user).with(scope: :admin, run_callbacks: false).returns(true)
+      @mock_warden.expects(:logout).with(:admin).returns(true)
+      @mock_warden.expects(:clear_strategies_cache!).with(scope: :admin).returns(true)
+      @controller.expects(:redirect_to).with(admin_root_path)
+      @controller.instance_eval "def after_sign_out_path_for(resource); admin_root_path; end"
+      @controller.sign_out_and_redirect(:admin)
+    end
+  end
+
+  test 'sign out and redirect uses the configured after sign out path when signing out all scopes' do
+    swap Devise, sign_out_all_scopes: true do
+      @mock_warden.expects(:user).times(Devise.mappings.size)
+      @mock_warden.expects(:logout).with().returns(true)
+      @mock_warden.expects(:clear_strategies_cache!).with().returns(true)
+      @controller.expects(:redirect_to).with(admin_root_path)
+      @controller.instance_eval "def after_sign_out_path_for(resource); admin_root_path; end"
+      @controller.sign_out_and_redirect(:admin)
+    end
+  end
+
+  test 'is not a devise controller' do
+    assert_not @controller.devise_controller?
+  end
+end
diff --git a/test/controllers/internal_helpers_test.rb b/test/controllers/internal_helpers_test.rb
new file mode 100644
index 0000000..db5f687
--- /dev/null
+++ b/test/controllers/internal_helpers_test.rb
@@ -0,0 +1,123 @@
+require 'test_helper'
+
+class MyController < DeviseController
+end
+
+class HelpersTest < ActionController::TestCase
+  tests MyController
+
+  def setup
+    @mock_warden = OpenStruct.new
+    @controller.request.env['warden'] = @mock_warden
+    @controller.request.env['devise.mapping'] = Devise.mappings[:user]
+  end
+
+  test 'get resource name from env' do
+    assert_equal :user, @controller.resource_name
+  end
+
+  test 'get resource class from env' do
+    assert_equal User, @controller.resource_class
+  end
+
+  test 'get resource instance variable from env' do
+    @controller.instance_variable_set(:@user, user = User.new)
+    assert_equal user, @controller.resource
+  end
+
+  test 'set resource instance variable from env' do
+    user = @controller.send(:resource_class).new
+    @controller.send(:resource=, user)
+
+    assert_equal user, @controller.send(:resource)
+    assert_equal user, @controller.instance_variable_get(:@user)
+  end
+
+  test 'get resource params from request params using resource name as key' do
+    user_params = {'email' => 'shirley at templar.com'}
+
+    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
+    assert @controller.class.action_methods.delete_if { |m| m.include? 'commenter' }.empty?
+  end
+
+  test 'require no authentication tests current mapping' do
+    @mock_warden.expects(:authenticate?).with(:rememberable, scope: :user).returns(true)
+    @mock_warden.expects(:user).with(:user).returns(User.new)
+    @controller.expects(:redirect_to).with(root_path)
+    @controller.send :require_no_authentication
+  end
+
+  test 'require no authentication only checks if already authenticated if no inputs strategies are available' do
+    Devise.mappings[:user].expects(:no_input_strategies).returns([])
+    @mock_warden.expects(:authenticate?).never
+    @mock_warden.expects(:authenticated?).with(:user).once.returns(true)
+    @mock_warden.expects(:user).with(:user).returns(User.new)
+    @controller.expects(:redirect_to).with(root_path)
+    @controller.send :require_no_authentication
+  end
+
+  test 'require no authentication sets a flash message' do
+    @mock_warden.expects(:authenticate?).with(:rememberable, scope: :user).returns(true)
+    @mock_warden.expects(:user).with(:user).returns(User.new)
+    @controller.expects(:redirect_to).with(root_path)
+    @controller.send :require_no_authentication
+    assert flash[:alert] == I18n.t("devise.failure.already_authenticated")
+  end
+
+  test 'signed in resource returns signed in resource for current scope' do
+    @mock_warden.expects(:authenticate).with(scope: :user).returns(User.new)
+    assert_kind_of User, @controller.signed_in_resource
+  end
+
+  test 'is a devise controller' do
+    assert @controller.devise_controller?
+  end
+
+  test 'does not issue blank flash messages' do
+    I18n.stubs(:t).returns('   ')
+    @controller.send :set_flash_message, :notice, :send_instructions
+    assert flash[:notice].nil?
+  end
+
+  test 'issues non-blank flash messages normally' do
+    I18n.stubs(:t).returns('non-blank')
+    @controller.send :set_flash_message, :notice, :send_instructions
+    assert_equal 'non-blank', flash[:notice]
+  end
+
+  test 'uses custom i18n options' do
+    @controller.stubs(:devise_i18n_options).returns(default: "devise custom options")
+    @controller.send :set_flash_message, :notice, :invalid_i18n_messagesend_instructions
+    assert_equal 'devise custom options', flash[:notice]
+  end
+
+  test 'allows custom i18n options to override resource_name' do
+    I18n.expects(:t).with("custom_resource_name.confirmed", anything)
+    @controller.stubs(:devise_i18n_options).returns(resource_name: "custom_resource_name")
+    @controller.send :set_flash_message, :notice, :confirmed
+  end
+
+  test 'navigational_formats not returning a wild card' do
+    MyController.send(:public, :navigational_formats)
+
+    swap Devise, navigational_formats: ['*/*', :html] do
+      assert_not @controller.navigational_formats.include?("*/*")
+    end
+
+    MyController.send(:protected, :navigational_formats)
+  end
+end
diff --git a/test/controllers/passwords_controller_test.rb b/test/controllers/passwords_controller_test.rb
new file mode 100644
index 0000000..3c225cb
--- /dev/null
+++ b/test/controllers/passwords_controller_test.rb
@@ -0,0 +1,31 @@
+require 'test_helper'
+
+class PasswordsControllerTest < ActionController::TestCase
+  tests Devise::PasswordsController
+  include Devise::TestHelpers
+
+  setup do
+    request.env["devise.mapping"] = Devise.mappings[:user]
+    @user = create_user.tap(&:confirm!)
+    @raw  = @user.send_reset_password_instructions
+  end
+
+  def put_update_with_params
+    put :update, "user" => {
+      "reset_password_token" => @raw, "password" => "1234567", "password_confirmation" => "1234567"
+    }
+  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
diff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rb
new file mode 100644
index 0000000..f82d1e9
--- /dev/null
+++ b/test/controllers/sessions_controller_test.rb
@@ -0,0 +1,103 @@
+require 'test_helper'
+
+class SessionsControllerTest < ActionController::TestCase
+  tests Devise::SessionsController
+  include Devise::TestHelpers
+
+  test "#create doesn't raise unpermitted params when sign in fails" do
+    begin
+      subscriber = 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'
+      create_user
+      post :create, user: {
+        email: "wrong at email.com",
+        password: "wrongpassword"
+      }
+      assert_equal 200, @response.status
+    ensure
+      ActiveSupport::Notifications.unsubscribe(subscriber)
+    end
+  end
+
+  test "#create works even with scoped views" do
+    swap Devise, scoped_views: true do
+      request.env["devise.mapping"] = Devise.mappings[:user]
+      post :create
+      assert_equal 200, @response.status
+      assert_template "users/sessions/new"
+    end
+  end
+
+  test "#create delete the url stored in the session if the requested format is navigational" do
+    request.env["devise.mapping"] = Devise.mappings[:user]
+    request.session["user_return_to"] = 'foo.bar'
+
+    user = create_user
+    user.confirm!
+    post :create, user: {
+      email: user.email,
+      password: user.password
+    }
+
+    assert_nil request.session["user_return_to"]
+  end
+
+  test "#create doesn't delete the url stored in the session if the requested format is not navigational" do
+    request.env["devise.mapping"] = Devise.mappings[:user]
+    request.session["user_return_to"] = 'foo.bar'
+
+    user = create_user
+    user.confirm!
+    post :create, format: 'json', user: {
+      email: user.email,
+      password: user.password
+    }
+
+    assert_equal 'foo.bar', request.session["user_return_to"]
+  end
+
+  test "#create doesn't raise exception after Warden authentication fails when TestHelpers included" do
+    request.env["devise.mapping"] = Devise.mappings[:user]
+    post :create, user: {
+      email: "nosuchuser at example.com",
+      password: "wevdude"
+    }
+    assert_equal 200, @response.status
+    assert_template "devise/sessions/new"
+  end
+
+  test "#destroy doesn't set the flash if the requested format is not navigational" do
+    request.env["devise.mapping"] = Devise.mappings[:user]
+    user = create_user
+    user.confirm!
+    post :create, format: 'json', user: {
+      email: user.email,
+      password: user.password
+    }
+
+    delete :destroy, format: 'json'
+    assert flash[:notice].blank?, "flash[:notice] should be blank, not #{flash[:notice].inspect}"
+    assert_equal 204, @response.status
+  end
+
+  if defined?(ActiveRecord) && ActiveRecord::Base.respond_to?(:mass_assignment_sanitizer)
+    test "#new doesn't raise mass-assignment exception even if sign-in key is attr_protected" do
+      request.env["devise.mapping"] = Devise.mappings[:user]
+
+      ActiveRecord::Base.mass_assignment_sanitizer = :strict
+      User.class_eval { attr_protected :email }
+
+      begin
+        assert_nothing_raised ActiveModel::MassAssignmentSecurity::Error do
+          get :new, user: { email: "allez viens!" }
+        end
+      ensure
+        ActiveRecord::Base.mass_assignment_sanitizer = :logger
+        User.class_eval { attr_accessible :email }
+      end
+    end
+  end
+end
diff --git a/test/controllers/url_helpers_test.rb b/test/controllers/url_helpers_test.rb
new file mode 100644
index 0000000..06895b5
--- /dev/null
+++ b/test/controllers/url_helpers_test.rb
@@ -0,0 +1,65 @@
+require 'test_helper'
+
+class RoutesTest < ActionController::TestCase
+  tests ApplicationController
+
+  def assert_path_and_url(name, prepend_path=nil)
+    @request.path = '/users/session'
+    prepend_path = "#{prepend_path}_" if prepend_path
+
+    # Resource param
+    assert_equal @controller.send(:"#{prepend_path}#{name}_path", :user),
+                 send(:"#{prepend_path}user_#{name}_path")
+    assert_equal @controller.send(:"#{prepend_path}#{name}_url", :user),
+                 send(:"#{prepend_path}user_#{name}_url")
+
+    # With string
+    assert_equal @controller.send(:"#{prepend_path}#{name}_path", "user"),
+                 send(:"#{prepend_path}user_#{name}_path")
+    assert_equal @controller.send(:"#{prepend_path}#{name}_url", "user"),
+                 send(:"#{prepend_path}user_#{name}_url")
+
+    # Default url params
+    assert_equal @controller.send(:"#{prepend_path}#{name}_path", :user, param: 123),
+                 send(:"#{prepend_path}user_#{name}_path", param: 123)
+    assert_equal @controller.send(:"#{prepend_path}#{name}_url", :user, param: 123),
+                 send(:"#{prepend_path}user_#{name}_url", param: 123)
+
+    @request.path = nil
+    # With an object
+    assert_equal @controller.send(:"#{prepend_path}#{name}_path", User.new),
+                 send(:"#{prepend_path}user_#{name}_path")
+    assert_equal @controller.send(:"#{prepend_path}#{name}_url", User.new),
+                 send(:"#{prepend_path}user_#{name}_url")
+  end
+
+
+  test 'should alias session to mapped user session' do
+    assert_path_and_url :session
+    assert_path_and_url :session, :new
+    assert_path_and_url :session, :destroy
+  end
+
+  test 'should alias password to mapped user password' do
+    assert_path_and_url :password
+    assert_path_and_url :password, :new
+    assert_path_and_url :password, :edit
+  end
+
+  test 'should alias confirmation to mapped user confirmation' do
+    assert_path_and_url :confirmation
+    assert_path_and_url :confirmation, :new
+  end
+
+  test 'should alias unlock to mapped user unlock' do
+    assert_path_and_url :unlock
+    assert_path_and_url :unlock, :new
+  end
+
+  test 'should alias registration to mapped user registration' do
+    assert_path_and_url :registration
+    assert_path_and_url :registration, :new
+    assert_path_and_url :registration, :edit
+    assert_path_and_url :registration, :cancel
+  end
+end
diff --git a/test/delegator_test.rb b/test/delegator_test.rb
new file mode 100644
index 0000000..65dda06
--- /dev/null
+++ b/test/delegator_test.rb
@@ -0,0 +1,19 @@
+require 'test_helper'
+
+class DelegatorTest < ActiveSupport::TestCase
+  def delegator
+    Devise::Delegator.new
+  end
+
+  test 'failure_app returns default failure app if no warden options in env' do
+    assert_equal Devise::FailureApp, delegator.failure_app({})
+  end
+
+  test 'failure_app returns default failure app if no scope in warden options' do
+    assert_equal Devise::FailureApp, delegator.failure_app({"warden.options" => {}})
+  end
+
+  test 'failure_app returns associated failure app by scope in the given environment' do
+    assert_kind_of Proc, delegator.failure_app({"warden.options" => {scope: "manager"}})
+  end
+end
diff --git a/test/devise_test.rb b/test/devise_test.rb
new file mode 100644
index 0000000..09f9aa9
--- /dev/null
+++ b/test/devise_test.rb
@@ -0,0 +1,107 @@
+require 'test_helper'
+
+module Devise
+  def self.yield_and_restore
+    @@warden_configured = nil
+    c, b = @@warden_config, @@warden_config_blocks
+    yield
+  ensure
+    @@warden_config, @@warden_config_blocks = c, b
+  end
+end
+
+class DeviseTest < ActiveSupport::TestCase
+  test 'bcrypt on the class' do
+    password = "super secret"
+    klass    = Struct.new(:pepper, :stretches).new("blahblah", 2)
+    hash     = Devise.bcrypt(klass, password)
+    assert_equal ::BCrypt::Password.create(hash), hash
+
+    klass    = Struct.new(:pepper, :stretches).new("bla", 2)
+    hash     = Devise.bcrypt(klass, password)
+    assert_not_equal ::BCrypt::Password.new(hash), hash
+  end
+
+  test 'model options can be configured through Devise' do
+    swap Devise, allow_unconfirmed_access_for: 113, pepper: "foo" do
+      assert_equal 113, Devise.allow_unconfirmed_access_for
+      assert_equal "foo", Devise.pepper
+    end
+  end
+
+  test 'setup block yields self' do
+    Devise.setup do |config|
+      assert_equal Devise, config
+    end
+  end
+
+  test 'stores warden configuration' do
+    assert_kind_of Devise::Delegator, Devise.warden_config.failure_app
+    assert_equal :user, Devise.warden_config.default_scope
+  end
+
+  test 'warden manager user configuration through a block' do
+    Devise.yield_and_restore do
+      executed = false
+      Devise.warden do |config|
+        executed = true
+        assert_kind_of Warden::Config, config
+      end
+
+      Devise.configure_warden!
+      assert executed
+    end
+  end
+
+  test 'warden manager user configuration through multiple blocks' do
+    Devise.yield_and_restore do
+      executed = 0
+
+      3.times do
+        Devise.warden { |config| executed += 1 }
+      end
+
+      Devise.configure_warden!
+      assert_equal 3, executed
+    end
+  end
+
+  test 'add new module using the helper method' do
+    assert_nothing_raised(Exception) { Devise.add_module(:coconut) }
+    assert_equal 1, Devise::ALL.select { |v| v == :coconut }.size
+    assert_not Devise::STRATEGIES.include?(:coconut)
+    assert_not defined?(Devise::Models::Coconut)
+    Devise::ALL.delete(:coconut)
+
+    assert_nothing_raised(Exception) { Devise.add_module(:banana, strategy: :fruits) }
+    assert_equal :fruits, Devise::STRATEGIES[:banana]
+    Devise::ALL.delete(:banana)
+    Devise::STRATEGIES.delete(:banana)
+
+    assert_nothing_raised(Exception) { Devise.add_module(:kivi, controller: :fruits) }
+    assert_equal :fruits, Devise::CONTROLLERS[:kivi]
+    Devise::ALL.delete(:kivi)
+    Devise::CONTROLLERS.delete(:kivi)
+  end
+
+  test 'should complain when comparing empty or different sized passes' do
+    [nil, ""].each do |empty|
+      assert_not Devise.secure_compare(empty, "something")
+      assert_not Devise.secure_compare("something", empty)
+      assert_not Devise.secure_compare(empty, empty)
+    end
+    assert_not Devise.secure_compare("size_1", "size_four")
+  end
+
+  test 'Devise.email_regexp should match valid email addresses' do
+    valid_emails = ["test at example.com", "jo at jo.co", "f4$_m at you.com", "testing.example at example.com.ua"]
+    non_valid_emails = ["rex", "test at go,com", "test user at example.com", "test_user at example server.com"]
+
+    valid_emails.each do |email|
+      assert_match Devise.email_regexp, email
+    end
+    non_valid_emails.each do |email|
+      assert_no_match Devise.email_regexp, email
+    end
+  end
+end
diff --git a/test/failure_app_test.rb b/test/failure_app_test.rb
new file mode 100644
index 0000000..8fb8588
--- /dev/null
+++ b/test/failure_app_test.rb
@@ -0,0 +1,268 @@
+require 'test_helper'
+require 'ostruct'
+
+class FailureTest < ActiveSupport::TestCase
+  class RootFailureApp < Devise::FailureApp
+    def fake_app
+      Object.new
+    end
+  end
+
+  class FailureWithSubdomain < RootFailureApp
+    routes = ActionDispatch::Routing::RouteSet.new
+
+    routes.draw do
+      scope subdomain: 'sub' do
+        root to: 'foo#bar'
+      end
+    end
+
+    include routes.url_helpers
+  end
+
+  class FailureWithI18nOptions < Devise::FailureApp
+    def i18n_options(options)
+      options.merge(name: 'Steve')
+    end
+  end
+
+  def self.context(name, &block)
+    instance_eval(&block)
+  end
+
+  def call_failure(env_params={})
+    env = {
+      'REQUEST_URI' => 'http://test.host/',
+      'HTTP_HOST' => 'test.host',
+      'REQUEST_METHOD' => 'GET',
+      'warden.options' => { scope: :user },
+      'rack.session' => {},
+      'action_dispatch.request.formats' => Array(env_params.delete('formats') || Mime::HTML),
+      'rack.input' => "",
+      'warden' => OpenStruct.new(message: nil)
+    }.merge!(env_params)
+
+    @response = (env.delete(:app) || Devise::FailureApp).call(env).to_a
+    @request  = ActionDispatch::Request.new(env)
+  end
+
+  context 'When redirecting' do
+    test 'returns to the default redirect location' do
+      call_failure
+      assert_equal 302, @response.first
+      assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert]
+      assert_equal 'http://test.host/users/sign_in', @response.second['Location']
+    end
+
+    test 'returns to the default redirect location considering subdomain' do
+      call_failure('warden.options' => { scope: :subdomain_user })
+      assert_equal 302, @response.first
+      assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert]
+      assert_equal 'http://sub.test.host/subdomain_users/sign_in', @response.second['Location']
+    end
+
+    test 'returns to the default redirect location for wildcard requests' do
+      call_failure 'action_dispatch.request.formats' => nil, 'HTTP_ACCEPT' => '*/*'
+      assert_equal 302, @response.first
+      assert_equal 'http://test.host/users/sign_in', @response.second['Location']
+    end
+
+    test 'returns to the root path if no session path is available' do
+      swap Devise, router_name: :fake_app do
+        call_failure app: RootFailureApp
+        assert_equal 302, @response.first
+        assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert]
+        assert_equal 'http://test.host/', @response.second['Location']
+      end
+    end
+
+    test 'returns to the root path considering subdomain if no session path is available' do
+      swap Devise, router_name: :fake_app do
+        call_failure app: FailureWithSubdomain
+        assert_equal 302, @response.first
+        assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert]
+        assert_equal 'http://sub.test.host/', @response.second['Location']
+      end
+    end
+
+    if Rails.application.config.respond_to?(:relative_url_root)
+      test 'returns to the default redirect location considering the relative url root' do
+        swap Rails.application.config, relative_url_root: "/sample" do
+          call_failure
+          assert_equal 302, @response.first
+          assert_equal 'http://test.host/sample/users/sign_in', @response.second['Location']
+        end
+      end
+
+      test 'returns to the default redirect location considering the relative url root and subdomain' do
+        swap Rails.application.config, relative_url_root: "/sample" do
+          call_failure('warden.options' => { scope: :subdomain_user })
+          assert_equal 302, @response.first
+          assert_equal 'http://sub.test.host/sample/subdomain_users/sign_in', @response.second['Location']
+        end
+      end
+    end
+
+    test 'uses the proxy failure message as symbol' do
+      call_failure('warden' => OpenStruct.new(message: :invalid))
+      assert_equal 'Invalid email or password.', @request.flash[:alert]
+      assert_equal 'http://test.host/users/sign_in', @response.second["Location"]
+    end
+
+    test 'uses custom i18n options' do
+      call_failure('warden' => OpenStruct.new(message: :does_not_exist), app: FailureWithI18nOptions)
+      assert_equal 'User Steve does not exist', @request.flash[:alert]
+    end
+
+    test 'uses the proxy failure message as string' do
+      call_failure('warden' => OpenStruct.new(message: 'Hello world'))
+      assert_equal 'Hello world', @request.flash[:alert]
+      assert_equal 'http://test.host/users/sign_in', @response.second["Location"]
+    end
+
+    test 'set content type to default text/html' do
+      call_failure
+      assert_equal 'text/html; charset=utf-8', @response.second['Content-Type']
+    end
+
+    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)
+    end
+
+    test 'works for any navigational format' do
+      swap Devise, navigational_formats: [:xml] do
+        call_failure('formats' => Mime::XML)
+        assert_equal 302, @response.first
+      end
+    end
+
+    test 'redirects the correct format if it is a non-html format request' do
+      swap Devise, navigational_formats: [:js] do
+        call_failure('formats' => Mime::JS)
+        assert_equal 'http://test.host/users/sign_in.js', @response.second["Location"]
+      end
+    end
+  end
+
+  context 'For HTTP request' do
+    test 'return 401 status' do
+      call_failure('formats' => Mime::XML)
+      assert_equal 401, @response.first
+    end
+
+    test 'return appropriate body for xml' do
+      call_failure('formats' => Mime::XML)
+      result = %(<?xml version="1.0" encoding="UTF-8"?>\n<errors>\n  <error>You need to sign in or sign up before continuing.</error>\n</errors>\n)
+      assert_equal result, @response.last.body
+    end
+
+    test 'return appropriate body for json' do
+      call_failure('formats' => Mime::JSON)
+      result = %({"error":"You need to sign in or sign up before continuing."})
+      assert_equal result, @response.last.body
+    end
+
+    test 'return 401 status for unknown formats' do
+      call_failure 'formats' => []
+      assert_equal 401, @response.first
+    end
+
+    test 'return WWW-authenticate headers if model allows' do
+      call_failure('formats' => Mime::XML)
+      assert_equal 'Basic realm="Application"', @response.second["WWW-Authenticate"]
+    end
+
+    test 'does not return WWW-authenticate headers if model does not allow' do
+      swap Devise, http_authenticatable: false do
+        call_failure('formats' => Mime::XML)
+        assert_nil @response.second["WWW-Authenticate"]
+      end
+    end
+
+    test 'works for any non navigational format' do
+      swap Devise, navigational_formats: [] do
+        call_failure('formats' => Mime::HTML)
+        assert_equal 401, @response.first
+      end
+    end
+
+    test 'uses the failure message as response body' do
+      call_failure('formats' => Mime::XML, 'warden' => OpenStruct.new(message: :invalid))
+      assert_match '<error>Invalid email or password.</error>', @response.third.body
+    end
+
+    context 'on ajax call' do
+      context 'when http_authenticatable_on_xhr is false' do
+        test 'dont return 401 with navigational formats' do
+          swap Devise, http_authenticatable_on_xhr: false do
+            call_failure('formats' => Mime::HTML, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest')
+            assert_equal 302, @response.first
+            assert_equal 'http://test.host/users/sign_in', @response.second["Location"]
+          end
+        end
+
+        test 'dont return 401 with non navigational formats' do
+          swap Devise, http_authenticatable_on_xhr: false do
+            call_failure('formats' => Mime::JSON, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest')
+            assert_equal 302, @response.first
+            assert_equal 'http://test.host/users/sign_in.json', @response.second["Location"]
+          end
+        end
+      end
+
+      context 'when http_authenticatable_on_xhr is true' do
+        test 'return 401' do
+          swap Devise, http_authenticatable_on_xhr: true do
+            call_failure('formats' => Mime::HTML, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest')
+            assert_equal 401, @response.first
+          end
+        end
+
+        test 'skip WWW-Authenticate header' do
+          swap Devise, http_authenticatable_on_xhr: true do
+            call_failure('formats' => Mime::HTML, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest')
+            assert_nil @response.second['WWW-Authenticate']
+          end
+        end
+      end
+    end
+  end
+
+  context 'With recall' do
+    test 'calls the original controller if invalid email or password' do
+      env = {
+        "warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in" },
+        "devise.mapping" => Devise.mappings[:user],
+        "warden" => stub_everything
+      }
+      call_failure(env)
+      assert @response.third.body.include?('<h2>Log in</h2>')
+      assert @response.third.body.include?('Invalid email or password.')
+    end
+
+    test 'calls the original controller if not confirmed email' do
+      env = {
+        "warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in", message: :unconfirmed },
+        "devise.mapping" => Devise.mappings[:user],
+        "warden" => stub_everything
+      }
+      call_failure(env)
+      assert @response.third.body.include?('<h2>Log in</h2>')
+      assert @response.third.body.include?('You have to confirm your email address before continuing.')
+    end
+
+    test 'calls the original controller if inactive account' do
+      env = {
+        "warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in", message: :inactive },
+        "devise.mapping" => Devise.mappings[:user],
+        "warden" => stub_everything
+      }
+      call_failure(env)
+      assert @response.third.body.include?('<h2>Log in</h2>')
+      assert @response.third.body.include?('Your account is not activated yet.')
+    end
+  end
+end
diff --git a/test/generators/active_record_generator_test.rb b/test/generators/active_record_generator_test.rb
new file mode 100644
index 0000000..e032bd9
--- /dev/null
+++ b/test/generators/active_record_generator_test.rb
@@ -0,0 +1,109 @@
+require "test_helper"
+
+if DEVISE_ORM == :active_record
+  require "generators/active_record/devise_generator"
+
+  class ActiveRecordGeneratorTest < Rails::Generators::TestCase
+    tests ActiveRecord::Generators::DeviseGenerator
+    destination File.expand_path("../../tmp", __FILE__)
+    setup :prepare_destination
+
+    test "all files are properly created with rails31 migration syntax" do
+      run_generator %w(monster)
+      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_migration "db/migrate/devise_create_admin_monsters.rb", /def change/
+    end
+
+    test "update model migration when model exists" do
+      run_generator %w(monster)
+      assert_file "app/models/monster.rb"
+      run_generator %w(monster)
+      assert_migration "db/migrate/add_devise_to_monsters.rb"
+    end
+
+    test "all files are properly deleted" do
+      run_generator %w(monster)
+      run_generator %w(monster)
+      assert_migration "db/migrate/devise_create_monsters.rb"
+      assert_migration "db/migrate/add_devise_to_monsters.rb"
+      run_generator %w(monster), behavior: :revoke
+      assert_no_migration "db/migrate/add_devise_to_monsters.rb"
+      assert_migration "db/migrate/devise_create_monsters.rb"
+      run_generator %w(monster), behavior: :revoke
+      assert_no_file "app/models/monster.rb"
+      assert_no_migration "db/migrate/devise_create_monsters.rb"
+    end
+
+    test "use string column type for ip addresses" do
+      run_generator %w(monster)
+      assert_migration "db/migrate/devise_create_monsters.rb", /t.string   :current_sign_in_ip/
+      assert_migration "db/migrate/devise_create_monsters.rb", /t.string   :last_sign_in_ip/
+    end
+  end
+
+  module RailsEngine
+    class Engine < Rails::Engine
+      isolate_namespace RailsEngine
+    end
+  end
+
+  def simulate_inside_engine(engine, namespace)
+    if Rails::Generators.respond_to?(:namespace=)
+      swap Rails::Generators, namespace: namespace do
+        yield
+      end
+    else
+      swap Rails, application: engine.instance do
+        yield
+      end
+    end
+  end
+
+  class ActiveRecordEngineGeneratorTest < Rails::Generators::TestCase
+    tests ActiveRecord::Generators::DeviseGenerator
+    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)
+      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
+      end
+    end
+  end
+end
diff --git a/test/generators/controllers_generator_test.rb b/test/generators/controllers_generator_test.rb
new file mode 100644
index 0000000..6df0f0c
--- /dev/null
+++ b/test/generators/controllers_generator_test.rb
@@ -0,0 +1,48 @@
+require "test_helper"
+
+class ControllersGeneratorTest < Rails::Generators::TestCase
+  tests Devise::Generators::ControllersGenerator
+  destination File.expand_path("../../tmp", __FILE__)
+  setup :prepare_destination
+
+  test "Assert no controllers are created with no params" do
+    capture(:stderr) { run_generator }
+    assert_no_file "app/controllers/sessions_controller.rb"
+    assert_no_file "app/controllers/registrations_controller.rb"
+    assert_no_file "app/controllers/confirmations_controller.rb"
+    assert_no_file "app/controllers/passwords_controller.rb"
+    assert_no_file "app/controllers/unlocks_controller.rb"
+    assert_no_file "app/controllers/omniauth_callbacks_controller.rb"
+  end
+
+  test "Assert all controllers are properly created with scope param" do
+    run_generator %w(users)
+    assert_class_names 'users'
+
+    run_generator %w(admins)
+    assert_class_names 'admins'
+  end
+
+  test "Assert specified controllers with scope" do
+    run_generator %w(users -c sessions)
+    assert_file "app/controllers/users/sessions_controller.rb"
+    assert_no_file "app/controllers/users/registrations_controller.rb"
+    assert_no_file "app/controllers/users/confirmations_controller.rb"
+    assert_no_file "app/controllers/users/passwords_controller.rb"
+    assert_no_file "app/controllers/users/unlocks_controller.rb"
+    assert_no_file "app/controllers/users/omniauth_callbacks_controller.rb"
+  end
+
+  private
+
+    def assert_class_names(scope, options = {})
+      base_dir = "app/controllers#{scope.blank? ? '' : ('/' + scope)}"
+      scope_prefix = scope.blank? ? '' : (scope.camelize + '::')
+      controllers = options[:controllers] ||
+        %w(confirmations passwords registrations sessions unlocks omniauth_callbacks)
+
+      controllers.each do |c|
+        assert_file "#{base_dir}/#{c}_controller.rb", /#{scope_prefix + c.camelize}/
+      end
+    end
+end
diff --git a/test/generators/devise_generator_test.rb b/test/generators/devise_generator_test.rb
new file mode 100644
index 0000000..b882468
--- /dev/null
+++ b/test/generators/devise_generator_test.rb
@@ -0,0 +1,39 @@
+require 'test_helper'
+
+require "generators/devise/devise_generator"
+
+class DeviseGeneratorTest < Rails::Generators::TestCase
+  tests Devise::Generators::DeviseGenerator
+  destination File.expand_path("../../tmp", __FILE__)
+
+  setup do
+    prepare_destination
+    copy_routes
+  end
+
+  test "route generation for simple model names" do
+    run_generator %w(monster name:string)
+    assert_file "config/routes.rb", /devise_for :monsters/
+  end
+
+  test "route generation for namespaced model names" do
+    run_generator %w(monster/goblin name:string)
+    match = /devise_for :goblins, class_name: "Monster::Goblin"/
+    assert_file "config/routes.rb", match
+  end
+
+  test "route generation with skip routes" do
+    run_generator %w(monster name:string --skip-routes)
+    match = /devise_for :monsters, skip: :all/
+    assert_file "config/routes.rb", match
+  end
+
+  def copy_routes
+    routes = File.expand_path("../../rails_app/config/routes.rb", __FILE__)
+    destination = File.join(destination_root, "config")
+
+    FileUtils.mkdir_p(destination)
+    FileUtils.cp routes, destination
+  end
+
+end
diff --git a/test/generators/install_generator_test.rb b/test/generators/install_generator_test.rb
new file mode 100644
index 0000000..db63e23
--- /dev/null
+++ b/test/generators/install_generator_test.rb
@@ -0,0 +1,13 @@
+require "test_helper"
+
+class InstallGeneratorTest < Rails::Generators::TestCase
+  tests Devise::Generators::InstallGenerator
+  destination File.expand_path("../../tmp", __FILE__)
+  setup :prepare_destination
+
+  test "Assert all files are properly created" do
+    run_generator
+    assert_file "config/initializers/devise.rb"
+    assert_file "config/locales/devise.en.yml"
+  end
+end
diff --git a/test/generators/mongoid_generator_test.rb b/test/generators/mongoid_generator_test.rb
new file mode 100644
index 0000000..51802e8
--- /dev/null
+++ b/test/generators/mongoid_generator_test.rb
@@ -0,0 +1,23 @@
+require "test_helper"
+
+if DEVISE_ORM == :mongoid
+  require "generators/mongoid/devise_generator"
+
+  class MongoidGeneratorTest < Rails::Generators::TestCase
+    tests Mongoid::Generators::DeviseGenerator
+    destination File.expand_path("../../tmp", __FILE__)
+    setup :prepare_destination
+
+    test "all files are properly created" do
+      run_generator %w(monster)
+      assert_file "app/models/monster.rb", /devise/
+    end
+
+    test "all files are properly deleted" do
+      run_generator %w(monster)
+      run_generator %w(monster), behavior: :revoke
+      assert_no_file "app/models/monster.rb"
+    end
+  end
+end
+
diff --git a/test/generators/views_generator_test.rb b/test/generators/views_generator_test.rb
new file mode 100644
index 0000000..052b2ad
--- /dev/null
+++ b/test/generators/views_generator_test.rb
@@ -0,0 +1,96 @@
+require "test_helper"
+
+class ViewsGeneratorTest < Rails::Generators::TestCase
+  tests Devise::Generators::ViewsGenerator
+  destination File.expand_path("../../tmp", __FILE__)
+  setup :prepare_destination
+
+  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" 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
+    run_generator %w(-b simple_form_for)
+    assert_files
+    assert_file "app/views/devise/confirmations/new.html.erb", /simple_form_for/
+
+    run_generator %w(users -b simple_form_for)
+    assert_files "users"
+    assert_file "app/views/users/confirmations/new.html.erb", /simple_form_for/
+  end
+
+  test "Assert views with markerb" do
+    run_generator %w(--markerb)
+    assert_files nil, mail_template_engine: "markerb"
+  end
+
+
+  test "Assert only views within specified directories" do
+    run_generator %w(-v sessions registrations)
+    assert_file "app/views/devise/sessions/new.html.erb"
+    assert_file "app/views/devise/registrations/new.html.erb"
+    assert_file "app/views/devise/registrations/edit.html.erb"
+    assert_no_file "app/views/devise/confirmations/new.html.erb"
+    assert_no_file "app/views/devise/mailer/confirmation_instructions.html.erb"
+  end
+
+  test "Assert specified directories with scope" do
+    run_generator %w(users -v sessions)
+    assert_file "app/views/users/sessions/new.html.erb"
+    assert_no_file "app/views/users/confirmations/new.html.erb"
+  end
+
+  test "Assert specified directories with simple form" do
+    run_generator %w(-v registrations -b simple_form_for)
+    assert_file "app/views/devise/registrations/new.html.erb", /simple_form_for/
+    assert_no_file "app/views/devise/confirmations/new.html.erb"
+    end
+
+  test "Assert specified directories with markerb" do
+    run_generator %w(--markerb -v passwords mailer)
+    assert_file "app/views/devise/passwords/new.html.erb"
+    assert_no_file "app/views/devise/confirmations/new.html.erb"
+    assert_file "app/views/devise/mailer/reset_password_instructions.markerb"
+  end
+
+  def assert_files(scope = nil, options={})
+    scope = "devise" if scope.nil?
+    mail_template_engine = options[:mail_template_engine] || "html.erb"
+
+    assert_file "app/views/#{scope}/confirmations/new.html.erb"
+    assert_file "app/views/#{scope}/mailer/confirmation_instructions.#{mail_template_engine}"
+    assert_file "app/views/#{scope}/mailer/reset_password_instructions.#{mail_template_engine}"
+    assert_file "app/views/#{scope}/mailer/unlock_instructions.#{mail_template_engine}"
+    assert_file "app/views/#{scope}/passwords/edit.html.erb"
+    assert_file "app/views/#{scope}/passwords/new.html.erb"
+    assert_file "app/views/#{scope}/registrations/new.html.erb"
+    assert_file "app/views/#{scope}/registrations/edit.html.erb"
+    assert_file "app/views/#{scope}/sessions/new.html.erb"
+    assert_file "app/views/#{scope}/shared/_links.html.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
diff --git a/test/helpers/devise_helper_test.rb b/test/helpers/devise_helper_test.rb
new file mode 100644
index 0000000..df4b23f
--- /dev/null
+++ b/test/helpers/devise_helper_test.rb
@@ -0,0 +1,49 @@
+require 'test_helper'
+
+class DeviseHelperTest < ActionDispatch::IntegrationTest
+  setup do
+    model_labels = { models: { user: "the user" } }
+    translations = {
+      errors: { messages: { not_saved: {
+        one: "Can't save %{resource} because of 1 error",
+        other: "Can't save %{resource} because of %{count} errors",
+      } } },
+      activerecord: model_labels,
+      mongoid: model_labels
+    }
+
+    I18n.available_locales
+    I18n.backend.store_translations(:en, translations)
+  end
+
+  teardown do
+    I18n.reload!
+  end
+
+  test 'test errors.messages.not_saved with single error from i18n' do
+    get new_user_registration_path
+
+    fill_in 'password', with: 'new_user123'
+    fill_in 'password confirmation', with: 'new_user123'
+    click_button 'Sign up'
+
+    assert_have_selector '#error_explanation'
+    assert_contain "Can't save the user because of 1 error"
+  end
+
+  test 'test errors.messages.not_saved with multiple errors from i18n' do
+    # Dirty tracking behavior prevents email validations from being applied:
+    #    https://github.com/mongoid/mongoid/issues/756
+    (pending "Fails on Mongoid < 2.1"; break) if defined?(Mongoid) && Mongoid::VERSION.to_f < 2.1
+
+    get new_user_registration_path
+
+    fill_in 'email', with: 'invalid_email'
+    fill_in 'password', with: 'new_user123'
+    fill_in 'password confirmation', with: 'new_user321'
+    click_button 'Sign up'
+
+    assert_have_selector '#error_explanation'
+    assert_contain "Can't save the user because of 2 errors"
+  end
+end
diff --git a/test/integration/authenticatable_test.rb b/test/integration/authenticatable_test.rb
new file mode 100644
index 0000000..8048390
--- /dev/null
+++ b/test/integration/authenticatable_test.rb
@@ -0,0 +1,729 @@
+require 'test_helper'
+
+class AuthenticationSanityTest < ActionDispatch::IntegrationTest
+  test 'home should be accessible without sign in' do
+    visit '/'
+    assert_response :success
+    assert_template 'home/index'
+  end
+
+  test 'sign in as user should not authenticate admin scope' do
+    sign_in_as_user
+    assert warden.authenticated?(:user)
+    assert_not warden.authenticated?(:admin)
+  end
+
+  test 'sign in as admin should not authenticate user scope' do
+    sign_in_as_admin
+    assert warden.authenticated?(:admin)
+    assert_not warden.authenticated?(:user)
+  end
+
+  test 'sign in as both user and admin at same time' do
+    sign_in_as_user
+    sign_in_as_admin
+    assert warden.authenticated?(:user)
+    assert warden.authenticated?(:admin)
+  end
+
+  test 'sign out as user should not touch admin authentication if sign_out_all_scopes is false' do
+    swap Devise, sign_out_all_scopes: false do
+      sign_in_as_user
+      sign_in_as_admin
+      get destroy_user_session_path
+      assert_not warden.authenticated?(:user)
+      assert warden.authenticated?(:admin)
+    end
+  end
+
+  test 'sign out as admin should not touch user authentication if sign_out_all_scopes is false' do
+    swap Devise, sign_out_all_scopes: false do
+      sign_in_as_user
+      sign_in_as_admin
+
+      get destroy_admin_session_path
+      assert_not warden.authenticated?(:admin)
+      assert warden.authenticated?(:user)
+    end
+  end
+
+  test 'sign out as user should also sign out admin if sign_out_all_scopes is true' do
+    swap Devise, sign_out_all_scopes: true do
+      sign_in_as_user
+      sign_in_as_admin
+
+      get destroy_user_session_path
+      assert_not warden.authenticated?(:user)
+      assert_not warden.authenticated?(:admin)
+    end
+  end
+
+  test 'sign out as admin should also sign out user if sign_out_all_scopes is true' do
+    swap Devise, sign_out_all_scopes: true do
+      sign_in_as_user
+      sign_in_as_admin
+
+      get destroy_admin_session_path
+      assert_not warden.authenticated?(:admin)
+      assert_not warden.authenticated?(:user)
+    end
+  end
+
+  test 'not signed in as admin should not be able to access admins actions' do
+    get admins_path
+    assert_redirected_to new_admin_session_path
+    assert_not warden.authenticated?(:admin)
+  end
+
+  test 'signed in as user should not be able to access admins actions' do
+    sign_in_as_user
+    assert warden.authenticated?(:user)
+    assert_not warden.authenticated?(:admin)
+
+    get admins_path
+    assert_redirected_to new_admin_session_path
+  end
+
+  test 'signed in as admin should be able to access admin actions' do
+    sign_in_as_admin
+    assert warden.authenticated?(:admin)
+    assert_not warden.authenticated?(:user)
+
+    get admins_path
+
+    assert_response :success
+    assert_template 'admins/index'
+    assert_contain 'Welcome Admin'
+  end
+
+  test 'authenticated admin should not be able to sign as admin again' do
+    sign_in_as_admin
+    get new_admin_session_path
+
+    assert_response :redirect
+    assert_redirected_to admin_root_path
+    assert warden.authenticated?(:admin)
+  end
+
+  test 'authenticated admin should be able to sign out' do
+    sign_in_as_admin
+    assert warden.authenticated?(:admin)
+
+    get destroy_admin_session_path
+    assert_response :redirect
+    assert_redirected_to root_path
+
+    get root_path
+    assert_contain 'Signed out successfully'
+    assert_not warden.authenticated?(:admin)
+  end
+
+  test 'unauthenticated admin set message on sign out' do
+    get destroy_admin_session_path
+    assert_response :redirect
+    assert_redirected_to root_path
+
+    get root_path
+    assert_contain 'Signed out successfully'
+  end
+
+  test 'scope uses custom failure app' do
+    put "/en/accounts/management"
+    assert_equal "Oops, not found", response.body
+    assert_equal 404, response.status
+  end
+end
+
+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
+    assert_not warden.authenticated?(:admin)
+  end
+
+  test 'signed in as user should not be able to access private route restricted to admins (authenticate denied)' do
+    sign_in_as_user
+    assert warden.authenticated?(:user)
+    assert_not warden.authenticated?(:admin)
+    get private_path
+    assert_redirected_to new_admin_session_path
+  end
+
+  test 'signed in as admin should be able to access private route restricted to admins (authenticate accepted)' do
+    sign_in_as_admin
+    assert warden.authenticated?(:admin)
+    assert_not warden.authenticated?(:user)
+
+    get private_path
+
+    assert_response :success
+    assert_template 'home/private'
+    assert_contain 'Private!'
+  end
+
+  test 'signed in as inactive admin should not be able to access private/active route restricted to active admins (authenticate denied)' do
+    sign_in_as_admin(active: false)
+    assert warden.authenticated?(:admin)
+    assert_not warden.authenticated?(:user)
+
+    assert_raises ActionController::RoutingError do
+      get "/private/active"
+    end
+  end
+
+  test 'signed in as active admin should be able to access private/active route restricted to active admins (authenticate accepted)' do
+    sign_in_as_admin(active: true)
+    assert warden.authenticated?(:admin)
+    assert_not warden.authenticated?(:user)
+
+    get private_active_path
+
+    assert_response :success
+    assert_template 'home/private'
+    assert_contain 'Private!'
+  end
+
+  test 'signed in as admin should get admin dashboard (authenticated accepted)' do
+    sign_in_as_admin
+    assert warden.authenticated?(:admin)
+    assert_not warden.authenticated?(:user)
+
+    get dashboard_path
+
+    assert_response :success
+    assert_template 'home/admin_dashboard'
+    assert_contain 'Admin dashboard'
+  end
+
+  test 'signed in as user should get user dashboard (authenticated accepted)' do
+    sign_in_as_user
+    assert warden.authenticated?(:user)
+    assert_not warden.authenticated?(:admin)
+
+    get dashboard_path
+
+    assert_response :success
+    assert_template 'home/user_dashboard'
+    assert_contain 'User dashboard'
+  end
+
+  test 'not signed in should get no dashboard (authenticated denied)' do
+    assert_raises ActionController::RoutingError do
+      get dashboard_path
+    end
+  end
+
+  test 'signed in as inactive admin should not be able to access dashboard/active route restricted to active admins (authenticated denied)' do
+    sign_in_as_admin(active: false)
+    assert warden.authenticated?(:admin)
+    assert_not warden.authenticated?(:user)
+
+    assert_raises ActionController::RoutingError do
+      get "/dashboard/active"
+    end
+  end
+
+  test 'signed in as active admin should be able to access dashboard/active route restricted to active admins (authenticated accepted)' do
+    sign_in_as_admin(active: true)
+    assert warden.authenticated?(:admin)
+    assert_not warden.authenticated?(:user)
+
+    get dashboard_active_path
+
+    assert_response :success
+    assert_template 'home/admin_dashboard'
+    assert_contain 'Admin dashboard'
+  end
+
+  test 'signed in user should not see unauthenticated page (unauthenticated denied)' do
+    sign_in_as_user
+    assert warden.authenticated?(:user)
+    assert_not warden.authenticated?(:admin)
+
+    assert_raises ActionController::RoutingError do
+      get join_path
+    end
+  end
+
+  test 'not signed in users should see unautheticated page (unauthenticated accepted)' do
+    get join_path
+
+    assert_response :success
+    assert_template 'home/join'
+    assert_contain 'Join'
+  end
+end
+
+class AuthenticationRedirectTest < ActionDispatch::IntegrationTest
+  test 'redirect from warden shows sign in or sign up message' do
+    get admins_path
+
+    warden_path = new_admin_session_path
+    assert_redirected_to warden_path
+
+    get warden_path
+    assert_contain 'You need to sign in or sign up before continuing.'
+  end
+
+  test 'redirect to default url if no other was configured' do
+    sign_in_as_user
+    assert_template 'home/index'
+    assert_nil session[:"user_return_to"]
+  end
+
+  test 'redirect to requested url after sign in' do
+    get users_path
+    assert_redirected_to new_user_session_path
+    assert_equal users_path, session[:"user_return_to"]
+
+    follow_redirect!
+    sign_in_as_user visit: false
+
+    assert_current_url '/users'
+    assert_nil session[:"user_return_to"]
+  end
+
+  test 'redirect to last requested url overwriting the stored return_to option' do
+    get expire_user_path(create_user)
+    assert_redirected_to new_user_session_path
+    assert_equal expire_user_path(create_user), session[:"user_return_to"]
+
+    get users_path
+    assert_redirected_to new_user_session_path
+    assert_equal users_path, session[:"user_return_to"]
+
+    follow_redirect!
+    sign_in_as_user visit: false
+
+    assert_current_url '/users'
+    assert_nil session[:"user_return_to"]
+  end
+
+  test 'xml http requests does not store urls for redirect' do
+    get users_path, {}, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'
+    assert_equal 401, response.status
+    assert_nil session[:"user_return_to"]
+  end
+
+  test 'redirect to configured home path for a given scope after sign in' do
+    sign_in_as_admin
+    assert_equal "/admin_area/home", @request.path
+  end
+
+  test 'require_no_authentication should set the already_authenticated flash message' do
+    sign_in_as_user
+    visit new_user_session_path
+    assert_equal flash[:alert], I18n.t("devise.failure.already_authenticated")
+  end
+end
+
+class AuthenticationSessionTest < ActionDispatch::IntegrationTest
+  test 'destroyed account is signed out' do
+    sign_in_as_user
+    get '/users'
+
+    User.destroy_all
+    get '/users'
+    assert_redirected_to new_user_session_path
+  end
+
+  test 'refreshes _csrf_token' do
+    ApplicationController.allow_forgery_protection = true
+
+    begin
+      get new_user_session_path
+      token = request.session[:_csrf_token]
+
+      sign_in_as_user
+      assert_not_equal request.session[:_csrf_token], token
+    ensure
+      ApplicationController.allow_forgery_protection = false
+    end
+  end
+
+  test 'allows session to be set for a given scope' do
+    sign_in_as_user
+    get '/users'
+    assert_equal "Cart", @controller.user_session[:cart]
+  end
+
+  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)
+    ensure
+      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
+
+  test 'session id is changed on sign in' do
+    get '/users'
+    session_id = request.session["session_id"]
+
+    get '/users'
+    assert_equal session_id, request.session["session_id"]
+
+    sign_in_as_user
+    assert_not_equal session_id, request.session["session_id"]
+  end
+end
+
+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
+        sign_in_as_user
+      end
+      assert_match /Special user view/, response.body
+    end
+  end
+
+  test 'renders the scoped view if turned on in an specific controller' do
+    begin
+      Devise::SessionsController.scoped_views = true
+      assert_raise Webrat::NotFoundError do
+        sign_in_as_user
+      end
+
+      assert_match /Special user view/, response.body
+      assert !Devise::PasswordsController.scoped_views?
+    ensure
+      Devise::SessionsController.send :remove_instance_variable, :@scoped_views
+    end
+  end
+
+  test 'does not render the scoped view if turned off' do
+    swap Devise, scoped_views: false do
+      assert_nothing_raised do
+        sign_in_as_user
+      end
+    end
+  end
+
+  test 'does not render the scoped view if not available' do
+    swap Devise, scoped_views: true do
+      assert_nothing_raised do
+        sign_in_as_admin
+      end
+    end
+  end
+end
+
+class AuthenticationOthersTest < ActionDispatch::IntegrationTest
+  test 'handles unverified requests gets rid of caches' do
+    swap ApplicationController, allow_forgery_protection: true do
+      post exhibit_user_url(1)
+      assert_not warden.authenticated?(:user)
+
+      sign_in_as_user
+      assert warden.authenticated?(:user)
+
+      post exhibit_user_url(1)
+      assert_not warden.authenticated?(:user)
+      assert_equal "User is not authenticated", response.body
+    end
+  end
+
+  test 'uses the custom controller with the custom controller view' do
+    get '/admin_area/sign_in'
+    assert_contain 'Log in'
+    assert_contain 'Welcome to "admins/sessions" controller!'
+    assert_contain 'Welcome to "sessions/new" view!'
+  end
+
+  test 'render 404 on roles without routes' do
+    assert_raise ActionController::RoutingError do
+      get '/admin_area/password/new'
+    end
+  end
+
+  test 'does not intercept Rails 401 responses' do
+    get '/unauthenticated'
+    assert_equal 401, response.status
+  end
+
+  test 'render 404 on roles without mapping' do
+    assert_raise AbstractController::ActionNotFound do
+      get '/sign_in'
+    end
+  end
+
+  test 'sign in with script name' do
+    assert_nothing_raised do
+      get new_user_session_path, {}, "SCRIPT_NAME" => "/omg"
+      fill_in "email", with: "user at test.com"
+    end
+  end
+
+  test 'sign in stub in xml format' do
+    get new_user_session_path(format: 'xml')
+    assert_match '<?xml version="1.0" encoding="UTF-8"?>', response.body
+    assert_match /<user>.*<\/user>/m, response.body
+    assert_match '<email></email>', response.body
+    assert_match '<password nil="true"', response.body
+  end
+
+  test 'sign in stub in json format' do
+    get new_user_session_path(format: 'json')
+    assert_match '{"user":{', response.body
+    assert_match '"email":""', response.body
+    assert_match '"password":null', response.body
+  end
+
+  test 'sign in stub in json with non attribute key' do
+    swap Devise, authentication_keys: [:other_key] do
+      get new_user_session_path(format: 'json')
+      assert_match '{"user":{', response.body
+      assert_match '"other_key":null', response.body
+      assert_match '"password":null', response.body
+    end
+  end
+
+  test 'uses the mapping from router' do
+    sign_in_as_user visit: "/as/sign_in"
+    assert warden.authenticated?(:user)
+    assert_not warden.authenticated?(:admin)
+  end
+
+  test 'sign in with xml format returns xml response' do
+    create_user
+    post user_session_path(format: 'xml'), user: {email: "user at test.com", password: '12345678'}
+    assert_response :success
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<user>)
+  end
+
+  test 'sign in with xml format is idempotent' do
+    get new_user_session_path(format: 'xml')
+    assert_response :success
+
+    create_user
+    post user_session_path(format: 'xml'), user: {email: "user at test.com", password: '12345678'}
+    assert_response :success
+
+    get new_user_session_path(format: 'xml')
+    assert_response :success
+
+    post user_session_path(format: 'xml'), user: {email: "user at test.com", password: '12345678'}
+    assert_response :success
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<user>)
+  end
+
+  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 no content' do
+    sign_in_as_user
+    get destroy_user_session_path(format: 'json')
+    assert_response :no_content
+    assert_not warden.authenticated?(:user)
+  end
+
+  test 'sign out with non-navigational format via XHR does not redirect' 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
+      assert_not warden.authenticated?(:user)
+    end
+  end
+
+  # 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
+      sign_in_as_user
+      xml_http_request :get, destroy_user_session_path, {}, { "HTTP_ACCEPT" => "text/html,*/*" }
+      assert_response :redirect
+      assert_not warden.authenticated?(:user)
+    end
+  end
+end
+
+class AuthenticationKeysTest < ActionDispatch::IntegrationTest
+  test 'missing authentication keys cause authentication to abort' do
+    swap Devise, authentication_keys: [:subdomain] do
+      sign_in_as_user
+      assert_contain "Invalid subdomain or password."
+      assert_not warden.authenticated?(:user)
+    end
+  end
+
+  test 'missing authentication keys cause authentication to abort unless marked as not required' do
+    swap Devise, authentication_keys: { email: true, subdomain: false } do
+      sign_in_as_user
+      assert warden.authenticated?(:user)
+    end
+  end
+end
+
+class AuthenticationRequestKeysTest < ActionDispatch::IntegrationTest
+  test 'request keys are used on authentication' do
+    host! 'foo.bar.baz'
+
+    swap Devise, request_keys: [:subdomain] do
+      User.expects(:find_for_authentication).with(subdomain: 'foo', email: 'user at test.com').returns(create_user)
+      sign_in_as_user
+      assert warden.authenticated?(:user)
+    end
+  end
+
+  test 'invalid request keys raises NoMethodError' do
+    swap Devise, request_keys: [:unknown_method] do
+      assert_raise NoMethodError do
+        sign_in_as_user
+      end
+
+      assert_not warden.authenticated?(:user)
+    end
+  end
+
+  test 'blank request keys cause authentication to abort' do
+    host! 'test.com'
+
+    swap Devise, request_keys: [:subdomain] do
+      sign_in_as_user
+      assert_contain "Invalid email or password."
+      assert_not warden.authenticated?(:user)
+    end
+  end
+
+  test 'blank request keys cause authentication to abort unless if marked as not required' do
+    host! 'test.com'
+
+    swap Devise, request_keys: { subdomain: false } do
+      sign_in_as_user
+      assert warden.authenticated?(:user)
+    end
+  end
+end
+
+class AuthenticationSignOutViaTest < ActionDispatch::IntegrationTest
+  def sign_in!(scope)
+    sign_in_as_admin(visit: send("new_#{scope}_session_path"))
+    assert warden.authenticated?(scope)
+  end
+
+  test 'allow sign out via delete when sign_out_via provides only delete' do
+    sign_in!(:sign_out_via_delete)
+    delete destroy_sign_out_via_delete_session_path
+    assert_not warden.authenticated?(:sign_out_via_delete)
+  end
+
+  test 'do not allow sign out via get when sign_out_via provides only delete' do
+    sign_in!(:sign_out_via_delete)
+    assert_raise ActionController::RoutingError do
+      get destroy_sign_out_via_delete_session_path
+    end
+    assert warden.authenticated?(:sign_out_via_delete)
+  end
+
+  test 'allow sign out via post when sign_out_via provides only post' do
+    sign_in!(:sign_out_via_post)
+    post destroy_sign_out_via_post_session_path
+    assert_not warden.authenticated?(:sign_out_via_post)
+  end
+
+  test 'do not allow sign out via get when sign_out_via provides only post' do
+    sign_in!(:sign_out_via_post)
+    assert_raise ActionController::RoutingError do
+      get destroy_sign_out_via_delete_session_path
+    end
+    assert warden.authenticated?(:sign_out_via_post)
+  end
+
+  test 'allow sign out via delete when sign_out_via provides delete and post' do
+    sign_in!(:sign_out_via_delete_or_post)
+    delete destroy_sign_out_via_delete_or_post_session_path
+    assert_not warden.authenticated?(:sign_out_via_delete_or_post)
+  end
+
+  test 'allow sign out via post when sign_out_via provides delete and post' do
+    sign_in!(:sign_out_via_delete_or_post)
+    post destroy_sign_out_via_delete_or_post_session_path
+    assert_not warden.authenticated?(:sign_out_via_delete_or_post)
+  end
+
+  test 'do not allow sign out via get when sign_out_via provides delete and post' do
+    sign_in!(:sign_out_via_delete_or_post)
+    assert_raise ActionController::RoutingError do
+      get destroy_sign_out_via_delete_or_post_session_path
+    end
+    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
+
+class DoubleSignOutRedirectTest < ActionDispatch::IntegrationTest
+  test 'sign out after already having signed out redirects to sign in' do
+    sign_in_as_user
+
+    post destroy_sign_out_via_delete_or_post_session_path
+
+    get root_path
+    assert_contain 'Signed out successfully.'
+
+    post destroy_sign_out_via_delete_or_post_session_path
+
+    get root_path
+    assert_contain 'Signed out successfully.'
+  end
+end
diff --git a/test/integration/confirmable_test.rb b/test/integration/confirmable_test.rb
new file mode 100644
index 0000000..d04b00c
--- /dev/null
+++ b/test/integration/confirmable_test.rb
@@ -0,0 +1,324 @@
+require 'test_helper'
+
+class ConfirmationTest < ActionDispatch::IntegrationTest
+
+  def visit_user_confirmation_with_token(confirmation_token)
+    visit user_confirmation_path(confirmation_token: confirmation_token)
+  end
+
+  def resend_confirmation
+    user = create_user(confirm: false)
+    ActionMailer::Base.deliveries.clear
+
+    visit new_user_session_path
+    click_link "Didn't receive confirmation instructions?"
+
+    fill_in 'email', with: user.email
+    click_button 'Resend confirmation instructions'
+  end
+
+  test 'user should be able to request a new confirmation' do
+    resend_confirmation
+
+    assert_current_url '/users/sign_in'
+    assert_contain 'You will receive an email with instructions for how to confirm your email address in a few minutes'
+    assert_equal 1, ActionMailer::Base.deliveries.size
+    assert_equal ['please-change-me at config-initializers-devise.com'], ActionMailer::Base.deliveries.first.from
+  end
+
+  test 'user should receive a confirmation from a custom mailer' do
+    User.any_instance.stubs(:devise_mailer).returns(Users::Mailer)
+    resend_confirmation
+    assert_equal ['custom at example.com'], ActionMailer::Base.deliveries.first.from
+  end
+
+  test 'user with invalid confirmation token should not be able to confirm an account' do
+    visit_user_confirmation_with_token('invalid_confirmation')
+    assert_have_selector '#error_explanation'
+    assert_contain /Confirmation token(.*)invalid/
+  end
+
+  test 'user with valid confirmation token should not be able to confirm an account after the token has expired' do
+    swap Devise, confirm_within: 3.days do
+      user = create_user(confirm: false, confirmation_sent_at: 4.days.ago)
+      assert_not user.confirmed?
+      visit_user_confirmation_with_token(user.raw_confirmation_token)
+
+      assert_have_selector '#error_explanation'
+      assert_contain /needs to be confirmed within 3 days/
+      assert_not user.reload.confirmed?
+      assert_current_url "/users/confirmation?confirmation_token=#{user.raw_confirmation_token}"
+    end
+  end
+
+  test 'user with valid confirmation token where the token has expired and with application router_name set to a different engine it should raise an error' do
+    user = create_user(confirm: false, confirmation_sent_at: 4.days.ago)
+
+    swap Devise, confirm_within: 3.days, router_name: :fake_engine do
+      assert_raise ActionView::Template::Error do
+        visit_user_confirmation_with_token(user.raw_confirmation_token)
+      end
+    end
+  end
+
+  test 'user with valid confirmation token where the token has expired and with application router_name set to a different engine and route overrides back to main it shows the path' do
+    user = create_user(confirm: false, confirmation_sent_at: 4.days.ago)
+
+    swap Devise, confirm_within: 3.days, router_name: :fake_engine do
+      visit user_on_main_app_confirmation_path(confirmation_token: user.raw_confirmation_token)
+
+      assert_current_url "/user_on_main_apps/confirmation?confirmation_token=#{user.raw_confirmation_token}"
+    end
+  end
+
+  test 'user with valid confirmation token where the token has expired with router overrides different engine it shows the path' do
+    user = create_user(confirm: false, confirmation_sent_at: 4.days.ago)
+
+    swap Devise, confirm_within: 3.days do
+      visit user_on_engine_confirmation_path(confirmation_token: user.raw_confirmation_token)
+
+      assert_current_url "/user_on_engines/confirmation?confirmation_token=#{user.raw_confirmation_token}"
+    end
+  end
+
+  test 'user with valid confirmation token should be able to confirm an account before the token has expired' do
+    swap Devise, confirm_within: 3.days do
+      user = create_user(confirm: false, confirmation_sent_at: 2.days.ago)
+      assert_not user.confirmed?
+      visit_user_confirmation_with_token(user.raw_confirmation_token)
+
+      assert_contain 'Your email address has been successfully confirmed.'
+      assert_current_url '/users/sign_in'
+      assert user.reload.confirmed?
+    end
+  end
+
+  test 'user should be redirected to a custom path after confirmation' do
+    Devise::ConfirmationsController.any_instance.stubs(:after_confirmation_path_for).returns("/?custom=1")
+
+    user = create_user(confirm: false)
+    visit_user_confirmation_with_token(user.raw_confirmation_token)
+
+    assert_current_url "/?custom=1"
+  end
+
+  test 'already confirmed user should not be able to confirm the account again' do
+    user = create_user(confirm: false)
+    user.confirmed_at = Time.now
+    user.save
+    visit_user_confirmation_with_token(user.raw_confirmation_token)
+
+    assert_have_selector '#error_explanation'
+    assert_contain 'already confirmed'
+  end
+
+  test 'already confirmed user should not be able to confirm the account again neither request confirmation' do
+    user = create_user(confirm: false)
+    user.confirmed_at = Time.now
+    user.save
+
+    visit_user_confirmation_with_token(user.raw_confirmation_token)
+    assert_contain 'already confirmed'
+
+    fill_in 'email', with: user.email
+    click_button 'Resend confirmation instructions'
+    assert_contain 'already confirmed'
+  end
+
+  test 'not confirmed user with setup to block without confirmation should not be able to sign in' do
+    swap Devise, allow_unconfirmed_access_for: 0.days do
+      sign_in_as_user(confirm: false)
+
+      assert_contain 'You have to confirm your email address before continuing'
+      assert_not warden.authenticated?(:user)
+    end
+  end
+
+  test 'not confirmed user should not see confirmation message if invalid credentials are given' do
+    swap Devise, allow_unconfirmed_access_for: 0.days do
+      sign_in_as_user(confirm: false) do
+        fill_in 'password', with: 'invalid'
+      end
+
+      assert_contain 'Invalid email or password'
+      assert_not warden.authenticated?(:user)
+    end
+  end
+
+  test 'not confirmed user but configured with some days to confirm should be able to sign in' do
+    swap Devise, allow_unconfirmed_access_for: 1.day do
+      sign_in_as_user(confirm: false)
+
+      assert_response :success
+      assert warden.authenticated?(:user)
+    end
+  end
+
+  test 'unconfirmed but signed in user should be redirected to their root path' do
+    swap Devise, allow_unconfirmed_access_for: 1.day do
+      user = sign_in_as_user(confirm: false)
+
+      visit_user_confirmation_with_token(user.raw_confirmation_token)
+      assert_contain 'Your email address has been successfully confirmed.'
+      assert_current_url '/'
+    end
+  end
+
+  test 'user should be redirected to sign in page whenever signed in as another resource at same session already' do
+    sign_in_as_admin
+
+    user = create_user(confirm: false)
+    visit_user_confirmation_with_token(user.raw_confirmation_token)
+
+    assert_current_url '/users/sign_in'
+  end
+
+  test 'error message is configurable by resource name' do
+    store_translations :en, devise: {
+      failure: { user: { unconfirmed: "Not confirmed user" } }
+    } do
+      sign_in_as_user(confirm: false)
+      assert_contain 'Not confirmed user'
+    end
+  end
+
+  test 'resent confirmation token with valid E-Mail in XML format should return valid response' do
+    user = create_user(confirm: false)
+    post user_confirmation_path(format: 'xml'), user: { email: user.email }
+    assert_response :success
+    assert_equal response.body, {}.to_xml
+  end
+
+  test 'resent confirmation token with invalid E-Mail in XML format should return invalid response' do
+    create_user(confirm: false)
+    post user_confirmation_path(format: 'xml'), user: { email: 'invalid.test at test.com' }
+    assert_response :unprocessable_entity
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>)
+  end
+
+  test 'confirm account with valid confirmation token in XML format should return valid response' do
+    user = create_user(confirm: false)
+    get user_confirmation_path(confirmation_token: user.raw_confirmation_token, format: 'xml')
+    assert_response :success
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<user>)
+  end
+
+  test 'confirm account with invalid confirmation token in XML format should return invalid response' do
+    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>)
+  end
+
+  test 'request an account confirmation account with JSON, should return an empty JSON' do
+    user = create_user(confirm: false)
+
+    post user_confirmation_path, user: { email: user.email }, format: :json
+    assert_response :success
+    assert_equal response.body, {}.to_json
+  end
+
+  test "when in paranoid mode and with a valid e-mail, should not say that the e-mail is valid" do
+    swap Devise, paranoid: true do
+      user = create_user(confirm: false)
+      visit new_user_session_path
+
+      click_link "Didn't receive confirmation instructions?"
+      fill_in 'email', with: user.email
+      click_button 'Resend confirmation instructions'
+
+      assert_contain "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes."
+      assert_current_url "/users/sign_in"
+    end
+  end
+
+  test "when in paranoid mode and with a invalid e-mail, should not say that the e-mail is invalid" do
+    swap Devise, paranoid: true do
+      visit new_user_session_path
+
+      click_link "Didn't receive confirmation instructions?"
+      fill_in 'email', with: "idonthavethisemail at gmail.com"
+      click_button 'Resend confirmation instructions'
+
+      assert_not_contain "1 error prohibited this user from being saved:"
+      assert_not_contain "Email not found"
+
+      assert_contain "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes."
+      assert_current_url "/users/sign_in"
+    end
+  end
+end
+
+class ConfirmationOnChangeTest < ActionDispatch::IntegrationTest
+  def create_second_admin(options={})
+    @admin = nil
+    create_admin(options)
+  end
+
+  def visit_admin_confirmation_with_token(confirmation_token)
+    visit admin_confirmation_path(confirmation_token: confirmation_token)
+  end
+
+  test 'admin should be able to request a new confirmation after email changed' do
+    admin = create_admin
+    admin.update_attributes(email: 'new_test at example.com')
+
+    visit new_admin_session_path
+    click_link "Didn't receive confirmation instructions?"
+
+    fill_in 'email', with: admin.unconfirmed_email
+    assert_difference "ActionMailer::Base.deliveries.size" do
+      click_button 'Resend confirmation instructions'
+    end
+
+    assert_current_url '/admin_area/sign_in'
+    assert_contain 'You will receive an email with instructions for how to confirm your email address in a few minutes'
+  end
+
+  test 'admin with valid confirmation token should be able to confirm email after email changed' do
+    admin = create_admin
+    admin.update_attributes(email: 'new_test at example.com')
+    assert_equal 'new_test at example.com', admin.unconfirmed_email
+    visit_admin_confirmation_with_token(admin.raw_confirmation_token)
+
+    assert_contain 'Your email address has been successfully confirmed.'
+    assert_current_url '/admin_area/sign_in'
+    assert admin.reload.confirmed?
+    assert_not admin.reload.pending_reconfirmation?
+  end
+
+  test 'admin with previously valid confirmation token should not be able to confirm email after email changed again' do
+    admin = create_admin
+    admin.update_attributes(email: 'first_test at example.com')
+    assert_equal 'first_test at example.com', admin.unconfirmed_email
+
+    raw_confirmation_token = admin.raw_confirmation_token
+    admin = Admin.find(admin.id)
+
+    admin.update_attributes(email: 'second_test at example.com')
+    assert_equal 'second_test at example.com', admin.unconfirmed_email
+
+    visit_admin_confirmation_with_token(raw_confirmation_token)
+    assert_have_selector '#error_explanation'
+    assert_contain(/Confirmation token(.*)invalid/)
+
+    visit_admin_confirmation_with_token(admin.raw_confirmation_token)
+    assert_contain 'Your email address has been successfully confirmed.'
+    assert_current_url '/admin_area/sign_in'
+    assert admin.reload.confirmed?
+    assert_not admin.reload.pending_reconfirmation?
+  end
+
+  test 'admin email should be unique also within unconfirmed_email' do
+    admin = create_admin
+    admin.update_attributes(email: 'new_admin_test at example.com')
+    assert_equal 'new_admin_test at example.com', admin.unconfirmed_email
+
+    create_second_admin(email: "new_admin_test at example.com")
+
+    visit_admin_confirmation_with_token(admin.raw_confirmation_token)
+    assert_have_selector '#error_explanation'
+    assert_contain(/Email.*already.*taken/)
+    assert admin.reload.pending_reconfirmation?
+  end
+end
diff --git a/test/integration/database_authenticatable_test.rb b/test/integration/database_authenticatable_test.rb
new file mode 100644
index 0000000..48aed2b
--- /dev/null
+++ b/test/integration/database_authenticatable_test.rb
@@ -0,0 +1,84 @@
+require 'test_helper'
+
+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 at Bar.com')
+
+    sign_in_as_user do
+      fill_in 'email', with: 'foo at bar.com'
+    end
+
+    assert warden.authenticated?(:user)
+  end
+
+  test 'sign in with email of different case should fail when email is NOT the list of case insensitive keys' do
+    swap Devise, case_insensitive_keys: [] do
+      create_user(email: 'Foo at Bar.com')
+
+      sign_in_as_user do
+        fill_in 'email', with: 'foo at bar.com'
+      end
+
+      assert_not warden.authenticated?(:user)
+    end
+  end
+
+  test 'sign in with email including extra spaces should succeed when email is in the list of strip whitespace keys' do
+    create_user(email: ' foo at bar.com ')
+
+    sign_in_as_user do
+      fill_in 'email', with: 'foo at bar.com'
+    end
+
+    assert warden.authenticated?(:user)
+  end
+
+  test 'sign in with email including extra spaces should fail when email is NOT the list of strip whitespace keys' do
+    swap Devise, strip_whitespace_keys: [] do
+      create_user(email: 'foo at bar.com')
+
+      sign_in_as_user do
+        fill_in 'email', with: ' foo at bar.com '
+      end
+
+      assert_not warden.authenticated?(:user)
+    end
+  end
+
+  test 'sign in should not authenticate if not using proper authentication keys' do
+    swap Devise, authentication_keys: [:username] do
+      sign_in_as_user
+      assert_not warden.authenticated?(:user)
+    end
+  end
+
+  test 'sign in with invalid email should return to sign in form with error message' do
+    store_translations :en, devise: { failure: { admin: { not_found_in_database: 'Invalid email address' } } } do
+      sign_in_as_admin do
+        fill_in 'email', with: 'wrongemail at test.com'
+      end
+
+      assert_contain 'Invalid email address'
+      assert_not warden.authenticated?(:admin)
+    end
+  end
+
+  test 'sign in with invalid pasword should return to sign in form with error message' do
+    sign_in_as_admin do
+      fill_in 'password', with: 'abcdef'
+    end
+
+    assert_contain 'Invalid email or password'
+    assert_not warden.authenticated?(:admin)
+  end
+
+  test 'error message is configurable by resource name' do
+    store_translations :en, devise: { failure: { admin: { invalid: "Invalid credentials" } } } do
+      sign_in_as_admin do
+        fill_in 'password', with: 'abcdef'
+      end
+
+      assert_contain 'Invalid credentials'
+    end
+  end
+end
diff --git a/test/integration/http_authenticatable_test.rb b/test/integration/http_authenticatable_test.rb
new file mode 100644
index 0000000..aad51f6
--- /dev/null
+++ b/test/integration/http_authenticatable_test.rb
@@ -0,0 +1,105 @@
+require 'test_helper'
+
+class HttpAuthenticationTest < ActionDispatch::IntegrationTest
+  test 'handles unverified requests gets rid of caches but continues signed in' do
+    swap ApplicationController, allow_forgery_protection: true do
+      create_user
+      post exhibit_user_url(1), {}, "HTTP_AUTHORIZATION" => "Basic #{Base64.encode64("user at test.com:12345678")}"
+      assert warden.authenticated?(:user)
+      assert_equal "User is authenticated", response.body
+    end
+  end
+
+  test 'sign in should authenticate with http' do
+    sign_in_as_new_user_with_http
+    assert_response 200
+    assert_match '<email>user at test.com</email>', response.body
+    assert warden.authenticated?(:user)
+
+    get users_path(format: :xml)
+    assert_response 200
+  end
+
+  test 'sign in should authenticate with http but not emit a cookie if skipping session storage' do
+    swap Devise, skip_session_storage: [:http_auth] do
+      sign_in_as_new_user_with_http
+      assert_response 200
+      assert_match '<email>user at test.com</email>', response.body
+      assert warden.authenticated?(:user)
+
+      get users_path(format: :xml)
+      assert_response 401
+    end
+  end
+
+  test 'returns a custom response with www-authenticate header on failures' do
+    sign_in_as_new_user_with_http("unknown")
+    assert_equal 401, status
+    assert_equal 'Basic realm="Application"', headers["WWW-Authenticate"]
+  end
+
+  test 'uses the request format as response content type' do
+    sign_in_as_new_user_with_http("unknown")
+    assert_equal 401, status
+    assert_equal "application/xml; charset=utf-8", headers["Content-Type"]
+    assert_match "<error>Invalid email or password.</error>", response.body
+  end
+
+  test 'returns a custom response with www-authenticate and chosen realm' do
+    swap Devise, http_authentication_realm: "MyApp" do
+      sign_in_as_new_user_with_http("unknown")
+      assert_equal 401, status
+      assert_equal 'Basic realm="MyApp"', headers["WWW-Authenticate"]
+    end
+  end
+
+  test 'sign in should authenticate with http even with specific authentication keys' do
+    swap Devise, authentication_keys: [:username] do
+      sign_in_as_new_user_with_http("usertest")
+      assert_response :success
+      assert_match '<email>user at test.com</email>', response.body
+      assert warden.authenticated?(:user)
+    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 at 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 at 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
+      assert_equal 401, status
+      assert_equal 'Basic realm="Application"', headers["WWW-Authenticate"]
+    end
+  end
+
+  private
+
+    def sign_in_as_new_user_with_http(username="user at test.com", password="12345678")
+      user = create_user
+      get users_path(format: :xml), {}, "HTTP_AUTHORIZATION" => "Basic #{Base64.encode64("#{username}:#{password}")}"
+      user
+    end
+
+    # Sign in with oauth2 token. This is just to test that it isn't misinterpreted as basic authentication
+    def add_oauth2_header
+      user = create_user
+      get users_path(format: :xml), {}, "HTTP_AUTHORIZATION" => "OAuth #{Base64.encode64("#{user.email}:12345678")}"
+    end
+
+end
diff --git a/test/integration/lockable_test.rb b/test/integration/lockable_test.rb
new file mode 100644
index 0000000..0c8c4a7
--- /dev/null
+++ b/test/integration/lockable_test.rb
@@ -0,0 +1,239 @@
+require 'test_helper'
+
+class LockTest < ActionDispatch::IntegrationTest
+
+  def visit_user_unlock_with_token(unlock_token)
+    visit user_unlock_path(unlock_token: unlock_token)
+  end
+
+  def send_unlock_request
+    user = create_user(locked: true)
+    ActionMailer::Base.deliveries.clear
+
+    visit new_user_session_path
+    click_link "Didn't receive unlock instructions?"
+
+    Devise.stubs(:friendly_token).returns("abcdef")
+    fill_in 'email', with: user.email
+    click_button 'Resend unlock instructions'
+  end
+
+  test 'user should be able to request a new unlock token' do
+    send_unlock_request
+
+    assert_template 'sessions/new'
+    assert_contain 'You will receive an email with instructions for how to unlock your account in a few minutes'
+
+    mail = ActionMailer::Base.deliveries.last
+    assert_equal 1, ActionMailer::Base.deliveries.size
+    assert_equal ['please-change-me at config-initializers-devise.com'], mail.from
+    assert_match user_unlock_path(unlock_token: 'abcdef'), mail.body.encoded
+  end
+
+  test 'user should receive the instructions from a custom mailer' do
+    User.any_instance.stubs(:devise_mailer).returns(Users::Mailer)
+
+    send_unlock_request
+
+    assert_equal ['custom at example.com'], ActionMailer::Base.deliveries.first.from
+  end
+
+  test 'unlocked user should not be able to request a unlock token' do
+    user = create_user(locked: false)
+    ActionMailer::Base.deliveries.clear
+
+    visit new_user_session_path
+    click_link "Didn't receive unlock instructions?"
+
+    fill_in 'email', with: user.email
+    click_button 'Resend unlock instructions'
+
+    assert_template 'unlocks/new'
+    assert_contain 'not locked'
+    assert_equal 0, ActionMailer::Base.deliveries.size
+  end
+
+  test 'unlocked pages should not be available if email strategy is disabled' do
+    visit "/admin_area/sign_in"
+
+    assert_raise Webrat::NotFoundError do
+      click_link "Didn't receive unlock instructions?"
+    end
+
+    assert_raise NameError do
+      visit new_admin_unlock_path
+    end
+
+    assert_raise ActionController::RoutingError do
+      visit "/admin_area/unlock/new"
+    end
+  end
+
+  test 'user with invalid unlock token should not be able to unlock an account' do
+    visit_user_unlock_with_token('invalid_token')
+
+    assert_response :success
+    assert_current_url '/users/unlock?unlock_token=invalid_token'
+    assert_have_selector '#error_explanation'
+    assert_contain /Unlock token(.*)invalid/
+  end
+
+  test "locked user should be able to unlock account" do
+    user = create_user
+    raw  = user.lock_access!
+    visit_user_unlock_with_token(raw)
+
+    assert_current_url "/users/sign_in"
+    assert_contain 'Your account has been unlocked successfully. Please sign in to continue.'
+    assert_not user.reload.access_locked?
+  end
+
+  test "user should not send a new e-mail if already locked" do
+    user = create_user(locked: true)
+    user.failed_attempts = User.maximum_attempts + 1
+    user.save!
+
+    ActionMailer::Base.deliveries.clear
+
+    sign_in_as_user(password: "invalid")
+    assert_contain 'Your account is locked.'
+    assert ActionMailer::Base.deliveries.empty?
+  end
+
+  test 'error message is configurable by resource name' do
+    store_translations :en, devise: {
+        failure: {user: {locked: "You are locked!"}}
+    } do
+
+      user = create_user(locked: true)
+      user.failed_attempts = User.maximum_attempts + 1
+      user.save!
+
+      sign_in_as_user(password: "invalid")
+      assert_contain "You are locked!"
+    end
+  end
+
+  test "user should not be able to sign in when locked" do
+    store_translations :en, devise: {
+        failure: {user: {locked: "You are locked!"}}
+    } do
+
+      user = create_user(locked: true)
+      user.failed_attempts = User.maximum_attempts + 1
+      user.save!
+
+      sign_in_as_user(password: "123456")
+      assert_contain "You are locked!"
+    end
+  end
+
+  test 'user should be able to request a new unlock token via XML request' do
+    user = create_user(locked: true)
+    ActionMailer::Base.deliveries.clear
+
+    post user_unlock_path(format: 'xml'), user: {email: user.email}
+    assert_response :success
+    assert_equal response.body, {}.to_xml
+    assert_equal 1, ActionMailer::Base.deliveries.size
+  end
+
+  test 'unlocked user should not be able to request a unlock token via XML request' do
+    user = create_user(locked: false)
+    ActionMailer::Base.deliveries.clear
+
+    post user_unlock_path(format: 'xml'), user: {email: user.email}
+    assert_response :unprocessable_entity
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>)
+    assert_equal 0, ActionMailer::Base.deliveries.size
+  end
+
+  test 'user with valid unlock token should be able to unlock account via XML request' do
+    user = create_user()
+    raw  = user.lock_access!
+    assert user.access_locked?
+    get user_unlock_path(format: 'xml', unlock_token: raw)
+    assert_response :success
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<user>)
+  end
+
+
+  test 'user with invalid unlock token should not be able to unlock the account via XML request' do
+    get user_unlock_path(format: 'xml', unlock_token: 'invalid_token')
+    assert_response :unprocessable_entity
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>)
+  end
+
+  test "when using json to ask a unlock request, should not return the user" do
+    user = create_user(locked: true)
+    post user_unlock_path(format: "json", user: {email: user.email})
+    assert_response :success
+    assert_equal response.body, {}.to_json
+  end
+
+  test "in paranoid mode, when trying to unlock an user that exists it should not say that it exists if it is locked" do
+    swap Devise, paranoid: true do
+      user = create_user(locked: true)
+
+      visit new_user_session_path
+      click_link "Didn't receive unlock instructions?"
+
+      fill_in 'email', with: user.email
+      click_button 'Resend unlock instructions'
+
+      assert_current_url "/users/sign_in"
+      assert_contain "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes."
+    end
+  end
+
+  test "in paranoid mode, when trying to unlock an user that exists it should not say that it exists if it is not locked" do
+    swap Devise, paranoid: true do
+      user = create_user(locked: false)
+
+      visit new_user_session_path
+      click_link "Didn't receive unlock instructions?"
+
+      fill_in 'email', with: user.email
+      click_button 'Resend unlock instructions'
+
+      assert_current_url "/users/sign_in"
+      assert_contain "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes."
+    end
+  end
+
+  test "in paranoid mode, when trying to unlock an user that does not exists it should not say that it does not exists" do
+    swap Devise, paranoid: true do
+      visit new_user_session_path
+      click_link "Didn't receive unlock instructions?"
+
+      fill_in 'email', with: "arandomemail at hotmail.com"
+      click_button 'Resend unlock instructions'
+
+      assert_not_contain "1 error prohibited this user from being saved:"
+      assert_not_contain "Email not found"
+      assert_current_url "/users/sign_in"
+
+      assert_contain "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes."
+
+    end
+  end
+
+  test "in paranoid mode, when locking a user that exists it should not say that the user was locked" do
+    swap Devise, paranoid: true, maximum_attempts: 1 do
+      user = create_user(locked: false)
+
+      visit new_user_session_path
+      fill_in 'email', with: user.email
+      fill_in 'password', with: "abadpassword"
+      click_button 'Log in'
+
+      fill_in 'email', with: user.email
+      fill_in 'password', with: "abadpassword"
+      click_button 'Log in'
+
+      assert_current_url "/users/sign_in"
+      assert_not_contain "locked"
+    end
+  end
+
+end
diff --git a/test/integration/omniauthable_test.rb b/test/integration/omniauthable_test.rb
new file mode 100644
index 0000000..f131d15
--- /dev/null
+++ b/test/integration/omniauthable_test.rb
@@ -0,0 +1,133 @@
+require 'test_helper'
+
+
+class OmniauthableIntegrationTest < ActionDispatch::IntegrationTest
+  FACEBOOK_INFO = {
+    "id" => '12345',
+    "link" => 'http://facebook.com/josevalim',
+    "email" => 'user at example.com',
+    "first_name" => 'Jose',
+    "last_name" => 'Valim',
+    "website" => 'http://blog.plataformatec.com.br'
+  }
+
+  setup do
+    OmniAuth.config.test_mode = true
+    OmniAuth.config.mock_auth[:facebook] = {
+      "uid" => '12345',
+      "provider" => 'facebook',
+      "user_info" => {"nickname" => 'josevalim'},
+      "credentials" => {"token" => 'plataformatec'},
+      "extra" => {"user_hash" => FACEBOOK_INFO}
+    }
+  end
+
+  teardown do
+    OmniAuth.config.test_mode = false
+  end
+
+  def stub_action!(name)
+    Users::OmniauthCallbacksController.class_eval do
+      alias_method :__old_facebook, :facebook
+      alias_method :facebook, name
+    end
+    yield
+  ensure
+    Users::OmniauthCallbacksController.class_eval do
+      alias_method :facebook, :__old_facebook
+    end
+  end
+
+  test "can access omniauth.auth in the env hash" do
+    visit "/users/sign_in"
+    click_link "Sign in with Facebook"
+
+    json = ActiveSupport::JSON.decode(response.body)
+
+    assert_equal "12345",         json["uid"]
+    assert_equal "facebook",      json["provider"]
+    assert_equal "josevalim",     json["user_info"]["nickname"]
+    assert_equal FACEBOOK_INFO,   json["extra"]["user_hash"]
+    assert_equal "plataformatec", json["credentials"]["token"]
+  end
+
+  test "cleans up session on sign up" do
+    assert_no_difference "User.count" do
+      visit "/users/sign_in"
+      click_link "Sign in with Facebook"
+    end
+
+    assert session["devise.facebook_data"]
+
+    assert_difference "User.count" do
+      visit "/users/sign_up"
+      fill_in "Password", with: "12345678"
+      fill_in "Password confirmation", with: "12345678"
+      click_button "Sign up"
+    end
+
+    assert_current_url "/"
+    assert_contain "You have signed up successfully."
+    assert_contain "Hello User user at example.com"
+    assert_not session["devise.facebook_data"]
+  end
+
+  test "cleans up session on cancel" do
+    assert_no_difference "User.count" do
+      visit "/users/sign_in"
+      click_link "Sign in with Facebook"
+    end
+
+    assert session["devise.facebook_data"]
+    visit "/users/cancel"
+    assert !session["devise.facebook_data"]
+  end
+
+  test "cleans up session on sign in" do
+    assert_no_difference "User.count" do
+      visit "/users/sign_in"
+      click_link "Sign in with Facebook"
+    end
+
+    assert session["devise.facebook_data"]
+    sign_in_as_user
+    assert !session["devise.facebook_data"]
+  end
+
+  test "sign in and send remember token if configured" do
+    visit "/users/sign_in"
+    click_link "Sign in with Facebook"
+    assert_nil warden.cookies["remember_user_token"]
+
+    stub_action!(:sign_in_facebook) do
+      create_user
+      visit "/users/sign_in"
+      click_link "Sign in with Facebook"
+      assert warden.authenticated?(:user)
+      assert warden.cookies["remember_user_token"]
+    end
+  end
+
+  test "generates a proper link when SCRIPT_NAME is set" do
+    header 'SCRIPT_NAME', '/q'
+    visit "/users/sign_in"
+    assert_select "a", href: "/q/users/auth/facebook"
+  end
+
+  test "handles callback error parameter according to the specification" do
+    OmniAuth.config.mock_auth[:facebook] = :access_denied
+    visit "/users/auth/facebook/callback?error=access_denied"
+    assert_current_url "/users/sign_in"
+    assert_contain 'Could not authenticate you from Facebook because "Access denied".'
+  end
+
+  test "handles other exceptions from omniauth" do
+    OmniAuth.config.mock_auth[:facebook] = :invalid_credentials
+
+    visit "/users/sign_in"
+    click_link "Sign in with Facebook"
+
+    assert_current_url "/users/sign_in"
+    assert_contain 'Could not authenticate you from Facebook because "Invalid credentials".'
+  end
+end
diff --git a/test/integration/recoverable_test.rb b/test/integration/recoverable_test.rb
new file mode 100644
index 0000000..004748e
--- /dev/null
+++ b/test/integration/recoverable_test.rb
@@ -0,0 +1,334 @@
+require 'test_helper'
+
+class PasswordTest < ActionDispatch::IntegrationTest
+
+  def visit_new_password_path
+    visit new_user_session_path
+    click_link 'Forgot your password?'
+  end
+
+  def request_forgot_password(&block)
+    visit_new_password_path
+    assert_response :success
+    assert_not warden.authenticated?(:user)
+
+    fill_in 'email', with: 'user at test.com'
+    yield if block_given?
+
+    Devise.stubs(:friendly_token).returns("abcdef")
+    click_button 'Send me reset password instructions'
+  end
+
+  def reset_password(options={}, &block)
+    unless options[:visit] == false
+      visit edit_user_password_path(reset_password_token: options[:reset_password_token] || "abcdef")
+      assert_response :success
+    end
+
+    fill_in 'New password', with: '987654321'
+    fill_in 'Confirm new password', with: '987654321'
+    yield if block_given?
+    click_button 'Change my password'
+  end
+
+  test 'reset password with email of different case should succeed when email is in the list of case insensitive keys' do
+    create_user(email: 'Foo at Bar.com')
+
+    request_forgot_password do
+      fill_in 'email', with: 'foo at bar.com'
+    end
+
+    assert_current_url '/users/sign_in'
+    assert_contain 'You will receive an email with instructions on how to reset your password in a few minutes.'
+  end
+
+  test 'reset password with email should send an email from a custom mailer' do
+    create_user(email: 'Foo at Bar.com')
+
+    User.any_instance.stubs(:devise_mailer).returns(Users::Mailer)
+    request_forgot_password do
+      fill_in 'email', with: 'foo at bar.com'
+    end
+
+    mail = ActionMailer::Base.deliveries.last
+    assert_equal ['custom at example.com'], mail.from
+    assert_match edit_user_password_path(reset_password_token: 'abcdef'), mail.body.encoded
+  end
+
+  test 'reset password with email of different case should fail when email is NOT the list of case insensitive keys' do
+    swap Devise, case_insensitive_keys: [] do
+      create_user(email: 'Foo at Bar.com')
+
+      request_forgot_password do
+        fill_in 'email', with: 'foo at bar.com'
+      end
+
+      assert_response :success
+      assert_current_url '/users/password'
+      assert_have_selector "input[type=email][value='foo at bar.com']"
+      assert_contain 'not found'
+    end
+  end
+
+  test 'reset password with email with extra whitespace should succeed when email is in the list of strip whitespace keys' do
+    create_user(email: 'foo at bar.com')
+
+    request_forgot_password do
+      fill_in 'email', with: ' foo at bar.com '
+    end
+
+    assert_current_url '/users/sign_in'
+    assert_contain 'You will receive an email with instructions on how to reset your password in a few minutes.'
+  end
+
+  test 'reset password with email with extra whitespace should fail when email is NOT the list of strip whitespace keys' do
+    swap Devise, strip_whitespace_keys: [] do
+      create_user(email: 'foo at bar.com')
+
+      request_forgot_password do
+        fill_in 'email', with: ' foo at bar.com '
+      end
+
+      assert_response :success
+      assert_current_url '/users/password'
+      assert_have_selector "input[type=email][value=' foo at bar.com ']"
+      assert_contain 'not found'
+    end
+  end
+
+  test 'authenticated user should not be able to visit forgot password page' do
+    sign_in_as_user
+    assert warden.authenticated?(:user)
+
+    get new_user_password_path
+
+    assert_response :redirect
+    assert_redirected_to root_path
+  end
+
+  test 'not authenticated user should be able to request a forgot password' do
+    create_user
+    request_forgot_password
+
+    assert_current_url '/users/sign_in'
+    assert_contain 'You will receive an email with instructions on how to reset your password in a few minutes.'
+  end
+
+  test 'not authenticated user with invalid email should receive an error message' do
+    request_forgot_password do
+      fill_in 'email', with: 'invalid.test at test.com'
+    end
+
+    assert_response :success
+    assert_current_url '/users/password'
+    assert_have_selector "input[type=email][value='invalid.test at test.com']"
+    assert_contain 'not found'
+  end
+
+  test 'authenticated user should not be able to visit edit password page' do
+    sign_in_as_user
+    get edit_user_password_path
+    assert_response :redirect
+    assert_redirected_to root_path
+    assert warden.authenticated?(:user)
+  end
+
+  test 'not authenticated user without a reset password token should not be able to visit the page' do
+    get edit_user_password_path
+    assert_response :redirect
+    assert_redirected_to "/users/sign_in"
+  end
+
+  test 'not authenticated user with invalid reset password token should not be able to change their password' do
+    user = create_user
+    reset_password reset_password_token: 'invalid_reset_password'
+
+    assert_response :success
+    assert_current_url '/users/password'
+    assert_have_selector '#error_explanation'
+    assert_contain /Reset password token(.*)invalid/
+    assert_not user.reload.valid_password?('987654321')
+  end
+
+  test 'not authenticated user with valid reset password token but invalid password should not be able to change their password' do
+    user = create_user
+    request_forgot_password
+    reset_password do
+      fill_in 'Confirm new password', with: 'other_password'
+    end
+
+    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_not user.reload.valid_password?('987654321')
+  end
+
+  test 'not authenticated user with valid data should be able to change their password' do
+    user = create_user
+    request_forgot_password
+    reset_password
+
+    assert_current_url '/'
+    assert_contain 'Your password has been changed successfully. You are now signed in.'
+    assert user.reload.valid_password?('987654321')
+  end
+
+  test 'after entering invalid data user should still be able to change their password' do
+    user = create_user
+    request_forgot_password
+
+    reset_password {  fill_in 'Confirm new password', with: 'other_password' }
+    assert_response :success
+    assert_have_selector '#error_explanation'
+    assert_not user.reload.valid_password?('987654321')
+
+    reset_password visit: false
+    assert_contain 'Your password has been changed successfully.'
+    assert user.reload.valid_password?('987654321')
+  end
+
+  test 'sign in user automatically after changing its password' do
+    create_user
+    request_forgot_password
+    reset_password
+
+    assert warden.authenticated?(:user)
+  end
+
+  test 'does not sign in user automatically after changing its password if it\'s locked and unlock strategy is :none or :time' do
+    [:none, :time].each do |strategy|
+      swap Devise, unlock_strategy: strategy do
+        user = create_user(locked: true)
+        request_forgot_password
+        reset_password
+
+        assert_contain 'Your password has been changed successfully.'
+        assert_not_contain 'You are now signed in.'
+        assert_equal new_user_session_path, @request.path
+        assert !warden.authenticated?(:user)
+      end
+    end
+  end
+
+  test 'unlocks and signs in locked user automatically after changing it\'s password if unlock strategy is :email' do
+    swap Devise, unlock_strategy: :email do
+      user = create_user(locked: true)
+      request_forgot_password
+      reset_password
+
+      assert_contain 'Your password has been changed successfully.'
+      assert !user.reload.access_locked?
+      assert warden.authenticated?(:user)
+    end
+  end
+
+  test 'unlocks and signs in locked user automatically after changing it\'s password if unlock strategy is :both' do
+    swap Devise, unlock_strategy: :both do
+      user = create_user(locked: true)
+      request_forgot_password
+      reset_password
+
+      assert_contain 'Your password has been changed successfully.'
+      assert !user.reload.access_locked?
+      assert warden.authenticated?(:user)
+    end
+  end
+
+  test 'reset password request with valid E-Mail in XML format should return valid response' do
+    create_user
+    post user_password_path(format: 'xml'), user: {email: "user at test.com"}
+    assert_response :success
+    assert_equal response.body, { }.to_xml
+  end
+
+  test 'reset password request with invalid E-Mail in XML format should return valid response' do
+    create_user
+    post user_password_path(format: 'xml'), user: {email: "invalid.test at test.com"}
+    assert_response :unprocessable_entity
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>)
+  end
+
+  test 'reset password request with invalid E-Mail in XML format should return empty and valid response' do
+    swap Devise, paranoid: true do
+      create_user
+      post user_password_path(format: 'xml'), user: {email: "invalid at test.com"}
+      assert_response :success
+      assert_equal response.body, { }.to_xml
+    end
+  end
+
+  test 'change password with valid parameters in XML format should return valid response' do
+    create_user
+    request_forgot_password
+    put user_password_path(format: 'xml'), user: {
+      reset_password_token: 'abcdef', password: '987654321', password_confirmation: '987654321'
+    }
+    assert_response :success
+    assert warden.authenticated?(:user)
+  end
+
+  test 'change password with invalid token in XML format should return invalid response' do
+    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
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>)
+  end
+
+  test 'change password with invalid new password in XML format should return invalid response' do
+    user = create_user
+    request_forgot_password
+    put user_password_path(format: 'xml'), user: {reset_password_token: user.reload.reset_password_token, password: '', password_confirmation: '987654321'}
+    assert_response :unprocessable_entity
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>)
+  end
+
+  test "when using json requests to ask a confirmable request, should not return the object" do
+    user = create_user(confirm: false)
+
+    post user_password_path(format: :json), user: { email: user.email }
+
+    assert_response :success
+    assert_equal response.body, "{}"
+  end
+
+  test "when in paranoid mode and with an invalid e-mail, asking to reset a password should display a message that does not indicates that the e-mail does not exists in the database" do
+    swap Devise, paranoid: true do
+      visit_new_password_path
+      fill_in "email", with: "arandomemail at test.com"
+      click_button 'Send me reset password instructions'
+
+      assert_not_contain "1 error prohibited this user from being saved:"
+      assert_not_contain "Email not found"
+      assert_contain "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes."
+      assert_current_url "/users/sign_in"
+    end
+  end
+
+  test "when in paranoid mode and with a valid e-mail, asking to reset password should display a message that does not indicates that the email exists in the database and redirect to the failure route" do
+    swap Devise, paranoid: true do
+      user = create_user
+      visit_new_password_path
+      fill_in 'email', with: user.email
+      click_button 'Send me reset password instructions'
+
+      assert_contain "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes."
+      assert_current_url "/users/sign_in"
+    end
+  end
+
+  test "after recovering a password, should set failed attempts to 0" do
+    user = create_user
+    user.update_attribute(:failed_attempts, 10)
+
+    assert_equal 10, user.failed_attempts
+    request_forgot_password
+    reset_password
+
+    assert warden.authenticated?(:user)
+    user.reload
+    assert_equal 0, user.failed_attempts
+  end
+end
diff --git a/test/integration/registerable_test.rb b/test/integration/registerable_test.rb
new file mode 100644
index 0000000..162ab31
--- /dev/null
+++ b/test/integration/registerable_test.rb
@@ -0,0 +1,359 @@
+require 'test_helper'
+
+class RegistrationTest < ActionDispatch::IntegrationTest
+
+  test 'a guest admin should be able to sign in successfully' do
+    get new_admin_session_path
+    click_link 'Sign up'
+
+    assert_template 'registrations/new'
+
+    fill_in 'email', with: 'new_user at test.com'
+    fill_in 'password', with: 'new_user123'
+    fill_in 'password confirmation', with: 'new_user123'
+    click_button 'Sign up'
+
+    assert_contain 'You have signed up successfully'
+    assert warden.authenticated?(:admin)
+    assert_current_url "/admin_area/home"
+
+    admin = Admin.to_adapter.find_first(order: [:id, :desc])
+    assert_equal admin.email, 'new_user at test.com'
+  end
+
+  test 'a guest admin should be able to sign in and be redirected to a custom location' do
+    Devise::RegistrationsController.any_instance.stubs(:after_sign_up_path_for).returns("/?custom=1")
+    get new_admin_session_path
+    click_link 'Sign up'
+
+    fill_in 'email', with: 'new_user at test.com'
+    fill_in 'password', with: 'new_user123'
+    fill_in 'password confirmation', with: 'new_user123'
+    click_button 'Sign up'
+
+    assert_contain 'Welcome! You have signed up successfully.'
+    assert warden.authenticated?(:admin)
+    assert_current_url "/?custom=1"
+  end
+
+  test 'a guest admin should not see a warning about minimum password length' do
+    get new_admin_session_path
+    assert_not_contain 'characters minimum'
+  end
+
+  def user_sign_up
+    ActionMailer::Base.deliveries.clear
+
+    get new_user_registration_path
+
+    fill_in 'email', with: 'new_user at test.com'
+    fill_in 'password', with: 'new_user123'
+    fill_in 'password confirmation', with: 'new_user123'
+    click_button 'Sign up'
+  end
+
+  test 'a guest user should see a warning about minimum password length' do
+    get new_user_registration_path
+    assert_contain '7 characters minimum'
+  end
+
+  test 'a guest user should be able to sign up successfully and be blocked by confirmation' do
+    user_sign_up
+
+    assert_contain 'A message with a confirmation link has been sent to your email address. Please follow the link to activate your account.'
+    assert_not_contain 'You have to confirm your account before continuing'
+    assert_current_url "/"
+
+    assert_not warden.authenticated?(:user)
+
+    user = User.to_adapter.find_first(order: [:id, :desc])
+    assert_equal user.email, 'new_user at test.com'
+    assert_not user.confirmed?
+  end
+
+  test 'a guest user should receive the confirmation instructions from the default mailer' do
+    user_sign_up
+    assert_equal ['please-change-me at config-initializers-devise.com'], ActionMailer::Base.deliveries.first.from
+  end
+
+  test 'a guest user should receive the confirmation instructions from a custom mailer' do
+    User.any_instance.stubs(:devise_mailer).returns(Users::Mailer)
+    user_sign_up
+    assert_equal ['custom at example.com'], ActionMailer::Base.deliveries.first.from
+  end
+
+  test 'a guest user should be blocked by confirmation and redirected to a custom path' do
+    Devise::RegistrationsController.any_instance.stubs(:after_inactive_sign_up_path_for).returns("/?custom=1")
+    get new_user_registration_path
+
+    fill_in 'email', with: 'new_user at test.com'
+    fill_in 'password', with: 'new_user123'
+    fill_in 'password confirmation', with: 'new_user123'
+    click_button 'Sign up'
+
+    assert_current_url "/?custom=1"
+    assert_not warden.authenticated?(:user)
+  end
+
+  test 'a guest user cannot sign up with invalid information' do
+    # Dirty tracking behavior prevents email validations from being applied:
+    #    https://github.com/mongoid/mongoid/issues/756
+    (pending "Fails on Mongoid < 2.1"; break) if defined?(Mongoid) && Mongoid::VERSION.to_f < 2.1
+
+    get new_user_registration_path
+
+    fill_in 'email', with: 'invalid_email'
+    fill_in 'password', with: 'new_user123'
+    fill_in 'password confirmation', with: 'new_user321'
+    click_button 'Sign up'
+
+    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 "2 errors prohibited"
+    assert_nil User.to_adapter.find_first
+
+    assert_not warden.authenticated?(:user)
+  end
+
+  test 'a guest should not sign up with email/password that already exists' do
+    # Dirty tracking behavior prevents email validations from being applied:
+    #    https://github.com/mongoid/mongoid/issues/756
+    (pending "Fails on Mongoid < 2.1"; break) if defined?(Mongoid) && Mongoid::VERSION.to_f < 2.1
+
+    create_user
+    get new_user_registration_path
+
+    fill_in 'email', with: 'user at test.com'
+    fill_in 'password', with: '123456'
+    fill_in 'password confirmation', with: '123456'
+    click_button 'Sign up'
+
+    assert_current_url '/users'
+    assert_contain(/Email.*already.*taken/)
+
+    assert_not warden.authenticated?(:user)
+  end
+
+  test 'a guest should not be able to change account' do
+    get edit_user_registration_path
+    assert_redirected_to new_user_session_path
+    follow_redirect!
+    assert_contain 'You need to sign in or sign up before continuing.'
+  end
+
+  test 'a signed in user should not be able to access sign up' do
+    sign_in_as_user
+    get new_user_registration_path
+    assert_redirected_to root_path
+  end
+
+  test 'a signed in user should be able to edit their account' do
+    sign_in_as_user
+    get edit_user_registration_path
+
+    fill_in 'email', with: 'user.new at example.com'
+    fill_in 'current password', with: '12345678'
+    click_button 'Update'
+
+    assert_current_url '/'
+    assert_contain 'Your account has been updated successfully.'
+
+    assert_equal "user.new at example.com", User.to_adapter.find_first.email
+  end
+
+  test 'a signed in user should still be able to use the website after changing their password' do
+    sign_in_as_user
+    get edit_user_registration_path
+
+    fill_in 'password', with: '1234567890'
+    fill_in 'password confirmation', with: '1234567890'
+    fill_in 'current password', with: '12345678'
+    click_button 'Update'
+
+    assert_contain 'Your account has been updated successfully.'
+    get users_path
+    assert warden.authenticated?(:user)
+  end
+
+  test 'a signed in user should not change their current user with invalid password' do
+    sign_in_as_user
+    get edit_user_registration_path
+
+    fill_in 'email', with: 'user.new at example.com'
+    fill_in 'current password', with: 'invalid'
+    click_button 'Update'
+
+    assert_template 'registrations/edit'
+    assert_contain 'user at test.com'
+    assert_have_selector 'form input[value="user.new at example.com"]'
+
+    assert_equal "user at test.com", User.to_adapter.find_first.email
+  end
+
+  test 'a signed in user should be able to edit their password' do
+    sign_in_as_user
+    get edit_user_registration_path
+
+    fill_in 'password', with: 'pass1234'
+    fill_in 'password confirmation', with: 'pass1234'
+    fill_in 'current password', with: '12345678'
+    click_button 'Update'
+
+    assert_current_url '/'
+    assert_contain 'Your account has been updated successfully.'
+
+    assert User.to_adapter.find_first.valid_password?('pass1234')
+  end
+
+  test 'a signed in user should not be able to edit their password with invalid confirmation' do
+    sign_in_as_user
+    get edit_user_registration_path
+
+    fill_in 'password', with: 'pas123'
+    fill_in 'password confirmation', with: ''
+    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_not User.to_adapter.find_first.valid_password?('pas123')
+  end
+
+  test 'a signed in user should be able to cancel their account' do
+    sign_in_as_user
+    get edit_user_registration_path
+
+    click_button "Cancel my account"
+    assert_contain "Bye! Your account has been successfully cancelled. We hope to see you again soon."
+
+    assert User.to_adapter.find_all.empty?
+  end
+
+  test 'a user should be able to cancel sign up by deleting data in the session' do
+    get "/set"
+    assert_equal "something", @request.session["devise.foo_bar"]
+
+    get "/users/sign_up"
+    assert_equal "something", @request.session["devise.foo_bar"]
+
+    get "/users/cancel"
+    assert_nil @request.session["devise.foo_bar"]
+    assert_redirected_to new_user_registration_path
+  end
+
+  test 'a user with XML sign up stub' do
+    get new_user_registration_path(format: 'xml')
+    assert_response :success
+    assert_match %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<user>), response.body
+    assert_no_match(/<confirmation-token/, response.body)
+  end
+
+  test 'a user with JSON sign up stub' do
+    get new_user_registration_path(format: 'json')
+    assert_response :success
+    assert_match %({"user":), response.body
+    assert_no_match(/"confirmation_token"/, response.body)
+  end
+
+  test 'an admin sign up with valid information in XML format should return valid response' do
+    post admin_registration_path(format: 'xml'), admin: { email: 'new_user at test.com', password: 'new_user123', password_confirmation: 'new_user123' }
+    assert_response :success
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<admin>)
+
+    admin = Admin.to_adapter.find_first(order: [:id, :desc])
+    assert_equal admin.email, 'new_user at test.com'
+  end
+
+  test 'a user sign up with valid information in XML format should return valid response' do
+    post user_registration_path(format: 'xml'), user: { email: 'new_user at test.com', password: 'new_user123', password_confirmation: 'new_user123' }
+    assert_response :success
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<user>)
+
+    user = User.to_adapter.find_first(order: [:id, :desc])
+    assert_equal user.email, 'new_user at test.com'
+  end
+
+  test 'a user sign up with invalid information in XML format should return invalid response' do
+    post user_registration_path(format: 'xml'), user: { email: 'new_user at test.com', password: 'new_user123', password_confirmation: 'invalid' }
+    assert_response :unprocessable_entity
+    assert response.body.include? %(<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<errors>)
+  end
+
+  test 'a user update information with valid data in XML format should return valid response' do
+    user = sign_in_as_user
+    put user_registration_path(format: 'xml'), user: { current_password: '12345678', email: 'user.new at test.com' }
+    assert_response :success
+    assert_equal user.reload.email, 'user.new at test.com'
+  end
+
+  test 'a user update information with invalid data in XML format should return invalid response' do
+    user = sign_in_as_user
+    put user_registration_path(format: 'xml'), user: { current_password: 'invalid', email: 'user.new at test.com' }
+    assert_response :unprocessable_entity
+    assert_equal user.reload.email, 'user at test.com'
+  end
+
+  test 'a user cancel their account in XML format should return valid response' do
+    sign_in_as_user
+    delete user_registration_path(format: 'xml')
+    assert_response :success
+    assert_equal User.to_adapter.find_all.size, 0
+  end
+end
+
+class ReconfirmableRegistrationTest < ActionDispatch::IntegrationTest
+  test 'a signed in admin should see a more appropriate flash message when editing their account if reconfirmable is enabled' do
+    sign_in_as_admin
+    get edit_admin_registration_path
+
+    fill_in 'email', with: 'admin.new at example.com'
+    fill_in 'current password', with: '123456'
+    click_button 'Update'
+
+    assert_current_url '/admin_area/home'
+    assert_contain 'but we need to verify your new email address'
+    assert_equal 'admin.new at example.com', Admin.to_adapter.find_first.unconfirmed_email
+
+    get edit_admin_registration_path
+    assert_contain 'Currently waiting confirmation for: admin.new at example.com'
+  end
+
+  test 'a signed in admin should not see a reconfirmation message if they did not change their password' do
+    sign_in_as_admin
+    get edit_admin_registration_path
+
+    fill_in 'password', with: 'pas123'
+    fill_in 'password confirmation', with: 'pas123'
+    fill_in 'current password', with: '123456'
+    click_button 'Update'
+
+    assert_current_url '/admin_area/home'
+    assert_contain 'Your account has been updated successfully.'
+
+    assert Admin.to_adapter.find_first.valid_password?('pas123')
+  end
+
+  test 'a signed in admin should not see a reconfirmation message if they did not change their email, despite having an unconfirmed email' do
+    sign_in_as_admin
+
+    get edit_admin_registration_path
+    fill_in 'email', with: 'admin.new at example.com'
+    fill_in 'current password', with: '123456'
+    click_button 'Update'
+
+    get edit_admin_registration_path
+    fill_in 'password', with: 'pas123'
+    fill_in 'password confirmation', with: 'pas123'
+    fill_in 'current password', with: '123456'
+    click_button 'Update'
+
+    assert_current_url '/admin_area/home'
+    assert_contain 'Your account has been updated successfully.'
+
+    assert_equal "admin.new at example.com", Admin.to_adapter.find_first.unconfirmed_email
+    assert Admin.to_adapter.find_first.valid_password?('pas123')
+  end
+end
diff --git a/test/integration/rememberable_test.rb b/test/integration/rememberable_test.rb
new file mode 100644
index 0000000..718a714
--- /dev/null
+++ b/test/integration/rememberable_test.rb
@@ -0,0 +1,167 @@
+require 'test_helper'
+
+class RememberMeTest < ActionDispatch::IntegrationTest
+  def create_user_and_remember(add_to_token='')
+    user = create_user
+    user.remember_me!
+    raw_cookie = User.serialize_into_cookie(user).tap { |a| a.last << add_to_token }
+    cookies['remember_user_token'] = generate_signed_cookie(raw_cookie)
+    user
+  end
+
+  def generate_signed_cookie(raw_cookie)
+    request = ActionDispatch::TestRequest.new
+    request.cookie_jar.signed['raw_cookie'] = raw_cookie
+    request.cookie_jar['raw_cookie']
+  end
+
+  def signed_cookie(key)
+    controller.send(:cookies).signed[key]
+  end
+
+  def cookie_expires(key)
+    cookie  = response.headers["Set-Cookie"].split("\n").grep(/^#{key}/).first
+    expires = cookie.split(";").map(&:strip).grep(/^expires=/).first
+    Time.parse(expires).utc
+  end
+
+  test 'do not remember the user if they have not checked remember me option' do
+    sign_in_as_user
+    assert_nil request.cookies["remember_user_cookie"]
+  end
+
+  test 'handle unverified requests gets rid of caches' do
+    swap ApplicationController, allow_forgery_protection: true do
+      post exhibit_user_url(1)
+      assert_not warden.authenticated?(:user)
+
+      create_user_and_remember
+      post exhibit_user_url(1)
+      assert_equal "User is not authenticated", response.body
+      assert_not warden.authenticated?(:user)
+    end
+  end
+
+  test 'handle unverified requests does not create cookies on sign in' do
+    swap ApplicationController, allow_forgery_protection: true do
+      get new_user_session_path
+      assert request.session[:_csrf_token]
+
+      post user_session_path, authenticity_token: "oops", user:
+           { email: "jose.valim at gmail.com", password: "123456", remember_me: "1" }
+      assert_not warden.authenticated?(:user)
+      assert_not request.cookies['remember_user_token']
+    end
+  end
+
+  test 'generate remember token after sign in' do
+    sign_in_as_user remember_me: true
+    assert request.cookies['remember_user_token']
+  end
+
+  test 'generate remember token after sign in setting cookie options' do
+    # We test this by asserting the cookie is not sent after the redirect
+    # since we changed the domain. This is the only difference with the
+    # previous test.
+    swap Devise, rememberable_options: { domain: "omg.somewhere.com" } do
+      sign_in_as_user remember_me: true
+      assert_nil request.cookies["remember_user_token"]
+    end
+  end
+
+  test 'generate remember token with a custom key' do
+    swap Devise, rememberable_options: { key: "v1lat_token" } do
+      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"
+      sign_in_as_user remember_me: true
+      assert_nil request.cookies["remember_user_token"]
+    ensure
+      Rails.configuration.session_options.delete(:domain)
+    end
+  end
+
+  test 'remember the user before sign in' do
+    user = create_user_and_remember
+    get users_path
+    assert_response :success
+    assert warden.authenticated?(:user)
+    assert warden.user(:user) == user
+    assert_match /remember_user_token[^\n]*HttpOnly/, response.headers["Set-Cookie"], "Expected Set-Cookie header in response to set HttpOnly flag on remember_user_token cookie."
+  end
+
+  test 'remember the user before sign up and redirect them to their home' do
+    create_user_and_remember
+    get new_user_registration_path
+    assert warden.authenticated?(:user)
+    assert_redirected_to root_path
+  end
+
+  test 'does not extend remember period through sign in' do
+    swap Devise, extend_remember_period: true, remember_for: 1.year do
+      user = create_user
+      user.remember_me!
+
+      user.remember_created_at = old = 10.days.ago
+      user.save
+
+      sign_in_as_user remember_me: true
+      user.reload
+
+      assert warden.user(:user) == user
+      assert_equal old.to_i, user.remember_created_at.to_i
+    end
+  end
+
+  test 'do not remember other scopes' do
+    create_user_and_remember
+    get root_path
+    assert_response :success
+    assert warden.authenticated?(:user)
+    assert_not warden.authenticated?(:admin)
+  end
+
+  test 'do not remember with invalid token' do
+    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
+    create_user_and_remember
+    swap Devise, remember_for: 0 do
+      get users_path
+      assert_not warden.authenticated?(:user)
+      assert_redirected_to new_user_session_path
+    end
+  end
+
+  test 'do not remember the user anymore after forget' do
+    create_user_and_remember
+    get users_path
+    assert warden.authenticated?(:user)
+
+    get destroy_user_session_path
+    assert_not warden.authenticated?(:user)
+    assert_nil warden.cookies['remember_user_token']
+
+    get users_path
+    assert_not warden.authenticated?(:user)
+  end
+
+  test 'changing user password expires remember me token' do
+    user = create_user_and_remember
+    user.password = "another_password"
+    user.password_confirmation = "another_password"
+    user.save!
+
+    get users_path
+    assert_not warden.authenticated?(:user)
+  end
+end
diff --git a/test/integration/timeoutable_test.rb b/test/integration/timeoutable_test.rb
new file mode 100644
index 0000000..71a6fdb
--- /dev/null
+++ b/test/integration/timeoutable_test.rb
@@ -0,0 +1,189 @@
+require 'test_helper'
+
+class SessionTimeoutTest < ActionDispatch::IntegrationTest
+
+  def last_request_at
+    @controller.user_session['last_request_at']
+  end
+
+  test 'set last request at in user session after each request' do
+    sign_in_as_user
+    assert_not_nil last_request_at
+
+    @controller.user_session.delete('last_request_at')
+    get users_path
+    assert_not_nil last_request_at
+  end
+
+  test 'set last request at in user session after each request is skipped if tracking is disabled' do
+    sign_in_as_user
+    old_last_request = last_request_at
+    assert_not_nil last_request_at
+
+    get users_path, {}, 'devise.skip_trackable' => true
+    assert_equal old_last_request, last_request_at
+  end
+
+  test 'does not time out user session before default limit time' do
+    sign_in_as_user
+    assert_response :success
+    assert warden.authenticated?(:user)
+
+    get users_path
+    assert_response :success
+    assert warden.authenticated?(:user)
+  end
+
+  test 'time out user session after default limit time when sign_out_all_scopes is false' do
+    swap Devise, sign_out_all_scopes: false do
+      sign_in_as_admin
+
+      user = sign_in_as_user
+      get expire_user_path(user)
+      assert_not_nil last_request_at
+
+      get users_path
+      assert_redirected_to users_path
+      assert_not warden.authenticated?(:user)
+      assert warden.authenticated?(:admin)
+    end
+  end
+
+  test 'time out all sessions after default limit time when sign_out_all_scopes is true' do
+    swap Devise, sign_out_all_scopes: true do
+      sign_in_as_admin
+
+      user = sign_in_as_user
+      get expire_user_path(user)
+      assert_not_nil last_request_at
+
+      get root_path
+      assert_not warden.authenticated?(:user)
+      assert_not warden.authenticated?(:admin)
+    end
+  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)
+
+    get destroy_user_session_path
+
+    assert_response :redirect
+    assert_redirected_to root_path
+    follow_redirect!
+    assert_contain 'Signed out successfully'
+  end
+
+  test 'expired session is not extended by sign in page' do
+    user = sign_in_as_user
+    get expire_user_path(user)
+    assert warden.authenticated?(:user)
+
+    get "/users/sign_in"
+    assert_redirected_to "/users/sign_in"
+    follow_redirect!
+
+    assert_response :success
+    assert_contain 'Sign in'
+    assert_not warden.authenticated?(:user)
+  end
+
+  test 'time out is not triggered on sign in' do
+    user = sign_in_as_user
+    get expire_user_path(user)
+
+    post "/users/sign_in", email: user.email, password: "123456"
+
+    assert_response :redirect
+    follow_redirect!
+    assert_contain 'You are signed in'
+  end
+
+  test 'admin does not explode on time out' do
+    admin = sign_in_as_admin
+    get expire_admin_path(admin)
+
+    Admin.send :define_method, :reset_authentication_token! do
+      nil
+    end
+
+    begin
+      get admins_path
+      assert_redirected_to admins_path
+      assert_not warden.authenticated?(:admin)
+    ensure
+      Admin.send(:remove_method, :reset_authentication_token!)
+    end
+  end
+
+  test 'user configured timeout limit' do
+    swap Devise, timeout_in: 8.minutes do
+      user = sign_in_as_user
+
+      get users_path
+      assert_not_nil last_request_at
+      assert_response :success
+      assert warden.authenticated?(:user)
+
+      get expire_user_path(user)
+      get users_path
+      assert_redirected_to users_path
+      assert_not warden.authenticated?(:user)
+    end
+  end
+
+  test 'error message with i18n' do
+    store_translations :en, devise: {
+      failure: { user: { timeout: 'Session expired!' } }
+    } do
+      user = sign_in_as_user
+
+      get expire_user_path(user)
+      get root_path
+      follow_redirect!
+      assert_contain 'Session expired!'
+    end
+  end
+
+  test 'error message with i18n with double redirect' do
+    store_translations :en, devise: {
+      failure: { user: { timeout: 'Session expired!' } }
+    } do
+      user = sign_in_as_user
+
+      get expire_user_path(user)
+      get users_path
+      follow_redirect!
+      follow_redirect!
+      assert_contain 'Session expired!'
+    end
+  end
+
+  test 'time out not triggered if remembered' do
+    user = sign_in_as_user remember_me: true
+    get expire_user_path(user)
+    assert_not_nil last_request_at
+
+    get users_path
+    assert_response :success
+    assert warden.authenticated?(:user)
+  end
+
+  test 'does not crashes when the last_request_at is a String' do
+    user = sign_in_as_user
+
+    get edit_form_user_path(user, last_request_at: Time.now.utc.to_s)
+    get users_path
+  end
+end
diff --git a/test/integration/trackable_test.rb b/test/integration/trackable_test.rb
new file mode 100644
index 0000000..0dbbee2
--- /dev/null
+++ b/test/integration/trackable_test.rb
@@ -0,0 +1,92 @@
+require 'test_helper'
+
+class TrackableHooksTest < ActionDispatch::IntegrationTest
+
+  test "current and last sign in timestamps are updated on each sign in" do
+    user = create_user
+    assert_nil user.current_sign_in_at
+    assert_nil user.last_sign_in_at
+
+    sign_in_as_user
+    user.reload
+
+    assert user.current_sign_in_at.acts_like?(:time)
+    assert user.last_sign_in_at.acts_like?(:time)
+
+    assert_equal user.current_sign_in_at, user.last_sign_in_at
+    assert user.current_sign_in_at >= user.created_at
+
+    visit destroy_user_session_path
+    new_time = 2.seconds.from_now
+    Time.stubs(:now).returns(new_time)
+
+    sign_in_as_user
+    user.reload
+    assert user.current_sign_in_at > user.last_sign_in_at
+  end
+
+  test "current and last sign in remote ip are updated on each sign in" do
+    user = create_user
+    assert_nil user.current_sign_in_ip
+    assert_nil user.last_sign_in_ip
+
+    sign_in_as_user
+    user.reload
+
+    assert_equal "127.0.0.1", user.current_sign_in_ip
+    assert_equal "127.0.0.1", user.last_sign_in_ip
+  end
+
+  test "current remote ip returns original ip behind a non transparent proxy" do
+    user = create_user
+
+    arbitrary_ip = '200.121.1.69'
+    sign_in_as_user do
+      header 'HTTP_X_FORWARDED_FOR', arbitrary_ip
+    end
+    user.reload
+    assert_equal arbitrary_ip, user.current_sign_in_ip
+  end
+
+  test "increase sign in count" do
+    user = create_user
+    assert_equal 0, user.sign_in_count
+
+    sign_in_as_user
+    user.reload
+    assert_equal 1, user.sign_in_count
+
+    visit destroy_user_session_path
+    sign_in_as_user
+    user.reload
+    assert_equal 2, user.sign_in_count
+  end
+
+  test "does not update anything if user has signed out along the way" do
+    swap Devise, allow_unconfirmed_access_for: 0.days do
+      user = create_user(confirm: false)
+      sign_in_as_user
+
+      user.reload
+      assert_nil user.current_sign_in_at
+      assert_nil user.last_sign_in_at
+    end
+  end
+
+  test "do not track if devise.skip_trackable is set" do
+    user = create_user
+    sign_in_as_user do
+      header 'devise.skip_trackable', '1'
+    end
+    user.reload
+    assert_equal 0, user.sign_in_count
+    visit destroy_user_session_path
+
+    sign_in_as_user do
+      header 'devise.skip_trackable', false
+    end
+    user.reload
+    assert_equal 1, user.sign_in_count
+  end
+
+end
diff --git a/test/mailers/confirmation_instructions_test.rb b/test/mailers/confirmation_instructions_test.rb
new file mode 100644
index 0000000..8eb9358
--- /dev/null
+++ b/test/mailers/confirmation_instructions_test.rb
@@ -0,0 +1,115 @@
+require 'test_helper'
+
+class ConfirmationInstructionsTest < ActionMailer::TestCase
+
+  def setup
+    setup_mailer
+    Devise.mailer = 'Devise::Mailer'
+    Devise.mailer_sender = 'test at example.com'
+  end
+
+  def teardown
+    Devise.mailer = 'Devise::Mailer'
+    Devise.mailer_sender = 'please-change-me at config-initializers-devise.com'
+  end
+
+  def user
+    @user ||= create_user
+  end
+
+  def mail
+    @mail ||= begin
+      user
+      ActionMailer::Base.deliveries.first
+    end
+  end
+
+  test 'email sent after creating the user' do
+    assert_not_nil mail
+  end
+
+  test 'content type should be set to html' do
+    assert mail.content_type.include?('text/html')
+  end
+
+  test 'send confirmation instructions to the user email' do
+    mail
+    assert_equal [user.email], mail.to
+  end
+
+  test 'setup sender from configuration' do
+    assert_equal ['test at example.com'], mail.from
+  end
+
+  test 'setup sender from custom mailer defaults' do
+    Devise.mailer = 'Users::Mailer'
+    assert_equal ['custom at example.com'], mail.from
+  end
+
+  test 'setup sender from custom mailer defaults with proc' do
+    Devise.mailer = 'Users::FromProcMailer'
+    assert_equal ['custom at example.com'], mail.from
+  end
+
+  test 'custom mailer renders parent mailer template' do
+    Devise.mailer = 'Users::Mailer'
+    assert_present mail.body.encoded
+  end
+
+  test 'setup reply to as copy from sender' do
+    assert_equal ['test at example.com'], mail.reply_to
+  end
+
+  test 'setup reply to as different if set in defaults' do
+    Devise.mailer = 'Users::ReplyToMailer'
+    assert_equal ['custom at example.com'], mail.from
+    assert_equal ['custom_reply_to at 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
+    end
+  end
+
+  test 'subject namespaced by model' do
+    store_translations :en, devise: { mailer: { confirmation_instructions: { user_subject: 'User Account Confirmation' } } } do
+      assert_equal 'User Account Confirmation', mail.subject
+    end
+  end
+
+  test 'body should have user info' do
+    assert_match user.email, mail.body.encoded
+  end
+
+  test 'body should have link to confirm the account' do
+    host, port = ActionMailer::Base.default_url_options.values_at :host, :port
+
+    if mail.body.encoded =~ %r{<a href=\"http://#{host}:#{port}/users/confirmation\?confirmation_token=([^"]+)">}
+      assert_equal Devise.token_generator.digest(user.class, :confirmation_token, $1), user.confirmation_token
+    else
+      flunk "expected confirmation url regex to match"
+    end
+  end
+
+  test 'renders a scoped if scoped_views is set to true' do
+    swap Devise, scoped_views: true do
+      assert_equal user.email, mail.body.decoded
+    end
+  end
+
+  test 'renders a scoped if scoped_views is set in the mailer class' do
+    begin
+      Devise::Mailer.scoped_views = true
+      assert_equal user.email, mail.body.decoded
+    ensure
+      Devise::Mailer.send :remove_instance_variable, :@scoped_views
+    end
+  end
+
+  test 'mailer sender accepts a proc' do
+    swap Devise, mailer_sender: proc { "another at example.com" } do
+      assert_equal ['another at example.com'], mail.from
+    end
+  end
+end
diff --git a/test/mailers/reset_password_instructions_test.rb b/test/mailers/reset_password_instructions_test.rb
new file mode 100644
index 0000000..4a95c9a
--- /dev/null
+++ b/test/mailers/reset_password_instructions_test.rb
@@ -0,0 +1,96 @@
+require 'test_helper'
+
+class ResetPasswordInstructionsTest < ActionMailer::TestCase
+  def setup
+    setup_mailer
+    Devise.mailer = 'Devise::Mailer'
+    Devise.mailer_sender = 'test at example.com'
+  end
+
+  def teardown
+    Devise.mailer = 'Devise::Mailer'
+    Devise.mailer_sender = 'please-change-me at config-initializers-devise.com'
+  end
+
+  def user
+    @user ||= begin
+      user = create_user
+      user.send_reset_password_instructions
+      user
+    end
+  end
+
+  def mail
+    @mail ||= begin
+      user
+      ActionMailer::Base.deliveries.last
+    end
+  end
+
+  test 'email sent after reseting the user password' do
+    assert_not_nil mail
+  end
+
+  test 'content type should be set to html' do
+    assert mail.content_type.include?('text/html')
+  end
+
+  test 'send confirmation instructions to the user email' do
+    assert_equal [user.email], mail.to
+  end
+
+  test 'setup sender from configuration' do
+    assert_equal ['test at example.com'], mail.from
+  end
+
+  test 'setup sender from custom mailer defaults' do
+    Devise.mailer = 'Users::Mailer'
+    assert_equal ['custom at example.com'], mail.from
+  end
+
+  test 'setup sender from custom mailer defaults with proc' do
+    Devise.mailer = 'Users::FromProcMailer'
+    assert_equal ['custom at example.com'], mail.from
+  end
+
+  test 'custom mailer renders parent mailer template' do
+    Devise.mailer = 'Users::Mailer'
+    assert_present mail.body.encoded
+  end
+
+  test 'setup reply to as copy from sender' do
+    assert_equal ['test at example.com'], mail.reply_to
+  end
+
+  test 'setup subject from I18n' do
+    store_translations :en, devise: { mailer: { reset_password_instructions: { subject: 'Reset instructions' } } } do
+      assert_equal 'Reset instructions', mail.subject
+    end
+  end
+
+  test 'subject namespaced by model' do
+    store_translations :en, devise: { mailer: { reset_password_instructions: { user_subject: 'User Reset Instructions' } } } do
+      assert_equal 'User Reset Instructions', mail.subject
+    end
+  end
+
+  test 'body should have user info' do
+    assert_match user.email, mail.body.encoded
+  end
+
+  test 'body should have link to confirm the account' do
+    host, port = ActionMailer::Base.default_url_options.values_at :host, :port
+
+    if mail.body.encoded =~ %r{<a href=\"http://#{host}:#{port}/users/password/edit\?reset_password_token=([^"]+)">}
+      assert_equal Devise.token_generator.digest(user.class, :reset_password_token, $1), user.reset_password_token
+    else
+      flunk "expected reset password url regex to match"
+    end
+  end
+
+  test 'mailer sender accepts a proc' do
+    swap Devise, mailer_sender: proc { "another at example.com" } do
+      assert_equal ['another at example.com'], mail.from
+    end
+  end
+end
diff --git a/test/mailers/unlock_instructions_test.rb b/test/mailers/unlock_instructions_test.rb
new file mode 100644
index 0000000..3894836
--- /dev/null
+++ b/test/mailers/unlock_instructions_test.rb
@@ -0,0 +1,91 @@
+require 'test_helper'
+
+class UnlockInstructionsTest < ActionMailer::TestCase
+
+  def setup
+    setup_mailer
+    Devise.mailer = 'Devise::Mailer'
+    Devise.mailer_sender = 'test at example.com'
+  end
+
+  def teardown
+    Devise.mailer = 'Devise::Mailer'
+    Devise.mailer_sender = 'please-change-me at config-initializers-devise.com'
+  end
+
+  def user
+    @user ||= begin
+      user = create_user
+      user.lock_access!
+      user
+    end
+  end
+
+  def mail
+    @mail ||= begin
+      user
+      ActionMailer::Base.deliveries.last
+    end
+  end
+
+  test 'email sent after locking the user' do
+    assert_not_nil mail
+  end
+
+  test 'content type should be set to html' do
+    assert mail.content_type.include?('text/html')
+  end
+
+  test 'send unlock instructions to the user email' do
+    assert_equal [user.email], mail.to
+  end
+
+  test 'setup sender from configuration' do
+    assert_equal ['test at example.com'], mail.from
+  end
+
+  test 'setup sender from custom mailer defaults' do
+    Devise.mailer = 'Users::Mailer'
+    assert_equal ['custom at example.com'], mail.from
+  end
+
+  test 'setup sender from custom mailer defaults with proc' do
+    Devise.mailer = 'Users::FromProcMailer'
+    assert_equal ['custom at example.com'], mail.from
+  end
+
+  test 'custom mailer renders parent mailer template' do
+    Devise.mailer = 'Users::Mailer'
+    assert_present mail.body.encoded
+  end
+
+  test 'setup reply to as copy from sender' do
+    assert_equal ['test at example.com'], mail.reply_to
+  end
+
+  test 'setup subject from I18n' do
+    store_translations :en, devise: { mailer: { unlock_instructions:  { subject: 'Yo unlock instructions' } } } do
+      assert_equal 'Yo unlock instructions', mail.subject
+    end
+  end
+
+  test 'subject namespaced by model' do
+    store_translations :en, devise: { mailer: { unlock_instructions: { user_subject: 'User Unlock Instructions' } } } do
+      assert_equal 'User Unlock Instructions', mail.subject
+    end
+  end
+
+  test 'body should have user info' do
+    assert_match user.email, mail.body.encoded
+  end
+
+  test 'body should have link to unlock the account' do
+    host, port = ActionMailer::Base.default_url_options.values_at :host, :port
+
+    if mail.body.encoded =~ %r{<a href=\"http://#{host}:#{port}/users/unlock\?unlock_token=([^"]+)">}
+      assert_equal Devise.token_generator.digest(user.class, :unlock_token, $1), user.unlock_token
+    else
+      flunk "expected unlock url regex to match"
+    end
+  end
+end
diff --git a/test/mapping_test.rb b/test/mapping_test.rb
new file mode 100644
index 0000000..d22bf0b
--- /dev/null
+++ b/test/mapping_test.rb
@@ -0,0 +1,128 @@
+require 'test_helper'
+
+class FakeRequest < Struct.new(:path_info, :params)
+end
+
+class MappingTest < ActiveSupport::TestCase
+  def fake_request(path, params={})
+    FakeRequest.new(path, params)
+  end
+
+  test 'store options' do
+    mapping = Devise.mappings[:user]
+    assert_equal User,                mapping.to
+    assert_equal User.devise_modules, mapping.modules
+    assert_equal "users",             mapping.scoped_path
+    assert_equal :user,               mapping.singular
+    assert_equal "users",             mapping.path
+    assert_equal "/users",            mapping.fullpath
+  end
+
+  test 'store options with namespace' do
+    mapping = Devise.mappings[:publisher_account]
+    assert_equal Admin,                 mapping.to
+    assert_equal "publisher/accounts",  mapping.scoped_path
+    assert_equal :publisher_account,    mapping.singular
+    assert_equal "accounts",            mapping.path
+    assert_equal "/publisher/accounts", mapping.fullpath
+  end
+
+  test 'allows path to be given' do
+    assert_equal "admin_area", Devise.mappings[:admin].path
+  end
+
+  test 'allows to skip all routes' do
+    assert_equal [], Devise.mappings[:skip_admin].used_routes
+  end
+
+  test 'sign_out_via defaults to :get' do
+    assert_equal :get, Devise.mappings[:user].sign_out_via
+  end
+
+  test 'allows custom sign_out_via to be given' do
+    assert_equal :delete,          Devise.mappings[:sign_out_via_delete].sign_out_via
+    assert_equal :post,            Devise.mappings[:sign_out_via_post].sign_out_via
+    assert_equal [:delete, :post], Devise.mappings[:sign_out_via_delete_or_post].sign_out_via
+  end
+
+  test 'allows custom singular to be given' do
+    assert_equal "accounts", Devise.mappings[:manager].path
+  end
+
+  test 'has strategies depending on the model declaration' do
+    assert_equal [:rememberable, :database_authenticatable], Devise.mappings[:user].strategies
+    assert_equal [:database_authenticatable], Devise.mappings[:admin].strategies
+  end
+
+  test 'has no input strategies depending on the model declaration' do
+    assert_equal [:rememberable], Devise.mappings[:user].no_input_strategies
+    assert_equal [], Devise.mappings[:admin].no_input_strategies
+  end
+
+  test 'find scope for a given object' do
+    assert_equal :user, Devise::Mapping.find_scope!(User)
+    assert_equal :user, Devise::Mapping.find_scope!(:user)
+    assert_equal :user, Devise::Mapping.find_scope!("user")
+    assert_equal :user, Devise::Mapping.find_scope!(User.new)
+  end
+
+  test 'find scope works with single table inheritance' do
+    assert_equal :user, Devise::Mapping.find_scope!(Class.new(User))
+    assert_equal :user, Devise::Mapping.find_scope!(Class.new(User).new)
+  end
+
+  test 'find scope raises an error if cannot be found' do
+    assert_raise RuntimeError do
+      Devise::Mapping.find_scope!(String)
+    end
+  end
+
+  test 'return default path names' do
+    mapping = Devise.mappings[:user]
+    assert_equal 'sign_in',      mapping.path_names[:sign_in]
+    assert_equal 'sign_out',     mapping.path_names[:sign_out]
+    assert_equal 'password',     mapping.path_names[:password]
+    assert_equal 'confirmation', mapping.path_names[:confirmation]
+    assert_equal 'sign_up',      mapping.path_names[:sign_up]
+    assert_equal 'unlock',       mapping.path_names[:unlock]
+  end
+
+  test 'allow custom path names to be given' do
+    mapping = Devise.mappings[:manager]
+    assert_equal 'login',        mapping.path_names[:sign_in]
+    assert_equal 'logout',       mapping.path_names[:sign_out]
+    assert_equal 'secret',       mapping.path_names[:password]
+    assert_equal 'verification', mapping.path_names[:confirmation]
+    assert_equal 'register',     mapping.path_names[:sign_up]
+    assert_equal 'unblock',      mapping.path_names[:unlock]
+  end
+
+  test 'magic predicates' do
+    mapping = Devise.mappings[:user]
+    assert mapping.authenticatable?
+    assert mapping.confirmable?
+    assert mapping.recoverable?
+    assert mapping.rememberable?
+    assert mapping.registerable?
+
+    mapping = Devise.mappings[:admin]
+    assert mapping.authenticatable?
+    assert mapping.recoverable?
+    assert mapping.lockable?
+    assert_not mapping.omniauthable?
+  end
+
+  test 'find mapping by path' do
+    assert_raise RuntimeError do
+      Devise::Mapping.find_by_path!('/accounts/facebook/callback')
+    end
+
+    assert_nothing_raised do
+      Devise::Mapping.find_by_path!('/:locale/accounts/login')
+    end
+
+    assert_nothing_raised do
+      Devise::Mapping.find_by_path!('/accounts/facebook/callback', :path)
+    end
+  end
+end
diff --git a/test/models/authenticatable_test.rb b/test/models/authenticatable_test.rb
new file mode 100644
index 0000000..ba664f3
--- /dev/null
+++ b/test/models/authenticatable_test.rb
@@ -0,0 +1,23 @@
+require 'test_helper'
+
+class AuthenticatableTest < ActiveSupport::TestCase
+  test 'required_fields should be an empty array' do
+    assert_equal Devise::Models::Validatable.required_fields(User), []
+  end
+
+  test 'find_first_by_auth_conditions allows custom filtering parameters' do
+    user = User.create!(email: "example at example.com", password: "1234567")
+    assert_equal User.find_first_by_auth_conditions({ email: "example at example.com" }), user
+    assert_nil User.find_first_by_auth_conditions({ email: "example at example.com" }, id: user.id.to_s.next)
+  end
+
+  if defined?(ActionController::Parameters)
+    test 'does not passes an ActionController::Parameters to find_first_by_auth_conditions through find_or_initialize_with_errors' do
+      user = create_user(email: 'example at example.com')
+      attributes = ActionController::Parameters.new(email: 'example at example.com')
+
+      User.expects(:find_first_by_auth_conditions).with('email' => 'example at example.com').returns(user)
+      User.find_or_initialize_with_errors([:email], attributes)
+    end
+  end
+end
diff --git a/test/models/confirmable_test.rb b/test/models/confirmable_test.rb
new file mode 100644
index 0000000..a08addf
--- /dev/null
+++ b/test/models/confirmable_test.rb
@@ -0,0 +1,455 @@
+require 'test_helper'
+
+class ConfirmableTest < ActiveSupport::TestCase
+
+  def setup
+    setup_mailer
+  end
+
+  test 'should generate confirmation token after creating a record' do
+    assert_nil new_user.confirmation_token
+    assert_not_nil create_user.confirmation_token
+  end
+
+  test 'should never generate the same confirmation token for different users' do
+    confirmation_tokens = []
+    3.times do
+      token = create_user.confirmation_token
+      assert !confirmation_tokens.include?(token)
+      confirmation_tokens << token
+    end
+  end
+
+  test 'should confirm a user by updating confirmed at' do
+    user = create_user
+    assert_nil user.confirmed_at
+    assert user.confirm!
+    assert_not_nil user.confirmed_at
+  end
+
+  test 'should clear confirmation token while confirming a user' do
+    user = create_user
+    assert_present user.confirmation_token
+    user.confirm!
+    assert_nil user.confirmation_token
+  end
+
+  test 'should verify whether a user is confirmed or not' do
+    assert_not new_user.confirmed?
+    user = create_user
+    assert_not user.confirmed?
+    user.confirm!
+    assert user.confirmed?
+  end
+
+  test 'should not confirm a user already confirmed' do
+    user = create_user
+    assert user.confirm!
+    assert_blank user.errors[:email]
+
+    assert_not user.confirm!
+    assert_equal "was already confirmed, please try signing in", user.errors[:email].join
+  end
+
+  test 'should find and confirm a user automatically based on the raw token' do
+    user = create_user
+    raw  = user.raw_confirmation_token
+    confirmed_user = User.confirm_by_token(raw)
+    assert_equal confirmed_user, user
+    assert user.reload.confirmed?
+  end
+
+  test 'should return a new record with errors when a invalid token is given' do
+    confirmed_user = User.confirm_by_token('invalid_confirmation_token')
+    assert_not confirmed_user.persisted?
+    assert_equal "is invalid", confirmed_user.errors[:confirmation_token].join
+  end
+
+  test 'should return a new record with errors when a blank token is given' do
+    confirmed_user = User.confirm_by_token('')
+    assert_not confirmed_user.persisted?
+    assert_equal "can't be blank", confirmed_user.errors[:confirmation_token].join
+  end
+
+  test 'should generate errors for a user email if user is already confirmed' do
+    user = create_user
+    user.confirmed_at = Time.now
+    user.save
+    confirmed_user = User.confirm_by_token(user.raw_confirmation_token)
+    assert confirmed_user.confirmed?
+    assert_equal "was already confirmed, please try signing in", confirmed_user.errors[:email].join
+  end
+
+  test 'should send confirmation instructions by email' do
+    assert_email_sent "mynewuser at example.com" do
+      create_user email: "mynewuser at example.com"
+    end
+  end
+
+  test 'should not send confirmation when trying to save an invalid user' do
+    assert_email_not_sent do
+      user = new_user
+      user.stubs(:valid?).returns(false)
+      user.save
+    end
+  end
+
+  test 'should not generate a new token neither send e-mail if skip_confirmation! is invoked' do
+    user = new_user
+    user.skip_confirmation!
+
+    assert_email_not_sent do
+      user.save!
+      assert_nil user.confirmation_token
+      assert_not_nil user.confirmed_at
+    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 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)
+    assert_equal confirmation_user, user
+  end
+
+  test 'should return a new user if no email was found' do
+    confirmation_user = User.send_confirmation_instructions(email: "invalid at example.com")
+    assert_not confirmation_user.persisted?
+  end
+
+  test 'should add error to new user email if no email was found' do
+    confirmation_user = User.send_confirmation_instructions(email: "invalid at example.com")
+    assert confirmation_user.errors[:email]
+    assert_equal "not found", confirmation_user.errors[:email].join
+  end
+
+  test 'should send email instructions for the user confirm its email' do
+    user = create_user
+    assert_email_sent user.email do
+      User.send_confirmation_instructions(email: user.email)
+    end
+  end
+
+  test 'should always have confirmation token when email is sent' do
+    user = new_user
+    user.instance_eval { def confirmation_required?; false end }
+    user.save
+    user.send_confirmation_instructions
+    assert_not_nil user.reload.confirmation_token
+  end
+
+  test 'should not resend email instructions if the user change their email' do
+    user = create_user
+    user.email = 'new_test at example.com'
+    assert_email_not_sent do
+      user.save!
+    end
+  end
+
+  test 'should not reset confirmation status or token when updating email' do
+    user = create_user
+    user.confirm!
+    user.email = 'new_test at example.com'
+    user.save!
+
+    user.reload
+    assert user.confirmed?
+    assert_nil user.confirmation_token
+  end
+
+  test 'should not be able to send instructions if the user is already confirmed' do
+    user = create_user
+    user.confirm!
+    assert_not user.resend_confirmation_instructions
+    assert user.confirmed?
+    assert_equal 'was already confirmed, please try signing in', user.errors[:email].join
+  end
+
+  test 'confirm time should fallback to devise confirm in default configuration' do
+    swap Devise, allow_unconfirmed_access_for: 1.day do
+      user = new_user
+      user.confirmation_sent_at = 2.days.ago
+      assert_not user.active_for_authentication?
+
+      Devise.allow_unconfirmed_access_for = 3.days
+      assert user.active_for_authentication?
+    end
+  end
+
+  test 'should be active when confirmation sent at is not overpast' do
+    swap Devise, allow_unconfirmed_access_for: 5.days do
+      Devise.allow_unconfirmed_access_for = 5.days
+      user = create_user
+
+      user.confirmation_sent_at = 4.days.ago
+      assert user.active_for_authentication?
+
+      user.confirmation_sent_at = 5.days.ago
+      assert_not user.active_for_authentication?
+    end
+  end
+
+  test 'should be active when already confirmed' do
+    user = create_user
+    assert_not user.confirmed?
+    assert_not user.active_for_authentication?
+
+    user.confirm!
+    assert user.confirmed?
+    assert user.active_for_authentication?
+  end
+
+  test 'should not be active when confirm in is zero' do
+    Devise.allow_unconfirmed_access_for = 0.days
+    user = create_user
+    user.confirmation_sent_at = Date.today
+    assert_not user.active_for_authentication?
+  end
+
+  test 'should be active when we set allow_unconfirmed_access_for to nil' do
+    swap Devise, allow_unconfirmed_access_for: nil do
+      user = create_user
+      user.confirmation_sent_at = Date.today
+      assert user.active_for_authentication?
+    end
+  end
+
+  test 'should not be active without confirmation' do
+    user = create_user
+    user.confirmation_sent_at = nil
+    user.save
+    assert_not user.reload.active_for_authentication?
+  end
+
+  test 'should be active without confirmation when confirmation is not required' do
+    user = create_user
+    user.instance_eval { def confirmation_required?; false end }
+    user.confirmation_sent_at = nil
+    user.save
+    assert user.reload.active_for_authentication?
+  end
+
+  test 'should find a user to send email instructions for the user confirm its email by authentication_keys' do
+    swap Devise, authentication_keys: [:username, :email] do
+      user = create_user
+      confirm_user = User.send_confirmation_instructions(email: user.email, username: user.username)
+      assert_equal confirm_user, user
+    end
+  end
+
+  test 'should require all confirmation_keys' do
+    swap Devise, confirmation_keys: [:username, :email] do
+      user = create_user
+      confirm_user = User.send_confirmation_instructions(email: user.email)
+      assert_not confirm_user.persisted?
+      assert_equal "can't be blank", confirm_user.errors[:username].join
+    end
+  end
+
+  def confirm_user_by_token_with_confirmation_sent_at(confirmation_sent_at)
+    user = create_user
+    user.update_attribute(:confirmation_sent_at, confirmation_sent_at)
+    confirmed_user = User.confirm_by_token(user.raw_confirmation_token)
+    assert_equal confirmed_user, user
+    user.reload.confirmed?
+  end
+
+  test 'should accept confirmation email token even after 5 years when no expiration is set' do
+    assert confirm_user_by_token_with_confirmation_sent_at(5.years.ago)
+  end
+
+  test 'should accept confirmation email token after 2 days when expiration is set to 3 days' do
+    swap Devise, confirm_within: 3.days do
+      assert confirm_user_by_token_with_confirmation_sent_at(2.days.ago)
+    end
+  end
+
+  test 'should not accept confirmation email token after 4 days when expiration is set to 3 days' do
+    swap Devise, confirm_within: 3.days do
+      assert_not confirm_user_by_token_with_confirmation_sent_at(4.days.ago)
+    end
+  end
+
+  test 'always generate a new token on resend' do
+    user = create_user
+    old  = user.confirmation_token
+    user = User.find(user.id)
+    user.resend_confirmation_instructions
+    assert_not_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
+  test 'should not worry about validations on confirm even with reconfirmable' do
+    admin = create_admin
+    admin.reset_password_token = "a"
+    assert admin.confirm!
+  end
+
+  test 'should generate confirmation token after changing email' do
+    admin = create_admin
+    assert admin.confirm!
+    assert_nil admin.confirmation_token
+    assert admin.update_attributes(email: 'new_test at example.com')
+    assert_not_nil admin.confirmation_token
+  end
+
+  test 'should not generate confirmation token if skipping reconfirmation after changing email' do
+    admin = create_admin
+    assert admin.confirm!
+    admin.skip_reconfirmation!
+    assert admin.update_attributes(email: 'new_test at example.com')
+    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 at example.com')
+    end
+  end
+
+  test 'should regenerate confirmation token after changing email' do
+    admin = create_admin
+    assert admin.confirm!
+    assert admin.update_attributes(email: 'old_test at example.com')
+    token = admin.confirmation_token
+    assert admin.update_attributes(email: 'new_test at example.com')
+    assert_not_equal token, admin.confirmation_token
+  end
+
+  test 'should send confirmation instructions by email after changing email' do
+    admin = create_admin
+    assert admin.confirm!
+    assert_email_sent "new_test at example.com" do
+      assert admin.update_attributes(email: 'new_test at example.com')
+    end
+    assert_match "new_test at example.com", ActionMailer::Base.deliveries.last.body.encoded
+  end
+
+  test 'should not send confirmation by email after changing password' do
+    admin = create_admin
+    assert admin.confirm!
+    assert_email_not_sent do
+      assert admin.update_attributes(password: 'newpass', password_confirmation: 'newpass')
+    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!
+    assert admin.update_attributes(email: 'new_test at example.com')
+    assert admin.confirmed?
+  end
+
+  test 'should update email only when it is confirmed' do
+    admin = create_admin
+    assert admin.confirm!
+    assert admin.update_attributes(email: 'new_test at example.com')
+    assert_not_equal 'new_test at example.com', admin.email
+    assert admin.confirm!
+    assert_equal 'new_test at example.com', admin.email
+  end
+
+  test 'should not allow admin to get past confirmation email by resubmitting their new address' do
+    admin = create_admin
+    assert admin.confirm!
+    assert admin.update_attributes(email: 'new_test at example.com')
+    assert_not_equal 'new_test at example.com', admin.email
+    assert admin.update_attributes(email: 'new_test at example.com')
+    assert_not_equal 'new_test at example.com', admin.email
+  end
+
+  test 'should find a admin by send confirmation instructions with unconfirmed_email' do
+    admin = create_admin
+    assert admin.confirm!
+    assert admin.update_attributes(email: 'new_test at example.com')
+    confirmation_admin = Admin.send_confirmation_instructions(email: admin.unconfirmed_email)
+    assert_equal confirmation_admin, admin
+  end
+
+  test 'should return a new admin if no email or unconfirmed_email was found' do
+    confirmation_admin = Admin.send_confirmation_instructions(email: "invalid at email.com")
+    assert_not confirmation_admin.persisted?
+  end
+
+  test 'should add error to new admin email if no email or unconfirmed_email was found' do
+    confirmation_admin = Admin.send_confirmation_instructions(email: "invalid at email.com")
+    assert confirmation_admin.errors[:email]
+    assert_equal "not found", confirmation_admin.errors[:email].join
+  end
+
+  test 'should find admin with email in unconfirmed_emails' do
+    admin = create_admin
+    admin.unconfirmed_email = "new_test at email.com"
+    assert admin.save
+    admin = Admin.find_by_unconfirmed_email_with_errors(email: "new_test at email.com")
+    assert admin.persisted?
+  end
+
+  test 'required_fields should contain the fields that Devise uses' do
+    assert_same_content Devise::Models::Confirmable.required_fields(User), [
+      :confirmation_sent_at,
+      :confirmation_token,
+      :confirmed_at
+    ]
+  end
+
+  test 'required_fields should also contain unconfirmable when reconfirmable_email is true' do
+    assert_same_content Devise::Models::Confirmable.required_fields(Admin), [
+      :confirmation_sent_at,
+      :confirmation_token,
+      :confirmed_at,
+      :unconfirmed_email
+    ]
+  end
+end
diff --git a/test/models/database_authenticatable_test.rb b/test/models/database_authenticatable_test.rb
new file mode 100644
index 0000000..fc3f729
--- /dev/null
+++ b/test/models/database_authenticatable_test.rb
@@ -0,0 +1,249 @@
+require 'test_helper'
+require 'test_models'
+require 'digest/sha1'
+
+class DatabaseAuthenticatableTest < ActiveSupport::TestCase
+  test 'should downcase case insensitive keys when saving' do
+    # case_insensitive_keys is set to :email by default.
+    email = 'Foo at Bar.com'
+    user = new_user(email: email)
+
+    assert_equal email, user.email
+    user.save!
+    assert_equal email.downcase, user.email
+  end
+
+  test 'should downcase case insensitive keys that refer to virtual attributes when saving' do
+    email        = 'Foo at Bar1.com'
+    confirmation = 'Foo at Bar1.com'
+    attributes   = valid_attributes(email: email, email_confirmation: confirmation)
+    user = UserWithVirtualAttributes.new(attributes)
+
+    assert_equal confirmation, user.email_confirmation
+    user.save!
+    assert_equal confirmation.downcase, user.email_confirmation
+  end
+
+  test 'should not mutate value assigned to case insensitive key' do
+    email          = 'Foo at Bar.com'
+    original_email = email.dup
+    user           = new_user(email: email)
+
+    user.save!
+    assert_equal original_email, email
+  end
+
+  test 'should remove whitespace from strip whitespace keys when saving' do
+    # strip_whitespace_keys is set to :email by default.
+    email = ' foo at bar.com '
+    user = new_user(email: email)
+
+    assert_equal email, user.email
+    user.save!
+    assert_equal email.strip, user.email
+  end
+
+  test 'should not mutate value assigned to string whitespace key' do
+    email          = ' foo at bar.com '
+    original_email = email.dup
+    user           = new_user(email: email)
+
+    user.save!
+    assert_equal original_email, email
+  end
+
+  test "doesn't throw exception when globally configured strip_whitespace_keys are not present on a model" do
+    swap Devise, strip_whitespace_keys: [:fake_key] do
+      assert_nothing_raised { create_user }
+    end
+  end
+
+  test "doesn't throw exception when globally configured case_insensitive_keys are not present on a model" do
+    swap Devise, case_insensitive_keys: [:fake_key] do
+      assert_nothing_raised { create_user }
+    end
+  end
+
+  test "param filter should not convert booleans and integer to strings" do
+    conditions = { "login" => "foo at bar.com", "bool1" => true, "bool2" => false, "fixnum" => 123, "will_be_converted" => (1..10) }
+    conditions = Devise::ParameterFilter.new([], []).filter(conditions)
+    assert_equal( { "login" => "foo at 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)
+    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)
+    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
+    user = new_user
+    assert user.respond_to?(:password)
+    assert user.respond_to?(:password_confirmation)
+  end
+
+  test 'should generate encrypted password while setting password' do
+    user = new_user
+    assert_present user.encrypted_password
+  end
+
+  test 'should support custom encryption methods' do
+    user = UserWithCustomEncryption.new(password: '654321')
+    assert_equal user.encrypted_password, '123456'
+  end
+
+  test 'allow authenticatable_salt to work even with nil encrypted password' do
+    user = User.new
+    user.encrypted_password = nil
+    assert_nil user.authenticatable_salt
+  end
+
+  test 'should not generate encrypted password if password is blank' do
+    assert_blank new_user(password: nil).encrypted_password
+    assert_blank new_user(password: '').encrypted_password
+  end
+
+  test 'should encrypt password again if password has changed' do
+    user = create_user
+    encrypted_password = user.encrypted_password
+    user.password = user.password_confirmation = 'new_password'
+    user.save!
+    assert_not_equal encrypted_password, user.encrypted_password
+  end
+
+  test 'should test for a valid password' do
+    user = create_user
+    assert user.valid_password?('12345678')
+    assert_not user.valid_password?('654321')
+  end
+
+  test 'should not raise error with an empty password' do
+    user = create_user
+    user.encrypted_password = ''
+    assert_nothing_raised { user.valid_password?('12345678') }
+  end
+
+  test 'should be an invalid password if the user has an empty password' do
+    user = create_user
+    user.encrypted_password = ''
+    assert_not user.valid_password?('654321')
+  end
+
+  test 'should respond to current password' do
+    assert new_user.respond_to?(:current_password)
+  end
+
+  test 'should update password with valid current password' do
+    user = create_user
+    assert user.update_with_password(current_password: '12345678',
+      password: 'pass4321', password_confirmation: 'pass4321')
+    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',
+      password: 'pass4321', password_confirmation: 'pass4321')
+    assert user.reload.valid_password?('12345678')
+    assert_match "is invalid", user.errors[:current_password].join
+  end
+
+  test 'should add an error to current password when it is blank' do
+    user = create_user
+    assert_not user.update_with_password(password: 'pass4321',
+      password_confirmation: 'pass4321')
+    assert user.reload.valid_password?('12345678')
+    assert_match "can't be blank", user.errors[:current_password].join
+  end
+
+  test 'should run validations even when current password is invalid or blank' do
+    user = UserWithValidation.create!(valid_attributes)
+    user.save
+    assert user.persisted?
+    assert_not user.update_with_password(username: "")
+    assert_match "usertest", user.reload.username
+    assert_match "can't be blank", user.errors[:username].join
+  end
+
+  test 'should ignore password and its confirmation if they are blank' do
+    user = create_user
+    assert user.update_with_password(current_password: '12345678', email: "new at example.com")
+    assert_equal "new at example.com", user.email
+  end
+
+  test 'should not update password with invalid confirmation' do
+    user = create_user
+    assert_not user.update_with_password(current_password: '12345678',
+      password: 'pass4321', password_confirmation: 'other')
+    assert user.reload.valid_password?('12345678')
+  end
+
+  test 'should clean up password fields on failure' do
+    user = create_user
+    assert_not user.update_with_password(current_password: '12345678',
+      password: 'pass4321', password_confirmation: 'other')
+    assert user.password.blank?
+    assert user.password_confirmation.blank?
+  end
+
+  test 'should update the user without password' do
+    user = create_user
+    user.update_without_password(email: 'new at example.com')
+    assert_equal 'new at 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')
+    assert !user.reload.valid_password?('pass4321')
+    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.create(email: "HEllO at example.com", password: "123456")
+    user = User.create(email: "HEllO at example.com", password: "123456")
+    assert !user.valid?
+  end
+
+  test 'required_fields should be encryptable_password and the email field by default' do
+    assert_same_content Devise::Models::DatabaseAuthenticatable.required_fields(User), [
+      :email,
+      :encrypted_password
+    ]
+  end
+
+  test 'required_fields should be encryptable_password and the login when the login is on authentication_keys' do
+    swap Devise, authentication_keys: [:login] do
+      assert_same_content Devise::Models::DatabaseAuthenticatable.required_fields(User), [
+        :encrypted_password,
+        :login
+      ]
+    end
+  end
+end
diff --git a/test/models/lockable_test.rb b/test/models/lockable_test.rb
new file mode 100644
index 0000000..3f7284c
--- /dev/null
+++ b/test/models/lockable_test.rb
@@ -0,0 +1,328 @@
+require 'test_helper'
+
+class LockableTest < ActiveSupport::TestCase
+  def setup
+    setup_mailer
+  end
+
+  test "should respect maximum attempts configuration" do
+    user = create_user
+    user.confirm!
+    swap Devise, maximum_attempts: 2 do
+      2.times { user.valid_for_authentication?{ false } }
+      assert user.reload.access_locked?
+    end
+  end
+
+  test "should increment failed_attempts on successfull validation if the user is already locked" do
+    user = create_user
+    user.confirm!
+
+    swap Devise, maximum_attempts: 2 do
+      2.times { user.valid_for_authentication?{ false } }
+      assert user.reload.access_locked?
+    end
+
+    user.valid_for_authentication?{ true }
+    assert_equal 3, user.reload.failed_attempts
+  end
+
+  test "should not touch failed_attempts if lock_strategy is none" do
+    user = create_user
+    user.confirm!
+    swap Devise, lock_strategy: :none, maximum_attempts: 2 do
+      3.times { user.valid_for_authentication?{ false } }
+      assert !user.access_locked?
+      assert_equal 0, user.failed_attempts
+    end
+  end
+
+  test 'should be valid for authentication with a unlocked user' do
+    user = create_user
+    user.lock_access!
+    user.unlock_access!
+    assert user.valid_for_authentication?{ true }
+  end
+
+  test "should verify whether a user is locked or not" do
+    user = create_user
+    assert_not user.access_locked?
+    user.lock_access!
+    assert user.access_locked?
+  end
+
+  test "active_for_authentication? should be the opposite of locked?" do
+    user = create_user
+    user.confirm!
+    assert user.active_for_authentication?
+    user.lock_access!
+    assert_not user.active_for_authentication?
+  end
+
+  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
+    assert_not_nil user.reload.unlock_token
+
+    user.unlock_access!
+    assert_nil user.reload.locked_at
+    assert_nil user.reload.unlock_token
+    assert_equal 0, user.reload.failed_attempts
+  end
+
+  test "new user should not be locked and should have zero failed_attempts" do
+    assert_not new_user.access_locked?
+    assert_equal 0, create_user.failed_attempts
+  end
+
+  test "should unlock user after unlock_in period" do
+    swap Devise, unlock_in: 3.hours do
+      user = new_user
+      user.locked_at = 2.hours.ago
+      assert user.access_locked?
+
+      Devise.unlock_in = 1.hour
+      assert_not user.access_locked?
+    end
+  end
+
+  test "should not unlock in 'unlock_in' if :time unlock strategy is not set" do
+    swap Devise, unlock_strategy: :email do
+      user = new_user
+      user.locked_at = 2.hours.ago
+      assert user.access_locked?
+    end
+  end
+
+  test "should set unlock_token when locking" do
+    user = create_user
+    assert_nil user.unlock_token
+    user.lock_access!
+    assert_not_nil user.unlock_token
+  end
+
+  test "should never generate the same unlock token for different users" do
+    unlock_tokens = []
+    3.times do
+      user = create_user
+      user.lock_access!
+      token = user.unlock_token
+      assert !unlock_tokens.include?(token)
+      unlock_tokens << token
+    end
+  end
+
+  test "should not generate unlock_token when :email is not an unlock strategy" do
+    swap Devise, unlock_strategy: :time do
+      user = create_user
+      user.lock_access!
+      assert_nil user.unlock_token
+    end
+  end
+
+  test "should send email with unlock instructions when :email is an unlock strategy" do
+    swap Devise, unlock_strategy: :email do
+      user = create_user
+      assert_email_sent do
+        user.lock_access!
+      end
+    end
+  end
+
+  test "doesn't send email when you pass option send_instructions to false" do
+    swap Devise, unlock_strategy: :email do
+      user = create_user
+      assert_email_not_sent do
+        user.lock_access! send_instructions: false
+      end
+    end
+  end
+
+  test "sends email when you pass options other than send_instructions" do
+    swap Devise, unlock_strategy: :email do
+      user = create_user
+      assert_email_sent do
+        user.lock_access! foo: :bar, bar: :foo
+      end
+    end
+  end
+
+  test "should not send email with unlock instructions when :email is not an unlock strategy" do
+    swap Devise, unlock_strategy: :time do
+      user = create_user
+      assert_email_not_sent do
+        user.lock_access!
+      end
+    end
+  end
+
+  test 'should find and unlock a user automatically based on raw token' do
+    user = create_user
+    raw  = user.send_unlock_instructions
+    locked_user = User.unlock_access_by_token(raw)
+    assert_equal locked_user, user
+    assert_not user.reload.access_locked?
+  end
+
+  test 'should return a new record with errors when a invalid token is given' do
+    locked_user = User.unlock_access_by_token('invalid_token')
+    assert_not locked_user.persisted?
+    assert_equal "is invalid", locked_user.errors[:unlock_token].join
+  end
+
+  test 'should return a new record with errors when a blank token is given' do
+    locked_user = User.unlock_access_by_token('')
+    assert_not locked_user.persisted?
+    assert_equal "can't be blank", locked_user.errors[:unlock_token].join
+  end
+
+  test 'should find a user to send unlock instructions' do
+    user = create_user
+    user.lock_access!
+    unlock_user = User.send_unlock_instructions(email: user.email)
+    assert_equal unlock_user, user
+  end
+
+  test 'should return a new user if no email was found' do
+    unlock_user = User.send_unlock_instructions(email: "invalid at example.com")
+    assert_not unlock_user.persisted?
+  end
+
+  test 'should add error to new user email if no email was found' do
+    unlock_user = User.send_unlock_instructions(email: "invalid at example.com")
+    assert_equal 'not found', unlock_user.errors[:email].join
+  end
+
+  test 'should find a user to send unlock instructions by authentication_keys' do
+    swap Devise, authentication_keys: [:username, :email] do
+      user = create_user
+      unlock_user = User.send_unlock_instructions(email: user.email, username: user.username)
+      assert_equal unlock_user, user
+    end
+  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
+  end
+
+  test 'should not be able to send instructions if the user is not locked' do
+    user = create_user
+    assert_not user.resend_unlock_instructions
+    assert_not user.access_locked?
+    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_instructions
+      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
+      user.confirm!
+
+      user.failed_attempts = 2
+      user.locked_at = 2.minutes.ago
+
+      user.valid_for_authentication? { false }
+      assert_equal 1, user.failed_attempts
+    end
+  end
+
+  test 'should unlock account if lock has expired on success' do
+    swap Devise, unlock_in: 1.minute do
+      user = create_user
+      user.confirm!
+
+      user.failed_attempts = 2
+      user.locked_at = 2.minutes.ago
+
+      user.valid_for_authentication? { true }
+      assert_equal 0, user.failed_attempts
+      assert_nil user.locked_at
+    end
+  end
+
+  test 'required_fields should contain the all the fields when all the strategies are enabled' do
+    swap Devise, unlock_strategy: :both do
+      swap Devise, lock_strategy: :failed_attempts do
+        assert_same_content Devise::Models::Lockable.required_fields(User), [
+         :failed_attempts,
+         :locked_at,
+         :unlock_token
+        ]
+      end
+    end
+  end
+
+  test 'required_fields should contain only failed_attempts and locked_at when the strategies are time and failed_attempts are enabled' do
+    swap Devise, unlock_strategy: :time do
+      swap Devise, lock_strategy: :failed_attempts do
+        assert_same_content Devise::Models::Lockable.required_fields(User), [
+         :failed_attempts,
+         :locked_at
+        ]
+      end
+    end
+  end
+
+  test 'required_fields should contain only failed_attempts and unlock_token when the strategies are token and failed_attempts are enabled' do
+    swap Devise, unlock_strategy: :email do
+      swap Devise, lock_strategy: :failed_attempts do
+        assert_same_content Devise::Models::Lockable.required_fields(User), [
+         :failed_attempts,
+         :unlock_token
+        ]
+      end
+    end
+  end
+
+  test 'should not return a locked unauthenticated message if in paranoid mode' do
+    swap Devise, paranoid: :true do
+      user = create_user
+      user.failed_attempts = Devise.maximum_attempts + 1
+      user.lock_access!
+
+      assert_equal :invalid, user.unauthenticated_message
+    end
+  end
+
+  test 'should return last attempt message if user made next-to-last attempt of password entering' do
+    swap Devise, last_attempt_warning: true, lock_strategy: :failed_attempts do
+      user = create_user
+      user.failed_attempts = Devise.maximum_attempts - 2
+      assert_equal :invalid, user.unauthenticated_message
+
+      user.failed_attempts = Devise.maximum_attempts - 1
+      assert_equal :last_attempt, user.unauthenticated_message
+
+      user.failed_attempts = Devise.maximum_attempts
+      assert_equal :locked, user.unauthenticated_message
+    end
+  end
+
+  test 'should not return last attempt message if last_attempt_warning is disabled' do
+    swap Devise, last_attempt_warning: false, lock_strategy: :failed_attempts do
+      user = create_user
+      user.failed_attempts = Devise.maximum_attempts - 1
+      assert_equal :invalid, user.unauthenticated_message
+    end
+  end
+
+  test 'should return locked message if user was programatically locked' do
+    user = create_user
+    user.lock_access!
+    assert_equal :locked, user.unauthenticated_message
+  end
+end
diff --git a/test/models/omniauthable_test.rb b/test/models/omniauthable_test.rb
new file mode 100644
index 0000000..13a89a5
--- /dev/null
+++ b/test/models/omniauthable_test.rb
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class OmniauthableTest < ActiveSupport::TestCase
+  test 'required_fields should contain the fields that Devise uses' do
+    assert_same_content Devise::Models::Omniauthable.required_fields(User), []
+  end
+end
diff --git a/test/models/recoverable_test.rb b/test/models/recoverable_test.rb
new file mode 100644
index 0000000..d4548ed
--- /dev/null
+++ b/test/models/recoverable_test.rb
@@ -0,0 +1,196 @@
+require 'test_helper'
+
+class RecoverableTest < ActiveSupport::TestCase
+
+  def setup
+    setup_mailer
+  end
+
+  test 'should not generate reset password token after creating a record' do
+    assert_nil new_user.reset_password_token
+  end
+
+  test 'should never generate the same reset password token for different users' do
+    reset_password_tokens = []
+    3.times do
+      user = create_user
+      user.send_reset_password_instructions
+      token = user.reset_password_token
+      assert !reset_password_tokens.include?(token)
+      reset_password_tokens << token
+    end
+  end
+
+  test 'should reset password and password confirmation from params' do
+    user = create_user
+    user.reset_password!('123456789', '987654321')
+    assert_equal '123456789', user.password
+    assert_equal '987654321', user.password_confirmation
+  end
+
+  test 'should reset password and save the record' do
+    assert create_user.reset_password!('123456789', '123456789')
+  end
+
+  test 'should clear reset password token while reseting the password' do
+    user = create_user
+    assert_nil user.reset_password_token
+
+    user.send_reset_password_instructions
+    assert_present user.reset_password_token
+    assert user.reset_password!('123456789', '123456789')
+    assert_nil user.reset_password_token
+  end
+
+  test 'should not clear reset password token if record is invalid' do
+    user = create_user
+    user.send_reset_password_instructions
+    assert_present user.reset_password_token
+    assert_not user.reset_password!('123456789', '987654321')
+    assert_present user.reset_password_token
+  end
+
+  test 'should not reset password with invalid data' do
+    user = create_user
+    user.stubs(:valid?).returns(false)
+    assert_not user.reset_password!('123456789', '987654321')
+  end
+
+  test 'should reset reset password token and send instructions by email' do
+    user = create_user
+    assert_email_sent do
+      token = user.reset_password_token
+      user.send_reset_password_instructions
+      assert_not_equal token, user.reset_password_token
+    end
+  end
+
+  test 'should find a user to send instructions by email' do
+    user = create_user
+    reset_password_user = User.send_reset_password_instructions(email: user.email)
+    assert_equal reset_password_user, user
+  end
+
+  test 'should return a new record with errors if user was not found by e-mail' do
+    reset_password_user = User.send_reset_password_instructions(email: "invalid at example.com")
+    assert_not reset_password_user.persisted?
+    assert_equal "not found", reset_password_user.errors[:email].join
+  end
+
+  test 'should find a user to send instructions by authentication_keys' do
+    swap Devise, authentication_keys: [:username, :email] do
+      user = create_user
+      reset_password_user = User.send_reset_password_instructions(email: user.email, username: user.username)
+      assert_equal reset_password_user, user
+    end
+  end
+
+  test 'should require all reset_password_keys' do
+      swap Devise, reset_password_keys: [:username, :email] do
+          user = create_user
+          reset_password_user = User.send_reset_password_instructions(email: user.email)
+          assert_not reset_password_user.persisted?
+          assert_equal "can't be blank", reset_password_user.errors[:username].join
+      end
+  end
+
+  test 'should reset reset_password_token before send the reset instructions email' do
+    user = create_user
+    token = user.reset_password_token
+    User.send_reset_password_instructions(email: user.email)
+    assert_not_equal token, user.reload.reset_password_token
+  end
+
+  test 'should send email instructions to the user reset their password' do
+    user = create_user
+    assert_email_sent do
+      User.send_reset_password_instructions(email: user.email)
+    end
+  end
+
+  test 'should find a user to reset their password based on the raw token' do
+    user = create_user
+    raw  = user.send_reset_password_instructions
+
+    reset_password_user = User.reset_password_by_token(reset_password_token: raw)
+    assert_equal reset_password_user, user
+  end
+
+  test 'should return a new record with errors if no reset_password_token is found' do
+    reset_password_user = User.reset_password_by_token(reset_password_token: 'invalid_token')
+    assert_not reset_password_user.persisted?
+    assert_equal "is invalid", reset_password_user.errors[:reset_password_token].join
+  end
+
+  test 'should return a new record with errors if reset_password_token is blank' do
+    reset_password_user = User.reset_password_by_token(reset_password_token: '')
+    assert_not reset_password_user.persisted?
+    assert_match "can't be blank", reset_password_user.errors[:reset_password_token].join
+  end
+
+  test 'should return a new record with errors if password is blank' do
+    user = create_user
+    raw  = user.send_reset_password_instructions
+
+    reset_password_user = User.reset_password_by_token(reset_password_token: raw, password: '')
+    assert_not reset_password_user.errors.empty?
+    assert_match "can't be blank", reset_password_user.errors[:password].join
+  end
+
+  test 'should reset successfully user password given the new password and confirmation' do
+    user = create_user
+    old_password = user.password
+    raw  = user.send_reset_password_instructions
+
+    User.reset_password_by_token(
+      reset_password_token: raw,
+      password: 'new_password',
+      password_confirmation: 'new_password'
+    )
+    user.reload
+
+    assert_not user.valid_password?(old_password)
+    assert user.valid_password?('new_password')
+  end
+
+  test 'should not reset password after reset_password_within time' do
+    swap Devise, reset_password_within: 1.hour do
+      user = create_user
+      raw  = user.send_reset_password_instructions
+
+      old_password = user.password
+      user.reset_password_sent_at = 2.days.ago
+      user.save!
+
+      reset_password_user = User.reset_password_by_token(
+        reset_password_token: raw,
+        password: 'new_password',
+        password_confirmation: 'new_password'
+      )
+      user.reload
+
+      assert user.valid_password?(old_password)
+      assert_not user.valid_password?('new_password')
+      assert_equal "has expired, please request a new one", reset_password_user.errors[:reset_password_token].join
+    end
+  end
+
+  test 'required_fields should contain the fields that Devise uses' do
+    assert_same_content Devise::Models::Recoverable.required_fields(User), [
+      :reset_password_sent_at,
+      :reset_password_token
+    ]
+  end
+
+  test 'should return a user based on the raw token' do
+    user = create_user
+    raw  = user.send_reset_password_instructions
+
+    assert_equal User.with_reset_password_token(raw), user
+  end
+
+  test 'should return nil if a user based on the raw token is not found' do
+    assert_equal User.with_reset_password_token('random-token'), nil
+  end
+
+end
diff --git a/test/models/registerable_test.rb b/test/models/registerable_test.rb
new file mode 100644
index 0000000..fe15728
--- /dev/null
+++ b/test/models/registerable_test.rb
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class RegisterableTest < ActiveSupport::TestCase
+  test 'required_fields should contain the fields that Devise uses' do
+    assert_same_content Devise::Models::Registerable.required_fields(User), []
+  end
+end
diff --git a/test/models/rememberable_test.rb b/test/models/rememberable_test.rb
new file mode 100644
index 0000000..aec1fe7
--- /dev/null
+++ b/test/models/rememberable_test.rb
@@ -0,0 +1,198 @@
+require 'test_helper'
+
+class RememberableTest < ActiveSupport::TestCase
+  def resource_class
+    User
+  end
+
+  def create_resource
+    create_user
+  end
+
+  test 'remember_me should not generate a new token if using salt' do
+    user = create_user
+    user.expects(:valid?).never
+    user.remember_me!
+  end
+
+  test 'forget_me should not clear remember token if using salt' do
+    user = create_user
+    user.remember_me!
+    user.expects(:valid?).never
+    user.forget_me!
+  end
+
+  test 'can generate remember token' do
+    user = create_user
+    user.singleton_class.send(:attr_accessor, :remember_token)
+    User.to_adapter.expects(:find_first).returns(nil)
+    user.remember_me!
+    assert user.remember_token
+  end
+
+  test 'serialize into cookie' do
+    user = create_user
+    user.remember_me!
+    assert_equal [user.to_key, user.authenticatable_salt], User.serialize_into_cookie(user)
+  end
+
+  test 'serialize from cookie' do
+    user = create_user
+    user.remember_me!
+    assert_equal user, User.serialize_from_cookie(user.to_key, user.authenticatable_salt)
+  end
+
+  test 'raises a RuntimeError if authenticatable_salt is nil' do
+    user = User.new
+    user.encrypted_password = nil
+    assert_raise RuntimeError do
+      user.rememberable_value
+    end
+  end
+
+  test 'should respond to remember_me attribute' do
+    assert resource_class.new.respond_to?(:remember_me)
+    assert resource_class.new.respond_to?(:remember_me=)
+  end
+
+  test 'forget_me should clear remember_created_at if expire_all_remember_me_on_sign_out is true' do
+    swap Devise, expire_all_remember_me_on_sign_out: true do
+      resource = create_resource
+      resource.remember_me!
+      assert_not_nil resource.remember_created_at
+
+      resource.forget_me!
+      assert_nil resource.remember_created_at
+    end
+  end
+
+  test 'forget_me should not clear remember_created_at if expire_all_remember_me_on_sign_out is false' do
+    swap Devise, expire_all_remember_me_on_sign_out: false do
+      resource = create_resource
+      resource.remember_me!
+
+      assert_not_nil resource.remember_created_at
+
+      resource.forget_me!
+      assert_not_nil resource.remember_created_at
+    end
+  end
+
+  test 'forget_me should not try to update resource if it has been destroyed' do
+    resource = create_resource
+    resource.expects(:remember_created_at).never
+    resource.expects(:save).never
+
+    resource.destroy
+    resource.forget_me!
+  end
+
+  test 'remember is expired if not created at timestamp is set' do
+    assert create_resource.remember_expired?
+  end
+
+  test 'serialize should return nil if no resource is found' do
+    assert_nil resource_class.serialize_from_cookie([0], "123")
+  end
+
+  test 'remember me return nil if is a valid resource with invalid token' do
+    resource = create_resource
+    assert_nil resource_class.serialize_from_cookie([resource.id], "123")
+  end
+
+  test 'remember for should fallback to devise remember for default configuration' do
+    swap Devise, remember_for: 1.day do
+      resource = create_resource
+      resource.remember_me!
+      assert_not resource.remember_expired?
+    end
+  end
+
+  test 'remember expires at should sum date of creation with remember for configuration' do
+    swap Devise, remember_for: 3.days do
+      resource = create_resource
+      resource.remember_me!
+      assert_equal 3.days.from_now.to_date, resource.remember_expires_at.to_date
+
+      Devise.remember_for = 5.days
+      assert_equal 5.days.from_now.to_date, resource.remember_expires_at.to_date
+    end
+  end
+
+  test 'remember should be expired if remember_for is zero' do
+    swap Devise, remember_for: 0.days do
+      Devise.remember_for = 0.days
+      resource = create_resource
+      resource.remember_me!
+      assert resource.remember_expired?
+    end
+  end
+
+  test 'remember should be expired if it was created before limit time' do
+    swap Devise, remember_for: 1.day do
+      resource = create_resource
+      resource.remember_me!
+      resource.remember_created_at = 2.days.ago
+      resource.save
+      assert resource.remember_expired?
+    end
+  end
+
+  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!
+      resource.remember_created_at = (30.days.ago + 2.minutes)
+      resource.save
+      assert_not resource.remember_expired?
+    end
+  end
+
+  test 'if extend_remember_period is false, remember_me! should generate a new timestamp if expired' do
+    swap Devise, remember_for: 5.minutes do
+      resource = create_resource
+      resource.remember_me!(false)
+      assert resource.remember_created_at
+
+      resource.remember_created_at = old = 10.minutes.ago
+      resource.save
+
+      resource.remember_me!(false)
+      assert_not_equal old.to_i, resource.remember_created_at.to_i
+    end
+  end
+
+  test 'if extend_remember_period is false, remember_me! should not generate a new timestamp' do
+    swap Devise, remember_for: 1.year do
+      resource = create_resource
+      resource.remember_me!(false)
+      assert resource.remember_created_at
+
+      resource.remember_created_at = old = 10.minutes.ago.utc
+      resource.save
+
+      resource.remember_me!(false)
+      assert_equal old.to_i, resource.remember_created_at.to_i
+    end
+  end
+
+  test 'if extend_remember_period is true, remember_me! should always generate a new timestamp' do
+    swap Devise, remember_for: 1.year do
+      resource = create_resource
+      resource.remember_me!(true)
+      assert resource.remember_created_at
+
+      resource.remember_created_at = old = 10.minutes.ago
+      resource.save
+
+      resource.remember_me!(true)
+      assert_not_equal old, resource.remember_created_at
+    end
+  end
+
+  test 'should have the required_fields array' do
+    assert_same_content Devise::Models::Rememberable.required_fields(User), [
+      :remember_created_at
+    ]
+  end
+end
diff --git a/test/models/serializable_test.rb b/test/models/serializable_test.rb
new file mode 100644
index 0000000..7e16f74
--- /dev/null
+++ b/test/models/serializable_test.rb
@@ -0,0 +1,49 @@
+require 'test_helper'
+
+class SerializableTest < ActiveSupport::TestCase
+  setup do
+    @user = create_user
+  end
+
+  test 'should not include unsafe keys on XML' do
+    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))
+  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))
+  end
+
+  test 'should not include unsafe keys on JSON' do
+    keys = from_json().keys.select{ |key| !key.include?("id") }
+    assert_equal %w(created_at email facebook_token updated_at username), keys.sort
+  end
+
+  test 'should not include unsafe keys on JSON even if a new except is provided' do
+    assert_no_key "email", from_json(except: :email)
+    assert_no_key "confirmation_token", from_json(except: :email)
+  end
+
+  test 'should include unsafe keys on JSON if a force_except is provided' do
+    assert_no_key "email", from_json(force_except: :email)
+    assert_key "confirmation_token", from_json(force_except: :email)
+  end
+
+  def assert_key(key, subject)
+    assert subject.key?(key), "Expected #{subject.inspect} to have key #{key.inspect}"
+  end
+
+  def assert_no_key(key, subject)
+    assert !subject.key?(key), "Expected #{subject.inspect} to not have key #{key.inspect}"
+  end
+
+  def from_json(options=nil)
+    ActiveSupport::JSON.decode(@user.to_json(options))["user"]
+  end
+end
diff --git a/test/models/timeoutable_test.rb b/test/models/timeoutable_test.rb
new file mode 100644
index 0000000..be68246
--- /dev/null
+++ b/test/models/timeoutable_test.rb
@@ -0,0 +1,51 @@
+require 'test_helper'
+
+class TimeoutableTest < ActiveSupport::TestCase
+
+  test 'should be expired' do
+    assert new_user.timedout?(31.minutes.ago)
+  end
+
+  test 'should not be expired' do
+    assert_not new_user.timedout?(29.minutes.ago)
+  end
+
+  test 'should not be expired when params is nil' do
+    assert_not new_user.timedout?(nil)
+  end
+
+  test 'should use timeout_in method' do
+    user = new_user
+    user.instance_eval { def timeout_in; 10.minutes end }
+
+    assert user.timedout?(12.minutes.ago)
+    assert_not user.timedout?(8.minutes.ago)
+  end
+
+  test 'should not be expired when timeout_in method returns nil' do
+    user = new_user
+    user.instance_eval { def timeout_in; nil end }
+    assert_not user.timedout?(10.hours.ago)
+  end
+
+  test 'fallback to Devise config option' do
+    swap Devise, timeout_in: 1.minute do
+      user = new_user
+      assert user.timedout?(2.minutes.ago)
+      assert_not user.timedout?(30.seconds.ago)
+
+      Devise.timeout_in = 5.minutes
+      assert_not user.timedout?(2.minutes.ago)
+      assert user.timedout?(6.minutes.ago)
+    end
+  end
+
+  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
diff --git a/test/models/trackable_test.rb b/test/models/trackable_test.rb
new file mode 100644
index 0000000..c63682f
--- /dev/null
+++ b/test/models/trackable_test.rb
@@ -0,0 +1,41 @@
+require 'test_helper'
+
+class TrackableTest < ActiveSupport::TestCase
+  test 'required_fields should contain the fields that Devise uses' do
+    assert_same_content Devise::Models::Trackable.required_fields(User), [
+      :current_sign_in_at,
+      :current_sign_in_ip,
+      :last_sign_in_at,
+      :last_sign_in_ip,
+      :sign_in_count
+    ]
+  end
+
+  test 'update_tracked_fields should only set attributes but not save the record' do
+    user = create_user
+    request = mock
+    request.stubs(:remote_ip).returns("127.0.0.1")
+
+    assert_nil user.current_sign_in_ip
+    assert_nil user.last_sign_in_ip
+    assert_nil user.current_sign_in_at
+    assert_nil user.last_sign_in_at
+    assert_equal 0, user.sign_in_count
+
+    user.update_tracked_fields(request)
+
+    assert_equal "127.0.0.1", user.current_sign_in_ip
+    assert_equal "127.0.0.1", user.last_sign_in_ip
+    assert_not_nil user.current_sign_in_at
+    assert_not_nil user.last_sign_in_at
+    assert_equal 1, user.sign_in_count
+
+    user.reload
+
+    assert_nil user.current_sign_in_ip
+    assert_nil user.last_sign_in_ip
+    assert_nil user.current_sign_in_at
+    assert_nil user.last_sign_in_at
+    assert_equal 0, user.sign_in_count
+  end
+end
diff --git a/test/models/validatable_test.rb b/test/models/validatable_test.rb
new file mode 100644
index 0000000..c8dc687
--- /dev/null
+++ b/test/models/validatable_test.rb
@@ -0,0 +1,127 @@
+# encoding: UTF-8
+require 'test_helper'
+
+class ValidatableTest < ActiveSupport::TestCase
+  test 'should require email to be set' do
+    user = new_user(email: nil)
+    assert user.invalid?
+    assert user.errors[:email]
+    assert_equal 'can\'t be blank', user.errors[:email].join
+  end
+
+  test 'should require uniqueness of email if email has changed, allowing blank' do
+    existing_user = create_user
+
+    user = new_user(email: '')
+    assert user.invalid?
+    assert_no_match(/taken/, user.errors[:email].join)
+
+    user.email = existing_user.email
+    assert user.invalid?
+    assert_match(/taken/, user.errors[:email].join)
+
+    user.save(validate: false)
+    assert user.valid?
+  end
+
+  test 'should require correct email format if email has changed, allowing blank' do
+    user = new_user(email: '')
+    assert user.invalid?
+    assert_not_equal 'is invalid', user.errors[:email].join
+
+    %w{invalid_email_format 123 $$$ () ☃ bla at bla.}.each do |email|
+      user.email = email
+      assert user.invalid?, 'should be invalid with email ' << email
+      assert_equal 'is invalid', user.errors[:email].join
+    end
+
+    user.save(validate: false)
+    assert user.valid?
+  end
+
+  test 'should accept valid emails' do
+    %w(a.b.c at example.com test_mail at gmail.com any at any.net email at test.br 123 at mail.test 1☃3 at mail.test).each do |email|
+      user = new_user(email: email)
+      assert user.valid?, 'should be valid with email ' << email
+      assert_blank user.errors[:email]
+    end
+  end
+
+  test 'should require password to be set when creating a new record' do
+    user = new_user(password: '', password_confirmation: '')
+    assert user.invalid?
+    assert_equal 'can\'t be blank', user.errors[:password].join
+  end
+
+  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
+  end
+
+  test 'should require password when updating/resetting password' do
+    user = create_user
+
+    user.password = ''
+    user.password_confirmation = ''
+
+    assert user.invalid?
+    assert_equal 'can\'t be blank', user.errors[:password].join
+  end
+
+  test 'should require confirmation when updating/resetting password' do
+    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
+  end
+
+  test 'should require a password with minimum of 7 characters' do
+    user = new_user(password: '12345', password_confirmation: '12345')
+    assert user.invalid?
+    assert_equal 'is too short (minimum is 7 characters)', user.errors[:password].join
+  end
+
+  test 'should require a password with maximum of 128 characters long' do
+    user = new_user(password: 'x'*129, password_confirmation: 'x'*129)
+    assert user.invalid?
+    assert_equal 'is too long (maximum is 128 characters)', user.errors[:password].join
+  end
+
+  test 'should not require password length when it\'s not changed' do
+    user = create_user.reload
+    user.password = user.password_confirmation = nil
+    assert user.valid?
+
+    user.password_confirmation = 'confirmation'
+    assert user.invalid?
+    assert_not (user.errors[:password].join =~ /is too long/)
+  end
+
+  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?
+    assert_equal 'is too long (maximum is 128 characters)', user.errors[:password].join
+  end
+
+  test 'should not be included in objects with invalid API' do
+    assert_raise RuntimeError do
+      Class.new.send :include, Devise::Models::Validatable
+    end
+  end
+
+  test 'required_fields should be an empty array' do
+    assert_equal Devise::Models::Validatable.required_fields(User), []
+  end
+end
diff --git a/test/models_test.rb b/test/models_test.rb
new file mode 100644
index 0000000..a5f13b4
--- /dev/null
+++ b/test/models_test.rb
@@ -0,0 +1,144 @@
+require 'test_helper'
+require 'test_models'
+
+class ActiveRecordTest < ActiveSupport::TestCase
+  def include_module?(klass, mod)
+    klass.devise_modules.include?(mod) &&
+      klass.included_modules.include?(Devise::Models::const_get(mod.to_s.classify))
+  end
+
+  def assert_include_modules(klass, *modules)
+    modules.each do |mod|
+      assert include_module?(klass, mod)
+    end
+
+    (Devise::ALL - modules).each do |mod|
+      assert_not include_module?(klass, mod)
+    end
+  end
+
+  test 'can cherry pick modules' do
+    assert_include_modules Admin, :database_authenticatable, :registerable, :timeoutable, :recoverable, :lockable, :confirmable
+  end
+
+  test 'validations options are not applied too late' do
+    validators = WithValidation.validators_on :password
+    length = validators.find { |v| v.kind == :length }
+    assert_equal 2, length.options[:minimum]
+    assert_equal 6, length.options[:maximum]
+  end
+
+  test 'validations are applied just once' do
+    validators = Several.validators_on :password
+    assert_equal 1, validators.select{ |v| v.kind == :length }.length
+  end
+
+  test 'chosen modules are inheritable' do
+    assert_include_modules Inheritable, :database_authenticatable, :registerable, :timeoutable, :recoverable, :lockable, :confirmable
+  end
+
+  test 'order of module inclusion' do
+    correct_module_order   = [:database_authenticatable, :recoverable, :registerable, :confirmable, :lockable, :timeoutable]
+    incorrect_module_order = [:database_authenticatable, :timeoutable, :registerable, :recoverable, :lockable, :confirmable]
+
+    assert_include_modules Admin, *incorrect_module_order
+
+    # get module constants from symbol list
+    module_constants = correct_module_order.collect { |mod| Devise::Models::const_get(mod.to_s.classify) }
+
+    # confirm that they adhere to the order in ALL
+    # get included modules, filter out the noise, and reverse the order
+    assert_equal module_constants, (Admin.included_modules & module_constants).reverse
+  end
+
+  test 'raise error on invalid module' do
+    assert_raise NameError do
+      # Mix valid an invalid modules.
+      Configurable.class_eval { devise :database_authenticatable, :doesnotexit }
+    end
+  end
+
+  test 'set a default value for stretches' do
+    assert_equal 15, Configurable.stretches
+  end
+
+  test 'set a default value for pepper' do
+    assert_equal 'abcdef', Configurable.pepper
+  end
+
+  test 'set a default value for allow_unconfirmed_access_for' do
+    assert_equal 5.days, Configurable.allow_unconfirmed_access_for
+  end
+
+  test 'set a default value for remember_for' do
+    assert_equal 7.days, Configurable.remember_for
+  end
+
+  test 'set a default value for timeout_in' do
+    assert_equal 15.minutes, Configurable.timeout_in
+  end
+
+  test 'set a default value for unlock_in' do
+    assert_equal 10.days, Configurable.unlock_in
+  end
+
+  test 'set null fields on migrations' do
+    # Ignore email sending since no email exists.
+    klass = Class.new(Admin) do
+      def send_devise_notification(*); end
+    end
+
+    klass.create!
+  end
+end
+
+class CheckFieldsTest < ActiveSupport::TestCase
+  test 'checks if the class respond_to the required fields' do
+    Player = Class.new do
+      extend Devise::Models
+
+      def self.before_validation(instance)
+      end
+
+      devise :database_authenticatable
+
+      attr_accessor :encrypted_password, :email
+    end
+
+    assert_nothing_raised Devise::Models::MissingAttribute do
+      Devise::Models.check_fields!(Player)
+    end
+  end
+
+  test 'raises Devise::Models::MissingAtrribute and shows the missing attribute if the class doesn\'t respond_to one of the attributes' do
+    Clown = Class.new do
+      extend Devise::Models
+
+      def self.before_validation(instance)
+      end
+
+      devise :database_authenticatable
+
+      attr_accessor :encrypted_password
+    end
+
+    assert_raise_with_message Devise::Models::MissingAttribute, "The following attribute(s) is (are) missing on your model: email" do
+      Devise::Models.check_fields!(Clown)
+    end
+  end
+
+  test 'raises Devise::Models::MissingAtrribute with all the missing attributes if there is more than one' do
+    Magician = Class.new do
+      extend Devise::Models
+
+      def self.before_validation(instance)
+      end
+
+      devise :database_authenticatable
+    end
+
+    assert_raise_with_message Devise::Models::MissingAttribute, "The following attribute(s) is (are) missing on your model: encrypted_password, email" do
+      Devise::Models.check_fields!(Magician)
+    end
+  end
+end
diff --git a/test/omniauth/config_test.rb b/test/omniauth/config_test.rb
new file mode 100644
index 0000000..86e9663
--- /dev/null
+++ b/test/omniauth/config_test.rb
@@ -0,0 +1,57 @@
+require 'test_helper'
+
+class OmniAuthConfigTest < ActiveSupport::TestCase
+  class MyStrategy
+    include OmniAuth::Strategy
+  end
+
+  test 'strategy_name returns provider if no options given' do
+    config = Devise::OmniAuth::Config.new :facebook, [{}]
+    assert_equal :facebook, config.strategy_name
+  end
+
+  test 'strategy_name returns provider if no name option are given' do
+    config = Devise::OmniAuth::Config.new :facebook, [{ other: :option }]
+    assert_equal :facebook, config.strategy_name
+  end
+
+  test 'returns name option when have a name' do
+    config = Devise::OmniAuth::Config.new :facebook, [{ name: :github }]
+    assert_equal :github, config.strategy_name
+  end
+
+  test "finds contrib strategies" do
+    config = Devise::OmniAuth::Config.new :facebook, [{}]
+    assert_equal OmniAuth::Strategies::Facebook, config.strategy_class
+  end
+
+  test "finds the strategy in OmniAuth's list by name" do
+    NamedTestStrategy = Class.new
+    NamedTestStrategy.send :include, OmniAuth::Strategy
+    NamedTestStrategy.option :name, :the_one
+
+    config = Devise::OmniAuth::Config.new :the_one, [{}]
+    assert_equal NamedTestStrategy, config.strategy_class
+  end
+
+  test "finds the strategy in OmniAuth's list by class name" do
+    UnNamedTestStrategy = Class.new
+    UnNamedTestStrategy.send :include, OmniAuth::Strategy
+
+    config = Devise::OmniAuth::Config.new :un_named_test_strategy, [{}]
+    assert_equal UnNamedTestStrategy, config.strategy_class
+  end
+
+  test 'raises an error if strategy cannot be found' do
+    config = Devise::OmniAuth::Config.new :my_other_strategy, [{}]
+    assert_raise Devise::OmniAuth::StrategyNotFound do
+      config.strategy_class
+    end
+  end
+
+  test 'allows the user to define a custom require path' do
+    config = Devise::OmniAuth::Config.new :my_strategy, [{strategy_class: MyStrategy}]
+    config_class = config.strategy_class
+    assert_equal MyStrategy, config_class
+  end
+end
diff --git a/test/omniauth/url_helpers_test.rb b/test/omniauth/url_helpers_test.rb
new file mode 100644
index 0000000..6f9c80e
--- /dev/null
+++ b/test/omniauth/url_helpers_test.rb
@@ -0,0 +1,54 @@
+require 'test_helper'
+
+class OmniAuthRoutesTest < ActionController::TestCase
+  ExpectedUrlGeneratiorError = Devise.rails4? ?
+    ActionController::UrlGenerationError : ActionController::RoutingError
+
+  tests ApplicationController
+
+  def assert_path(action, provider, with_param=true)
+    # Resource param
+    assert_equal @controller.send(action, :user, provider),
+                 @controller.send("user_#{action}", provider)
+
+    # With an object
+    assert_equal @controller.send(action, User.new, provider),
+                 @controller.send("user_#{action}", provider)
+
+    if with_param
+      # Default url params
+      assert_equal @controller.send(action, :user, provider, param: 123),
+                   @controller.send("user_#{action}", provider, param: 123)
+    end
+  end
+
+  test 'should alias omniauth_callback to mapped user auth_callback' do
+    assert_path :omniauth_callback_path, :facebook
+  end
+
+  test 'should alias omniauth_authorize to mapped user auth_authorize' do
+    assert_path :omniauth_authorize_path, :facebook, false
+  end
+
+  test 'should generate authorization path' do
+    assert_match "/users/auth/facebook", @controller.omniauth_authorize_path(:user, :facebook)
+
+    assert_raise ExpectedUrlGeneratiorError do
+      @controller.omniauth_authorize_path(:user, :github)
+    end
+  end
+
+  test 'should generate authorization path for named open_id omniauth' do
+    assert_match "/users/auth/google", @controller.omniauth_authorize_path(:user, :google)
+  end
+
+  test 'should generate authorization path with params' do
+    assert_match "/users/auth/openid?openid_url=http%3A%2F%2Fyahoo.com",
+                  @controller.omniauth_authorize_path(:user, :openid, openid_url: "http://yahoo.com")
+  end
+
+  test 'should not add a "?" if no param was sent' do
+    assert_equal "/users/auth/openid",
+                  @controller.omniauth_authorize_path(:user, :openid)
+  end
+end
diff --git a/test/orm/active_record.rb b/test/orm/active_record.rb
new file mode 100644
index 0000000..023e3cb
--- /dev/null
+++ b/test/orm/active_record.rb
@@ -0,0 +1,10 @@
+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__))
+
+class ActiveSupport::TestCase
+  self.use_transactional_fixtures = true
+  self.use_instantiated_fixtures  = false
+end
diff --git a/test/orm/mongoid.rb b/test/orm/mongoid.rb
new file mode 100644
index 0000000..739b971
--- /dev/null
+++ b/test/orm/mongoid.rb
@@ -0,0 +1,13 @@
+require 'mongoid/version'
+
+Mongoid.configure do |config|
+  config.load!('test/support/mongoid.yml')
+  config.use_utc = true
+  config.include_root_in_json = true
+end
+
+class ActiveSupport::TestCase
+  setup do
+    Mongoid.purge!
+  end
+end
diff --git a/test/parameter_sanitizer_test.rb b/test/parameter_sanitizer_test.rb
new file mode 100644
index 0000000..f086cf9
--- /dev/null
+++ b/test/parameter_sanitizer_test.rb
@@ -0,0 +1,81 @@
+require 'test_helper'
+require 'devise/parameter_sanitizer'
+
+class BaseSanitizerTest < ActiveSupport::TestCase
+  def sanitizer(params)
+    Devise::BaseSanitizer.new(User, :user, params)
+  end
+
+  test 'returns chosen params' do
+    sanitizer = sanitizer(user: { "email" => "jose" })
+    assert_equal({ "email" => "jose" }, sanitizer.sanitize(: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.sanitize(: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.sanitize(: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.sanitize(: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.sanitize(: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.sanitize(:sign_in))
+    end
+
+    test 'adding multiple permitted parameters' do
+      sanitizer = sanitizer(user: { "email" => "jose", "username" => "jose1", "role" => "valid" })
+      sanitizer.for(:sign_in).concat([:username, :role])
+      assert_equal({ "email" => "jose", "username" => "jose1", "role" => "valid" }, sanitizer.sanitize(:sign_in))
+    end
+
+    test 'removing multiple default parameters' do
+      sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid", "remember_me" => "1" })
+      sanitizer.for(:sign_in).delete(:email)
+      sanitizer.for(:sign_in).delete(:password)
+      assert_equal({ "remember_me" => "1" }, sanitizer.sanitize(:sign_in))
+    end
+
+    test 'raises on unknown hooks' do
+      sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid" })
+      assert_raise NotImplementedError do
+        sanitizer.sanitize(:unknown)
+      end
+    end
+
+    test 'passes parameters to filter as arguments to sanitizer' do
+      params = {user: stub}
+      sanitizer = Devise::ParameterSanitizer.new(User, :user, params)
+
+      params[:user].expects(:permit).with(kind_of(Symbol), kind_of(Symbol), kind_of(Symbol))
+
+      sanitizer.sanitize(:sign_in)
+    end
+  end
+end
diff --git a/test/rails_app/Rakefile b/test/rails_app/Rakefile
new file mode 100644
index 0000000..ba6b733
--- /dev/null
+++ b/test/rails_app/Rakefile
@@ -0,0 +1,6 @@
+# Add your own tasks in files placed in lib/tasks ending in .rake,
+# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
+
+require File.expand_path('../config/application', __FILE__)
+
+Rails.application.load_tasks
diff --git a/test/rails_app/app/active_record/admin.rb b/test/rails_app/app/active_record/admin.rb
new file mode 100644
index 0000000..124bc90
--- /dev/null
+++ b/test/rails_app/app/active_record/admin.rb
@@ -0,0 +1,6 @@
+require 'shared_admin'
+
+class Admin < ActiveRecord::Base
+  include Shim
+  include SharedAdmin
+end
diff --git a/test/rails_app/app/active_record/shim.rb b/test/rails_app/app/active_record/shim.rb
new file mode 100644
index 0000000..66f12cd
--- /dev/null
+++ b/test/rails_app/app/active_record/shim.rb
@@ -0,0 +1,2 @@
+module Shim
+end
diff --git a/test/rails_app/app/active_record/user.rb b/test/rails_app/app/active_record/user.rb
new file mode 100644
index 0000000..eefe2dd
--- /dev/null
+++ b/test/rails_app/app/active_record/user.rb
@@ -0,0 +1,6 @@
+require 'shared_user'
+
+class User < ActiveRecord::Base
+  include Shim
+  include SharedUser
+end
diff --git a/test/rails_app/app/active_record/user_on_engine.rb b/test/rails_app/app/active_record/user_on_engine.rb
new file mode 100644
index 0000000..21eb305
--- /dev/null
+++ b/test/rails_app/app/active_record/user_on_engine.rb
@@ -0,0 +1,7 @@
+require 'shared_user_without_omniauth'
+
+class UserOnEngine < ActiveRecord::Base
+  self.table_name = 'users'
+  include Shim
+  include SharedUserWithoutOmniauth
+end
diff --git a/test/rails_app/app/active_record/user_on_main_app.rb b/test/rails_app/app/active_record/user_on_main_app.rb
new file mode 100644
index 0000000..54ef1f8
--- /dev/null
+++ b/test/rails_app/app/active_record/user_on_main_app.rb
@@ -0,0 +1,7 @@
+require 'shared_user_without_omniauth'
+
+class UserOnMainApp < ActiveRecord::Base
+  self.table_name = 'users'
+  include Shim
+  include SharedUserWithoutOmniauth
+end
diff --git a/test/rails_app/app/controllers/admins/sessions_controller.rb b/test/rails_app/app/controllers/admins/sessions_controller.rb
new file mode 100644
index 0000000..525ca5e
--- /dev/null
+++ b/test/rails_app/app/controllers/admins/sessions_controller.rb
@@ -0,0 +1,6 @@
+class Admins::SessionsController < Devise::SessionsController
+  def new
+    flash[:special] = "Welcome to #{controller_path.inspect} controller!"
+    super
+  end
+end
diff --git a/test/rails_app/app/controllers/admins_controller.rb b/test/rails_app/app/controllers/admins_controller.rb
new file mode 100644
index 0000000..2b4837c
--- /dev/null
+++ b/test/rails_app/app/controllers/admins_controller.rb
@@ -0,0 +1,11 @@
+class AdminsController < ApplicationController
+  before_filter :authenticate_admin!
+
+  def index
+  end
+
+  def expire
+    admin_session['last_request_at'] = 31.minutes.ago.utc
+    render text: 'Admin will be expired on next request'
+  end
+end
diff --git a/test/rails_app/app/controllers/application_controller.rb b/test/rails_app/app/controllers/application_controller.rb
new file mode 100644
index 0000000..740830d
--- /dev/null
+++ b/test/rails_app/app/controllers/application_controller.rb
@@ -0,0 +1,12 @@
+# Filters added to this controller apply to all controllers in the application.
+# Likewise, all the methods added will be available for all controllers.
+
+class ApplicationController < ActionController::Base
+  protect_from_forgery
+  before_filter :current_user, unless: :devise_controller?
+  before_filter :authenticate_user!, if: :devise_controller?
+  respond_to *Mime::SET.map(&:to_sym)
+
+  devise_group :commenter, contains: [:user, :admin]
+end
+
diff --git a/test/rails_app/app/controllers/application_with_fake_engine.rb b/test/rails_app/app/controllers/application_with_fake_engine.rb
new file mode 100644
index 0000000..c77d67f
--- /dev/null
+++ b/test/rails_app/app/controllers/application_with_fake_engine.rb
@@ -0,0 +1,30 @@
+class ApplicationWithFakeEngine < ApplicationController
+  private
+
+  helper_method :fake_engine
+  def fake_engine
+    @fake_engine ||= FakeEngine.new
+  end
+end
+
+class FakeEngine
+  def user_on_engine_confirmation_path
+    '/user_on_engine/confirmation'
+  end
+
+  def new_user_on_engine_session_path
+    '/user_on_engine/confirmation/new'
+  end
+
+  def new_user_on_engine_registration_path
+    '/user_on_engine/registration/new'
+  end
+
+  def new_user_on_engine_password_path
+    '/user_on_engine/password/new'
+  end
+
+  def new_user_on_engine_unlock_path
+    '/user_on_engine/unlock/new'
+  end
+end
diff --git a/test/rails_app/app/controllers/custom/registrations_controller.rb b/test/rails_app/app/controllers/custom/registrations_controller.rb
new file mode 100644
index 0000000..9f1699c
--- /dev/null
+++ b/test/rails_app/app/controllers/custom/registrations_controller.rb
@@ -0,0 +1,21 @@
+class Custom::RegistrationsController < Devise::RegistrationsController
+  def create
+    super do |resource|
+      @create_block_called = true
+    end
+  end
+
+  def update
+    super do |resource|
+      @update_block_called = true
+    end
+  end
+
+  def create_block_called?
+    @create_block_called == true
+  end
+
+  def update_block_called?
+    @update_block_called == true
+  end
+end
diff --git a/test/rails_app/app/controllers/home_controller.rb b/test/rails_app/app/controllers/home_controller.rb
new file mode 100644
index 0000000..c647195
--- /dev/null
+++ b/test/rails_app/app/controllers/home_controller.rb
@@ -0,0 +1,25 @@
+class HomeController < ApplicationController
+  def index
+  end
+
+  def private
+  end
+
+  def user_dashboard
+  end
+
+  def admin_dashboard
+  end
+
+  def join
+  end
+
+  def set
+    session["devise.foo_bar"] = "something"
+    head :ok
+  end
+
+  def unauthenticated
+    render text: "unauthenticated", status: :unauthorized
+  end
+end
diff --git a/test/rails_app/app/controllers/publisher/registrations_controller.rb b/test/rails_app/app/controllers/publisher/registrations_controller.rb
new file mode 100644
index 0000000..7809a36
--- /dev/null
+++ b/test/rails_app/app/controllers/publisher/registrations_controller.rb
@@ -0,0 +1,2 @@
+class Publisher::RegistrationsController < ApplicationController
+end
diff --git a/test/rails_app/app/controllers/publisher/sessions_controller.rb b/test/rails_app/app/controllers/publisher/sessions_controller.rb
new file mode 100644
index 0000000..2eed1bb
--- /dev/null
+++ b/test/rails_app/app/controllers/publisher/sessions_controller.rb
@@ -0,0 +1,2 @@
+class Publisher::SessionsController < ApplicationController
+end
diff --git a/test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb b/test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb
new file mode 100644
index 0000000..f6474be
--- /dev/null
+++ b/test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb
@@ -0,0 +1,14 @@
+class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
+  def facebook
+    data = env["omniauth.auth"]
+    session["devise.facebook_data"] = data["extra"]["user_hash"]
+    render json: data
+  end
+
+  def sign_in_facebook
+    user = User.to_adapter.find_first(email: 'user at test.com')
+    user.remember_me = true
+    sign_in user
+    render text: ""
+  end
+end
diff --git a/test/rails_app/app/controllers/users_controller.rb b/test/rails_app/app/controllers/users_controller.rb
new file mode 100644
index 0000000..c1ae874
--- /dev/null
+++ b/test/rails_app/app/controllers/users_controller.rb
@@ -0,0 +1,31 @@
+class UsersController < ApplicationController
+  prepend_before_filter :current_user, only: :exhibit
+  before_filter :authenticate_user!, except: [:accept, :exhibit]
+  respond_to :html, :xml
+
+  def index
+    user_session[:cart] = "Cart"
+    respond_with(current_user)
+  end
+
+  def edit_form
+    user_session['last_request_at'] = params.fetch(:last_request_at, 31.minutes.ago.utc)
+  end
+
+  def update_form
+    render text: 'Update'
+  end
+
+  def accept
+    @current_user = current_user
+  end
+
+  def exhibit
+    render text: current_user ? "User is authenticated" : "User is not authenticated"
+  end
+
+  def expire
+    user_session['last_request_at'] = 31.minutes.ago.utc
+    render text: 'User will be expired on next request'
+  end
+end
diff --git a/test/rails_app/app/helpers/application_helper.rb b/test/rails_app/app/helpers/application_helper.rb
new file mode 100644
index 0000000..22a7940
--- /dev/null
+++ b/test/rails_app/app/helpers/application_helper.rb
@@ -0,0 +1,3 @@
+# Methods added to this helper will be available to all templates in the application.
+module ApplicationHelper
+end
diff --git a/test/rails_app/app/mailers/users/from_proc_mailer.rb b/test/rails_app/app/mailers/users/from_proc_mailer.rb
new file mode 100644
index 0000000..1bff4ca
--- /dev/null
+++ b/test/rails_app/app/mailers/users/from_proc_mailer.rb
@@ -0,0 +1,3 @@
+class Users::FromProcMailer < Devise::Mailer
+  default from: proc { 'custom at example.com' }
+end
diff --git a/test/rails_app/app/mailers/users/mailer.rb b/test/rails_app/app/mailers/users/mailer.rb
new file mode 100644
index 0000000..3342f75
--- /dev/null
+++ b/test/rails_app/app/mailers/users/mailer.rb
@@ -0,0 +1,3 @@
+class Users::Mailer < Devise::Mailer
+  default from: 'custom at example.com'
+end
diff --git a/test/rails_app/app/mailers/users/reply_to_mailer.rb b/test/rails_app/app/mailers/users/reply_to_mailer.rb
new file mode 100644
index 0000000..67ca82c
--- /dev/null
+++ b/test/rails_app/app/mailers/users/reply_to_mailer.rb
@@ -0,0 +1,4 @@
+class Users::ReplyToMailer < Devise::Mailer
+  default from: 'custom at example.com'
+  default reply_to: 'custom_reply_to at example.com'
+end
diff --git a/test/rails_app/app/mongoid/admin.rb b/test/rails_app/app/mongoid/admin.rb
new file mode 100644
index 0000000..d5884cb
--- /dev/null
+++ b/test/rails_app/app/mongoid/admin.rb
@@ -0,0 +1,29 @@
+require 'shared_admin'
+
+class Admin
+  include Mongoid::Document
+  include Shim
+  include SharedAdmin
+
+  ## Database authenticatable
+  field :email,              type: String
+  field :encrypted_password, type: String
+
+  ## Recoverable
+  field :reset_password_token,   type: String
+  field :reset_password_sent_at, type: Time
+
+  ## Rememberable
+  field :remember_created_at, type: Time
+
+  ## Confirmable
+  field :confirmation_token,   type: String
+  field :confirmed_at,         type: Time
+  field :confirmation_sent_at, type: Time
+  field :unconfirmed_email,    type: String # Only if using reconfirmable
+
+  ## Lockable
+  field :locked_at, type: Time
+
+  field :active, type: Boolean, default: false
+end
diff --git a/test/rails_app/app/mongoid/shim.rb b/test/rails_app/app/mongoid/shim.rb
new file mode 100644
index 0000000..cd48fd4
--- /dev/null
+++ b/test/rails_app/app/mongoid/shim.rb
@@ -0,0 +1,23 @@
+module Shim
+  extend ::ActiveSupport::Concern
+
+  included do
+    include ::Mongoid::Timestamps
+    field :created_at, type: DateTime
+  end
+
+  module ClassMethods
+    def order(attribute)
+      asc(attribute)
+    end
+
+    def find_by_email(email)
+      find_by(email: email)
+    end
+  end
+
+  # overwrite equality (because some devise tests use this for asserting model equality)
+  def ==(other)
+    other.is_a?(self.class) && _id == other._id
+  end
+end
diff --git a/test/rails_app/app/mongoid/user.rb b/test/rails_app/app/mongoid/user.rb
new file mode 100644
index 0000000..0a2e5ea
--- /dev/null
+++ b/test/rails_app/app/mongoid/user.rb
@@ -0,0 +1,39 @@
+require 'shared_user'
+
+class User
+  include Mongoid::Document
+  include Shim
+  include SharedUser
+
+  field :username, type: String
+  field :facebook_token, type: String
+
+  ## 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
+
+  ## Rememberable
+  field :remember_created_at, type: Time
+
+  ## Trackable
+  field :sign_in_count,      type: Integer, default: 0
+  field :current_sign_in_at, type: Time
+  field :last_sign_in_at,    type: Time
+  field :current_sign_in_ip, type: String
+  field :last_sign_in_ip,    type: String
+
+  ## Confirmable
+  field :confirmation_token,   type: String
+  field :confirmed_at,         type: Time
+  field :confirmation_sent_at, type: Time
+  # field :unconfirmed_email,    type: String # Only if using reconfirmable
+
+  ## Lockable
+  field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
+  field :unlock_token,    type: String # Only if unlock strategy is :email or :both
+  field :locked_at,       type: Time
+end
diff --git a/test/rails_app/app/mongoid/user_on_engine.rb b/test/rails_app/app/mongoid/user_on_engine.rb
new file mode 100644
index 0000000..e68b096
--- /dev/null
+++ b/test/rails_app/app/mongoid/user_on_engine.rb
@@ -0,0 +1,39 @@
+require 'shared_user_without_omniauth'
+
+class UserOnEngine
+  include Mongoid::Document
+  include Shim
+  include SharedUserWithoutOmniauth
+
+  field :username, type: String
+  field :facebook_token, type: String
+
+  ## 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
+
+  ## Rememberable
+  field :remember_created_at, type: Time
+
+  ## Trackable
+  field :sign_in_count, type: Integer, default: 0
+  field :current_sign_in_at, type: Time
+  field :last_sign_in_at, type: Time
+  field :current_sign_in_ip, type: String
+  field :last_sign_in_ip, type: String
+
+  ## Confirmable
+  field :confirmation_token, type: String
+  field :confirmed_at, type: Time
+  field :confirmation_sent_at, type: Time
+  # field :unconfirmed_email,    type: String # Only if using reconfirmable
+
+  ## Lockable
+  field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
+  field :unlock_token, type: String # Only if unlock strategy is :email or :both
+  field :locked_at, type: Time
+end
diff --git a/test/rails_app/app/mongoid/user_on_main_app.rb b/test/rails_app/app/mongoid/user_on_main_app.rb
new file mode 100644
index 0000000..a35f233
--- /dev/null
+++ b/test/rails_app/app/mongoid/user_on_main_app.rb
@@ -0,0 +1,39 @@
+require 'shared_user_without_omniauth'
+
+class UserOnMainApp
+  include Mongoid::Document
+  include Shim
+  include SharedUserWithoutOmniauth
+
+  field :username, type: String
+  field :facebook_token, type: String
+
+  ## 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
+
+  ## Rememberable
+  field :remember_created_at, type: Time
+
+  ## Trackable
+  field :sign_in_count, type: Integer, default: 0
+  field :current_sign_in_at, type: Time
+  field :last_sign_in_at, type: Time
+  field :current_sign_in_ip, type: String
+  field :last_sign_in_ip, type: String
+
+  ## Confirmable
+  field :confirmation_token, type: String
+  field :confirmed_at, type: Time
+  field :confirmation_sent_at, type: Time
+  # field :unconfirmed_email,    type: String # Only if using reconfirmable
+
+  ## Lockable
+  field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
+  field :unlock_token, type: String # Only if unlock strategy is :email or :both
+  field :locked_at, type: Time
+end
diff --git a/test/rails_app/app/views/admins/index.html.erb b/test/rails_app/app/views/admins/index.html.erb
new file mode 100644
index 0000000..798119e
--- /dev/null
+++ b/test/rails_app/app/views/admins/index.html.erb
@@ -0,0 +1 @@
+Welcome Admin!
diff --git a/test/rails_app/app/views/admins/sessions/new.html.erb b/test/rails_app/app/views/admins/sessions/new.html.erb
new file mode 100644
index 0000000..75f3b86
--- /dev/null
+++ b/test/rails_app/app/views/admins/sessions/new.html.erb
@@ -0,0 +1,2 @@
+Welcome to "sessions/new" view!
+<%= render file: "devise/sessions/new" %>
diff --git a/test/rails_app/app/views/home/admin_dashboard.html.erb b/test/rails_app/app/views/home/admin_dashboard.html.erb
new file mode 100644
index 0000000..382c996
--- /dev/null
+++ b/test/rails_app/app/views/home/admin_dashboard.html.erb
@@ -0,0 +1 @@
+Admin dashboard
diff --git a/test/rails_app/app/views/home/index.html.erb b/test/rails_app/app/views/home/index.html.erb
new file mode 100644
index 0000000..c3942a0
--- /dev/null
+++ b/test/rails_app/app/views/home/index.html.erb
@@ -0,0 +1 @@
+Home!
diff --git a/test/rails_app/app/views/home/join.html.erb b/test/rails_app/app/views/home/join.html.erb
new file mode 100644
index 0000000..e3bafea
--- /dev/null
+++ b/test/rails_app/app/views/home/join.html.erb
@@ -0,0 +1 @@
+Join
diff --git a/test/rails_app/app/views/home/private.html.erb b/test/rails_app/app/views/home/private.html.erb
new file mode 100644
index 0000000..f92dfa5
--- /dev/null
+++ b/test/rails_app/app/views/home/private.html.erb
@@ -0,0 +1 @@
+Private!
diff --git a/test/rails_app/app/views/home/user_dashboard.html.erb b/test/rails_app/app/views/home/user_dashboard.html.erb
new file mode 100644
index 0000000..578ba45
--- /dev/null
+++ b/test/rails_app/app/views/home/user_dashboard.html.erb
@@ -0,0 +1 @@
+User dashboard
diff --git a/test/rails_app/app/views/layouts/application.html.erb b/test/rails_app/app/views/layouts/application.html.erb
new file mode 100644
index 0000000..cdd9fe1
--- /dev/null
+++ b/test/rails_app/app/views/layouts/application.html.erb
@@ -0,0 +1,24 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html>
+  <head>
+    <title>Devise Test App</title>
+  </head>
+  <body>
+    <div id="container">
+      <%- flash.each do |name, msg| -%>
+        <%= content_tag :div, msg, id: "flash_#{name}" %>
+      <%- end -%>
+
+      <% if user_signed_in? -%>
+        <p>Hello User <%= current_user.email %>! You are signed in!</p>
+      <% end -%>
+
+      <% if admin_signed_in? -%>
+        <p>Hello Admin <%= current_admin.email %>! You are signed in!</p>
+      <% end -%>
+
+      <%= yield %>
+    </div>
+  </body>
+</html>
diff --git a/test/rails_app/app/views/users/edit_form.html.erb b/test/rails_app/app/views/users/edit_form.html.erb
new file mode 100644
index 0000000..b7a2e31
--- /dev/null
+++ b/test/rails_app/app/views/users/edit_form.html.erb
@@ -0,0 +1 @@
+<%= button_to 'Update', update_form_user_path(current_user), method: 'put' %>
diff --git a/test/rails_app/app/views/users/index.html.erb b/test/rails_app/app/views/users/index.html.erb
new file mode 100644
index 0000000..df405f2
--- /dev/null
+++ b/test/rails_app/app/views/users/index.html.erb
@@ -0,0 +1 @@
+Welcome User #<%= current_user.id %>!
diff --git a/test/rails_app/app/views/users/mailer/confirmation_instructions.erb b/test/rails_app/app/views/users/mailer/confirmation_instructions.erb
new file mode 100644
index 0000000..f6e30c3
--- /dev/null
+++ b/test/rails_app/app/views/users/mailer/confirmation_instructions.erb
@@ -0,0 +1 @@
+<%= @resource.email %>
\ No newline at end of file
diff --git a/test/rails_app/app/views/users/sessions/new.html.erb b/test/rails_app/app/views/users/sessions/new.html.erb
new file mode 100644
index 0000000..280cbd0
--- /dev/null
+++ b/test/rails_app/app/views/users/sessions/new.html.erb
@@ -0,0 +1 @@
+Special user view
diff --git a/test/rails_app/bin/bundle b/test/rails_app/bin/bundle
new file mode 100755
index 0000000..66e9889
--- /dev/null
+++ b/test/rails_app/bin/bundle
@@ -0,0 +1,3 @@
+#!/usr/bin/env ruby
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
+load Gem.bin_path('bundler', 'bundle')
diff --git a/test/rails_app/bin/rails b/test/rails_app/bin/rails
new file mode 100755
index 0000000..728cd85
--- /dev/null
+++ b/test/rails_app/bin/rails
@@ -0,0 +1,4 @@
+#!/usr/bin/env ruby
+APP_PATH = File.expand_path('../../config/application',  __FILE__)
+require_relative '../config/boot'
+require 'rails/commands'
diff --git a/test/rails_app/bin/rake b/test/rails_app/bin/rake
new file mode 100755
index 0000000..1724048
--- /dev/null
+++ b/test/rails_app/bin/rake
@@ -0,0 +1,4 @@
+#!/usr/bin/env ruby
+require_relative '../config/boot'
+require 'rake'
+Rake.application.run
diff --git a/test/rails_app/config.ru b/test/rails_app/config.ru
new file mode 100644
index 0000000..2c6ec58
--- /dev/null
+++ b/test/rails_app/config.ru
@@ -0,0 +1,4 @@
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment',  __FILE__)
+run RailsApp::Application
diff --git a/test/rails_app/config/application.rb b/test/rails_app/config/application.rb
new file mode 100644
index 0000000..91c75cb
--- /dev/null
+++ b/test/rails_app/config/application.rb
@@ -0,0 +1,40 @@
+require File.expand_path('../boot', __FILE__)
+
+require "action_controller/railtie"
+require "action_mailer/railtie"
+require "rails/test_unit/railtie"
+
+Bundler.require :default, DEVISE_ORM
+
+begin
+  require "#{DEVISE_ORM}/railtie"
+rescue LoadError
+end
+
+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 += [ "#{config.root}/app/#{DEVISE_ORM}" ]
+
+    # Configure generators values. Many other options are available, be sure to check the documentation.
+    # config.generators do |g|
+    #   g.orm             :active_record
+    #   g.template_engine :erb
+    #   g.test_framework  :test_unit, fixture: true
+    # end
+
+    # Configure sensitive parameters which will be filtered from the log file.
+    config.filter_parameters << :password
+    config.assets.enabled = false
+
+    config.action_mailer.default_url_options = { host: "localhost", port: 3000 }
+
+    # This was used to break devise in some situations
+    config.to_prepare do
+      Devise::SessionsController.layout "application"
+    end
+  end
+end
diff --git a/test/rails_app/config/boot.rb b/test/rails_app/config/boot.rb
new file mode 100644
index 0000000..1a479a1
--- /dev/null
+++ b/test/rails_app/config/boot.rb
@@ -0,0 +1,14 @@
+unless defined?(DEVISE_ORM)
+  DEVISE_ORM = (ENV["DEVISE_ORM"] || :active_record).to_sym
+end
+
+module Devise
+  # Detection for minor differences between Rails 3.2 and 4 in tests.
+  def self.rails4?
+    Rails.version.start_with? '4'
+  end
+end
+
+# Set up gems listed in the Gemfile.
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__)
+require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
diff --git a/test/rails_app/config/database.yml b/test/rails_app/config/database.yml
new file mode 100644
index 0000000..f999fcc
--- /dev/null
+++ b/test/rails_app/config/database.yml
@@ -0,0 +1,18 @@
+# SQLite version 3.x
+#   gem install sqlite3-ruby (not necessary on OS X Leopard)
+development:
+  adapter: sqlite3
+  database: db/development.sqlite3
+  pool: 5
+  timeout: 5000
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+  adapter: sqlite3
+  database: ":memory:"
+
+production:
+  adapter: sqlite3
+  database: ":memory:"
diff --git a/test/rails_app/config/environment.rb b/test/rails_app/config/environment.rb
new file mode 100644
index 0000000..1fe685f
--- /dev/null
+++ b/test/rails_app/config/environment.rb
@@ -0,0 +1,5 @@
+# Load the rails application.
+require File.expand_path('../application', __FILE__)
+
+# Initialize the rails application.
+RailsApp::Application.initialize!
diff --git a/test/rails_app/config/environments/development.rb b/test/rails_app/config/environments/development.rb
new file mode 100644
index 0000000..fcddb5f
--- /dev/null
+++ b/test/rails_app/config/environments/development.rb
@@ -0,0 +1,30 @@
+RailsApp::Application.configure do
+  # 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 web server when you make code changes.
+  config.cache_classes = false
+
+  # Do not eager load code on boot.
+  config.eager_load = false
+
+  # 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.
+  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
+
+  # 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
diff --git a/test/rails_app/config/environments/production.rb b/test/rails_app/config/environments/production.rb
new file mode 100644
index 0000000..2ce2f51
--- /dev/null
+++ b/test/rails_app/config/environments/production.rb
@@ -0,0 +1,80 @@
+RailsApp::Application.configure do
+  # Settings specified here will take precedence over those in config/application.rb.
+
+  # 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.
+  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
+
+  # Disable Rails's static asset server (Apache or nginx will already do this).
+  config.serve_static_assets = false
+
+  # 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"
+
+  # 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 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
+
+  # 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
diff --git a/test/rails_app/config/environments/test.rb b/test/rails_app/config/environments/test.rb
new file mode 100644
index 0000000..b9feca8
--- /dev/null
+++ b/test/rails_app/config/environments/test.rb
@@ -0,0 +1,36 @@
+RailsApp::Application.configure do
+  # 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
+  # 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!
+  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
+
+  # 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
+
+  # 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
+
+  # Print deprecation notices to the stderr.
+  config.active_support.deprecation = :stderr
+end
diff --git a/test/rails_app/config/initializers/backtrace_silencers.rb b/test/rails_app/config/initializers/backtrace_silencers.rb
new file mode 100644
index 0000000..56ddc8d
--- /dev/null
+++ b/test/rails_app/config/initializers/backtrace_silencers.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
+# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
+
+# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
+Rails.backtrace_cleaner.remove_silencers!
diff --git a/test/rails_app/config/initializers/devise.rb b/test/rails_app/config/initializers/devise.rb
new file mode 100644
index 0000000..1f99480
--- /dev/null
+++ b/test/rails_app/config/initializers/devise.rb
@@ -0,0 +1,183 @@
+require "omniauth-facebook"
+require "omniauth-openid"
+
+# Use this hook to configure devise mailer, warden hooks and so forth. The first
+# four configuration values can also be set straight in your models.
+Devise.setup do |config|
+  config.secret_key = "d9eb5171c59a4c817f68b0de27b8c1e340c2341b52cdbc60d3083d4e8958532" \
+                      "18dcc5f589cafde048faec956b61f864b9b5513ff9ce29bf9e5d58b0f234f8e3b"
+
+  # ==> Mailer Configuration
+  # Configure the e-mail address which will be shown in Devise::Mailer,
+  # note that it will be overwritten if you use your own mailer class with default "from" parameter.
+  config.mailer_sender = "please-change-me at config-initializers-devise.com"
+
+
+  config.parent_controller = "ApplicationWithFakeEngine"
+  # Configure the class responsible to send e-mails.
+  # config.mailer = "Devise::Mailer"
+
+  # ==> ORM configuration
+  # Load and configure the ORM. Supports :active_record (default) and
+  # :mongoid (bson_ext recommended) by default. Other ORMs may be
+  # available as additional gems.
+  require "devise/orm/#{DEVISE_ORM}"
+
+  # ==> Configuration for any authentication mechanism
+  # Configure which keys are used when authenticating a user. By default is
+  # just :email. You can configure it to use [:username, :subdomain], so for
+  # authenticating a user, both parameters are required. Remember that those
+  # parameters are used only when authenticating and not when retrieving from
+  # session. If you need permissions, you should implement that in a before filter.
+  # You can also supply hash where the value is a boolean expliciting if authentication
+  # should be aborted or not if the value is not present. By default is empty.
+  # config.authentication_keys = [ :email ]
+
+  # Configure parameters from the request object used for authentication. Each entry
+  # given should be a request method and 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 used on authentication.
+  # The same considerations mentioned for authentication_keys also apply to request_keys.
+  # config.request_keys = []
+
+  # Configure which authentication keys should be case-insensitive.
+  # These keys will be downcased upon creating or modifying a user and when used
+  # to authenticate or find a user. Default is :email.
+  config.case_insensitive_keys = [ :email ]
+
+  # Configure which authentication keys should have whitespace stripped.
+  # These keys will have whitespace before and after removed upon creating or
+  # modifying a user and when used to authenticate or find a user. Default is :email.
+  config.strip_whitespace_keys = [ :email ]
+
+  # Tell if authentication through request.params is enabled. True by default.
+  # config.params_authenticatable = true
+
+  # Tell if authentication through HTTP Basic Auth is enabled. False by default.
+  config.http_authenticatable = true
+
+  # If http headers should be returned for AJAX requests. True by default.
+  # config.http_authenticatable_on_xhr = true
+
+  # The realm used in Http Basic Authentication. "Application" by default.
+  # config.http_authentication_realm = "Application"
+
+  # ==> Configuration for :database_authenticatable
+  # For bcrypt, this is the cost for hashing the password and defaults to 10. If
+  # using other encryptors, it sets how many times you want the password re-encrypted.
+  config.stretches = Rails.env.test? ? 1 : 10
+
+  # ==> Configuration for :confirmable
+  # The time you want to give your user to confirm their account. During this time
+  # they will be able to access your application without confirming. Default is nil.
+  # When allow_unconfirmed_access_for is zero, the user won't be able to sign in without confirming.
+  # You can use this to let your user access some features of your application
+  # without confirming the account, but blocking it after a certain period
+  # (ie 2 days).
+  # config.allow_unconfirmed_access_for = 2.days
+
+  # Defines which key will be used when confirming an account
+  # config.confirmation_keys = [ :email ]
+
+  # ==> Configuration for :rememberable
+  # The time the user will be remembered without asking for credentials again.
+  # config.remember_for = 2.weeks
+
+  # If true, a valid remember token can be re-used between multiple browsers.
+  # config.remember_across_browsers = true
+
+  # If true, extends the user's remember period when remembered via cookie.
+  # config.extend_remember_period = false
+
+  # ==> Configuration for :validatable
+  # Range for password length. Default is 8..128.
+  # config.password_length = 8..128
+
+  # Regex to use to validate the email address
+  # config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i
+
+  # ==> Configuration for :timeoutable
+  # The time you want to timeout the user session without activity. After this
+  # time the user will be asked for credentials again. Default is 30 minutes.
+  # config.timeout_in = 30.minutes
+
+  # ==> Configuration for :lockable
+  # Defines which strategy will be used to lock an account.
+  # :failed_attempts = Locks an account after a number of failed attempts to sign in.
+  # :none            = No lock strategy. You should handle locking by yourself.
+  # config.lock_strategy = :failed_attempts
+
+  # Defines which key will be used when locking and unlocking an account
+  # config.unlock_keys = [ :email ]
+
+  # Defines which strategy will be used to unlock an account.
+  # :email = Sends an unlock link to the user email
+  # :time  = Re-enables login after a certain amount of time (see :unlock_in below)
+  # :both  = Enables both strategies
+  # :none  = No unlock strategy. You should handle unlocking by yourself.
+  # config.unlock_strategy = :both
+
+  # Number of authentication tries before locking an account if lock_strategy
+  # is failed attempts.
+  # config.maximum_attempts = 20
+
+  # Time interval to unlock the account if :time is enabled as unlock_strategy.
+  # config.unlock_in = 1.hour
+
+  # ==> Configuration for :recoverable
+  #
+  # Defines which key will be used when recovering the password for an account
+  # config.reset_password_keys = [ :email ]
+
+  # Time interval you can reset your password with a reset password key.
+  # Don't put a too small interval or your users won't have the time to
+  # change their passwords.
+  config.reset_password_within = 2.hours
+
+  # Setup a pepper to generate the encrypted password.
+  config.pepper = "d142367154e5beacca404b1a6a4f8bc52c6fdcfa3ccc3cf8eb49f3458a688ee6ac3b9fae488432a3bfca863b8a90008368a9f3a3dfbe5a962e64b6ab8f3a3a1a"
+
+  # ==> Configuration for :token_authenticatable
+  # Defines name of the authentication token params key
+  # config.token_authentication_key = :auth_token
+
+  # ==> Scopes configuration
+  # Turn scoped views on. Before rendering "sessions/new", it will first check for
+  # "users/sessions/new". It's turned off by default because it's slower if you
+  # are using only default views.
+  # config.scoped_views = false
+
+  # Configure the default scope given to Warden. By default it's the first
+  # devise role declared in your routes (usually :user).
+  # config.default_scope = :user
+
+  # Configure sign_out behavior.
+  # Sign_out action can be scoped (i.e. /users/sign_out affects only :user scope).
+  # The default is true, which means any logout action will sign out all active scopes.
+  # config.sign_out_all_scopes = true
+
+  # ==> Navigation configuration
+  # Lists the formats that should be treated as navigational. Formats like
+  # :html, should redirect to the sign in page when the user does not have
+  # access, but formats like :xml or :json, should return 401.
+  # If you have any extra navigational formats, like :iphone or :mobile, you
+  # should add them to the navigational formats lists. Default is [:html]
+  # config.navigational_formats = [:html, :iphone]
+
+  # The default HTTP method used to sign out a resource. Default is :get.
+  # config.sign_out_via = :get
+
+  # ==> OmniAuth
+  config.omniauth :facebook, 'APP_ID', 'APP_SECRET', scope: 'email,offline_access'
+  config.omniauth :openid
+  config.omniauth :openid, name: 'google', identifier: 'https://www.google.com/accounts/o8/id'
+
+  # ==> Warden configuration
+  # If you want to use other strategies, that are not supported by Devise, or
+  # change the failure app, you can configure them inside the config.warden block.
+  #
+  # config.warden do |manager|
+  #   manager.failure_app = AnotherApp
+  #   manager.default_strategies(scope: :user).unshift :some_external_strategy
+  # end
+end
diff --git a/test/rails_app/config/initializers/inflections.rb b/test/rails_app/config/initializers/inflections.rb
new file mode 100644
index 0000000..45fc8f4
--- /dev/null
+++ b/test/rails_app/config/initializers/inflections.rb
@@ -0,0 +1,2 @@
+ActiveSupport::Inflector.inflections do |inflect|
+end
diff --git a/test/rails_app/config/initializers/secret_token.rb b/test/rails_app/config/initializers/secret_token.rb
new file mode 100644
index 0000000..2469891
--- /dev/null
+++ b/test/rails_app/config/initializers/secret_token.rb
@@ -0,0 +1,8 @@
+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
diff --git a/test/rails_app/config/initializers/session_store.rb b/test/rails_app/config/initializers/session_store.rb
new file mode 100644
index 0000000..5ac94e7
--- /dev/null
+++ b/test/rails_app/config/initializers/session_store.rb
@@ -0,0 +1 @@
+RailsApp::Application.config.session_store :cookie_store, key: '_rails_app_session'
diff --git a/test/rails_app/config/routes.rb b/test/rails_app/config/routes.rb
new file mode 100644
index 0000000..7438114
--- /dev/null
+++ b/test/rails_app/config/routes.rb
@@ -0,0 +1,122 @@
+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
+
+    authenticate do
+      post :exhibit, on: :member
+    end
+  end
+
+  resources :admins, only: [:index] do
+    get :expire, on: :member
+  end
+
+  # Users scope
+  devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" }
+
+  devise_for :user_on_main_apps,
+    class_name: 'UserOnMainApp',
+    router_name: :main_app,
+    module: :devise
+
+  devise_for :user_on_engines,
+    class_name: 'UserOnEngine',
+    router_name: :fake_engine,
+    module: :devise
+
+  as :user do
+    get "/as/sign_in", to: "devise/sessions#new"
+  end
+
+  get "/sign_in", to: "devise/sessions#new"
+
+  # Routes for custom controller testing
+  devise_for :user, only: [:registrations], controllers: { registrations: "custom/registrations" }, as: :custom, path: :custom
+
+  # Admin scope
+  devise_for :admin, path: "admin_area", controllers: { sessions: :"admins/sessions" }, skip: :passwords
+
+  get "/admin_area/home", to: "admins#index", as: :admin_root
+  get "/anywhere", to: "foo#bar", as: :new_admin_password
+
+  authenticate(:admin) do
+    get "/private", to: "home#private", as: :private
+  end
+
+  authenticate(:admin, lambda { |admin| admin.active? }) do
+    get "/private/active", to: "home#private", as: :private_active
+  end
+
+  authenticated :admin do
+    get "/dashboard", to: "home#admin_dashboard"
+  end
+
+  authenticated :admin, lambda { |admin| admin.active? } do
+    get "/dashboard/active", to: "home#admin_dashboard"
+  end
+
+  authenticated do
+    get "/dashboard", to: "home#user_dashboard"
+  end
+
+  unauthenticated do
+    get "/join", to: "home#join"
+  end
+
+  # Routes for constraints testing
+  devise_for :headquarters_admin, class_name: "Admin", path: "headquarters", constraints: {host: /192\.168\.1\.\d\d\d/}
+
+  constraints(host: /192\.168\.1\.\d\d\d/) do
+    devise_for :homebase_admin, class_name: "Admin", path: "homebase"
+  end
+
+  scope(subdomain: 'sub') do
+    devise_for :subdomain_users, class_name: "User", only: [:sessions]
+  end
+
+  devise_for :skip_admin, class_name: "Admin", skip: :all
+
+  # Routes for format=false testing
+  devise_for :htmlonly_admin, class_name: "Admin", skip: [:confirmations, :unlocks], path: "htmlonly_admin", format: false, skip_helpers: [:confirmations, :unlocks]
+  devise_for :htmlonly_users, class_name: "User", only: [:confirmations, :unlocks], path: "htmlonly_users", format: false, skip_helpers: true
+
+  # Other routes for routing_test.rb
+  devise_for :reader, class_name: "User", only: :passwords
+
+  scope host: "sub.example.com" do
+    devise_for :sub_admin, class_name: "Admin"
+  end
+
+  namespace :publisher, path_names: { sign_in: "i_dont_care", sign_out: "get_out" } do
+    devise_for :accounts, class_name: "Admin", path_names: { sign_in: "get_in" }
+  end
+
+  scope ":locale", module: :invalid do
+    devise_for :accounts, singular: "manager", class_name: "Admin",
+      path_names: {
+        sign_in: "login", sign_out: "logout",
+        password: "secret", confirmation: "verification",
+        unlock: "unblock", sign_up: "register",
+        registration: "management",
+        cancel: "giveup", edit: "edit/profile"
+      }, failure_app: lambda { |env| [404, {"Content-Type" => "text/plain"}, ["Oops, not found"]] }, module: :devise
+  end
+
+  namespace :sign_out_via, module: "devise" do
+    devise_for :deletes, sign_out_via: :delete, class_name: "Admin"
+    devise_for :posts, sign_out_via: :post, class_name: "Admin"
+    devise_for :delete_or_posts, sign_out_via: [:delete, :post], class_name: "Admin"
+  end
+
+  get "/set", to: "home#set"
+  get "/unauthenticated", to: "home#unauthenticated"
+  get "/custom_strategy/new"
+
+  root to: "home#index", via: [:get, :post]
+end
diff --git a/test/rails_app/db/migrate/20100401102949_create_tables.rb b/test/rails_app/db/migrate/20100401102949_create_tables.rb
new file mode 100644
index 0000000..fd90b50
--- /dev/null
+++ b/test/rails_app/db/migrate/20100401102949_create_tables.rb
@@ -0,0 +1,71 @@
+class CreateTables < ActiveRecord::Migration
+  def self.up
+    create_table :users do |t|
+      t.string :username
+      t.string :facebook_token
+
+      ## Database authenticatable
+      t.string :email,              null: false, default: ""
+      t.string :encrypted_password, null: false, default: ""
+
+      ## Recoverable
+      t.string   :reset_password_token
+      t.datetime :reset_password_sent_at
+
+      ## Rememberable
+      t.datetime :remember_created_at
+
+      ## Trackable
+      t.integer  :sign_in_count, default: 0
+      t.datetime :current_sign_in_at
+      t.datetime :last_sign_in_at
+      t.string   :current_sign_in_ip
+      t.string   :last_sign_in_ip
+
+      ## Confirmable
+      t.string   :confirmation_token
+      t.datetime :confirmed_at
+      t.datetime :confirmation_sent_at
+      # t.string   :unconfirmed_email # Only if using reconfirmable
+
+      ## Lockable
+      t.integer  :failed_attempts, default: 0 # Only if lock strategy is :failed_attempts
+      t.string   :unlock_token # Only if unlock strategy is :email or :both
+      t.datetime :locked_at
+
+      t.timestamps null: false
+    end
+
+    create_table :admins do |t|
+      ## Database authenticatable
+      t.string :email,              null: true
+      t.string :encrypted_password, null: true
+
+      ## Recoverable
+      t.string   :reset_password_token
+      t.datetime :reset_password_sent_at
+
+      ## Rememberable
+      t.datetime :remember_created_at
+
+      ## Confirmable
+      t.string   :confirmation_token
+      t.datetime :confirmed_at
+      t.datetime :confirmation_sent_at
+      t.string   :unconfirmed_email # Only if using reconfirmable
+
+      ## Lockable
+      t.datetime :locked_at
+
+      ## Attribute for testing route blocks
+      t.boolean :active, default: false
+
+      t.timestamps null: false
+    end
+  end
+
+  def self.down
+    drop_table :users
+    drop_table :admins
+  end
+end
diff --git a/test/rails_app/db/schema.rb b/test/rails_app/db/schema.rb
new file mode 100644
index 0000000..a744605
--- /dev/null
+++ b/test/rails_app/db/schema.rb
@@ -0,0 +1,55 @@
+# encoding: UTF-8
+# This file is auto-generated from the current state of the database. Instead
+# of editing this file, please use the migrations feature of Active Record to
+# incrementally modify your database, and then regenerate this schema definition.
+#
+# Note that this schema.rb definition is the authoritative source for your
+# database schema. If you need to create the application database on another
+# system, you should be using db:schema:load, not running all the migrations
+# from scratch. The latter is a flawed and unsustainable approach (the more migrations
+# you'll amass, the slower it'll run and the greater likelihood for issues).
+#
+# It's strongly recommended that you check this file into your version control system.
+
+ActiveRecord::Schema.define(version: 20100401102949) do
+
+  create_table "admins", force: true do |t|
+    t.string   "email"
+    t.string   "encrypted_password"
+    t.string   "reset_password_token"
+    t.datetime "reset_password_sent_at"
+    t.datetime "remember_created_at"
+    t.string   "confirmation_token"
+    t.datetime "confirmed_at"
+    t.datetime "confirmation_sent_at"
+    t.string   "unconfirmed_email"
+    t.datetime "locked_at"
+    t.boolean  "active",                 default: false
+    t.datetime "created_at"
+    t.datetime "updated_at"
+  end
+
+  create_table "users", force: true do |t|
+    t.string   "username"
+    t.string   "facebook_token"
+    t.string   "email",                  default: "", null: false
+    t.string   "encrypted_password",     default: "", null: false
+    t.string   "reset_password_token"
+    t.datetime "reset_password_sent_at"
+    t.datetime "remember_created_at"
+    t.integer  "sign_in_count",          default: 0
+    t.datetime "current_sign_in_at"
+    t.datetime "last_sign_in_at"
+    t.string   "current_sign_in_ip"
+    t.string   "last_sign_in_ip"
+    t.string   "confirmation_token"
+    t.datetime "confirmed_at"
+    t.datetime "confirmation_sent_at"
+    t.integer  "failed_attempts",        default: 0
+    t.string   "unlock_token"
+    t.datetime "locked_at"
+    t.datetime "created_at"
+    t.datetime "updated_at"
+  end
+
+end
diff --git a/test/rails_app/lib/shared_admin.rb b/test/rails_app/lib/shared_admin.rb
new file mode 100644
index 0000000..e8c293e
--- /dev/null
+++ b/test/rails_app/lib/shared_admin.rb
@@ -0,0 +1,17 @@
+module SharedAdmin
+  extend ActiveSupport::Concern
+
+  included do
+    devise :database_authenticatable, :registerable,
+           :timeoutable, :recoverable, :lockable, :confirmable,
+           unlock_strategy: :time, lock_strategy: :none,
+           allow_unconfirmed_access_for: 2.weeks, reconfirmable: true
+
+    validates_length_of     :reset_password_token, minimum: 3, allow_blank: true
+    validates_uniqueness_of :email, allow_blank: true, if: :email_changed?
+  end
+
+  def raw_confirmation_token
+    @raw_confirmation_token
+  end
+end
diff --git a/test/rails_app/lib/shared_user.rb b/test/rails_app/lib/shared_user.rb
new file mode 100644
index 0000000..adb0e33
--- /dev/null
+++ b/test/rails_app/lib/shared_user.rb
@@ -0,0 +1,29 @@
+module SharedUser
+  extend ActiveSupport::Concern
+
+  included do
+    devise :database_authenticatable, :confirmable, :lockable, :recoverable,
+           :registerable, :rememberable, :timeoutable,
+           :trackable, :validatable, :omniauthable, password_length: 7..128
+
+    attr_accessor :other_key
+
+    # They need to be included after Devise is called.
+    extend ExtendMethods
+  end
+
+  def raw_confirmation_token
+    @raw_confirmation_token
+  end
+
+  module ExtendMethods
+    def new_with_session(params, session)
+      super.tap do |user|
+        if data = session["devise.facebook_data"]
+          user.email = data["email"]
+          user.confirmed_at = Time.now
+        end
+      end
+    end
+  end
+end
diff --git a/test/rails_app/lib/shared_user_without_omniauth.rb b/test/rails_app/lib/shared_user_without_omniauth.rb
new file mode 100644
index 0000000..df145e3
--- /dev/null
+++ b/test/rails_app/lib/shared_user_without_omniauth.rb
@@ -0,0 +1,13 @@
+module SharedUserWithoutOmniauth
+  extend ActiveSupport::Concern
+
+  included do
+    devise :database_authenticatable, :confirmable, :lockable, :recoverable,
+      :registerable, :rememberable, :timeoutable,
+      :trackable, :validatable
+  end
+
+  def raw_confirmation_token
+    @raw_confirmation_token
+  end
+end
diff --git a/test/rails_app/public/404.html b/test/rails_app/public/404.html
new file mode 100644
index 0000000..9a48320
--- /dev/null
+++ b/test/rails_app/public/404.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>The page you were looking for doesn't exist (404)</title>
+  <style type="text/css">
+    body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+    div.dialog {
+      width: 25em;
+      padding: 0 4em;
+      margin: 4em auto 0 auto;
+      border: 1px solid #ccc;
+      border-right-color: #999;
+      border-bottom-color: #999;
+    }
+    h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+  </style>
+</head>
+
+<body>
+  <!-- This file lives in public/404.html -->
+  <div class="dialog">
+    <h1>The page you were looking for doesn't exist.</h1>
+    <p>You may have mistyped the address or the page may have moved.</p>
+  </div>
+</body>
+</html>
diff --git a/test/rails_app/public/422.html b/test/rails_app/public/422.html
new file mode 100644
index 0000000..83660ab
--- /dev/null
+++ b/test/rails_app/public/422.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>The change you wanted was rejected (422)</title>
+  <style type="text/css">
+    body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+    div.dialog {
+      width: 25em;
+      padding: 0 4em;
+      margin: 4em auto 0 auto;
+      border: 1px solid #ccc;
+      border-right-color: #999;
+      border-bottom-color: #999;
+    }
+    h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+  </style>
+</head>
+
+<body>
+  <!-- This file lives in public/422.html -->
+  <div class="dialog">
+    <h1>The change you wanted was rejected.</h1>
+    <p>Maybe you tried to change something you didn't have access to.</p>
+  </div>
+</body>
+</html>
diff --git a/test/rails_app/public/500.html b/test/rails_app/public/500.html
new file mode 100644
index 0000000..b80307f
--- /dev/null
+++ b/test/rails_app/public/500.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>We're sorry, but something went wrong (500)</title>
+  <style type="text/css">
+    body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+    div.dialog {
+      width: 25em;
+      padding: 0 4em;
+      margin: 4em auto 0 auto;
+      border: 1px solid #ccc;
+      border-right-color: #999;
+      border-bottom-color: #999;
+    }
+    h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+  </style>
+</head>
+
+<body>
+  <!-- This file lives in public/500.html -->
+  <div class="dialog">
+    <h1>We're sorry, but something went wrong.</h1>
+    <p>We've been notified about this issue and we'll take a look at it shortly.</p>
+  </div>
+</body>
+</html>
diff --git a/test/rails_app/public/favicon.ico b/test/rails_app/public/favicon.ico
new file mode 100644
index 0000000..e69de29
diff --git a/test/routes_test.rb b/test/routes_test.rb
new file mode 100644
index 0000000..d3b3765
--- /dev/null
+++ b/test/routes_test.rb
@@ -0,0 +1,264 @@
+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})
+    assert_named_route "/users/sign_in", :new_user_session_path
+  end
+
+  test 'map create user session' do
+    assert_recognizes({controller: 'devise/sessions', action: 'create'}, {path: 'users/sign_in', method: :post})
+    assert_named_route "/users/sign_in", :user_session_path
+  end
+
+  test 'map destroy user session' do
+    assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: 'users/sign_out', method: :get})
+    assert_named_route "/users/sign_out", :destroy_user_session_path
+  end
+
+  test 'map new user confirmation' do
+    assert_recognizes({controller: 'devise/confirmations', action: 'new'}, 'users/confirmation/new')
+    assert_named_route "/users/confirmation/new", :new_user_confirmation_path
+  end
+
+  test 'map create user confirmation' do
+    assert_recognizes({controller: 'devise/confirmations', action: 'create'}, {path: 'users/confirmation', method: :post})
+    assert_named_route "/users/confirmation", :user_confirmation_path
+  end
+
+  test 'map show user confirmation' do
+    assert_recognizes({controller: 'devise/confirmations', action: 'show'}, {path: 'users/confirmation', method: :get})
+  end
+
+  test 'map new user password' do
+    assert_recognizes({controller: 'devise/passwords', action: 'new'}, 'users/password/new')
+    assert_named_route "/users/password/new", :new_user_password_path
+  end
+
+  test 'map create user password' do
+    assert_recognizes({controller: 'devise/passwords', action: 'create'}, {path: 'users/password', method: :post})
+    assert_named_route "/users/password", :user_password_path
+  end
+
+  test 'map edit user password' do
+    assert_recognizes({controller: 'devise/passwords', action: 'edit'}, 'users/password/edit')
+    assert_named_route "/users/password/edit", :edit_user_password_path
+  end
+
+  test 'map update user password' do
+    assert_recognizes({controller: 'devise/passwords', action: 'update'}, {path: 'users/password', method: :put})
+  end
+
+  test 'map new user unlock' do
+    assert_recognizes({controller: 'devise/unlocks', action: 'new'}, 'users/unlock/new')
+    assert_named_route "/users/unlock/new", :new_user_unlock_path
+  end
+
+  test 'map create user unlock' do
+    assert_recognizes({controller: 'devise/unlocks', action: 'create'}, {path: 'users/unlock', method: :post})
+    assert_named_route "/users/unlock", :user_unlock_path
+  end
+
+  test 'map show user unlock' do
+    assert_recognizes({controller: 'devise/unlocks', action: 'show'}, {path: 'users/unlock', method: :get})
+  end
+
+  test 'map new user registration' do
+    assert_recognizes({controller: 'devise/registrations', action: 'new'}, 'users/sign_up')
+    assert_named_route "/users/sign_up", :new_user_registration_path
+  end
+
+  test 'map create user registration' do
+    assert_recognizes({controller: 'devise/registrations', action: 'create'}, {path: 'users', method: :post})
+    assert_named_route "/users", :user_registration_path
+  end
+
+  test 'map edit user registration' do
+    assert_recognizes({controller: 'devise/registrations', action: 'edit'}, {path: 'users/edit', method: :get})
+    assert_named_route "/users/edit", :edit_user_registration_path
+  end
+
+  test 'map update user registration' do
+    assert_recognizes({controller: 'devise/registrations', action: 'update'}, {path: 'users', method: :put})
+  end
+
+  test 'map destroy user registration' do
+    assert_recognizes({controller: 'devise/registrations', action: 'destroy'}, {path: 'users', method: :delete})
+  end
+
+  test 'map cancel user registration' do
+    assert_recognizes({controller: 'devise/registrations', action: 'cancel'}, {path: 'users/cancel', method: :get})
+    assert_named_route "/users/cancel", :cancel_user_registration_path
+  end
+
+  test 'map omniauth callbacks' do
+    assert_recognizes({controller: 'users/omniauth_callbacks', action: 'facebook'}, {path: 'users/auth/facebook/callback', method: :get})
+    assert_recognizes({controller: 'users/omniauth_callbacks', action: 'facebook'}, {path: 'users/auth/facebook/callback', method: :post})
+    assert_named_route "/users/auth/facebook/callback", :user_omniauth_callback_path, :facebook
+
+    # named open_id
+    assert_recognizes({controller: 'users/omniauth_callbacks', action: 'google'}, {path: 'users/auth/google/callback', method: :get})
+    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_recognizes({controller: 'ysers/omniauth_callbacks', action: 'twitter'}, {path: 'users/auth/twitter/callback', method: :get})
+    end
+  end
+
+  protected
+
+  def assert_named_route(result, *args)
+    assert_equal result, @routes.url_helpers.send(*args)
+  end
+end
+
+class CustomizedRoutingTest < ActionController::TestCase
+  test 'map admin with :path option' do
+    assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'admin_area/sign_up', method: :get})
+  end
+
+  test 'map admin with :controllers option' do
+    assert_recognizes({controller: 'admins/sessions', action: 'new'}, {path: 'admin_area/sign_in', method: :get})
+  end
+
+  test 'does not map admin password' do
+    assert_raise ExpectedRoutingError do
+      assert_recognizes({controller: 'devise/passwords', action: 'new'}, 'admin_area/password/new')
+    end
+  end
+
+  test 'subdomain admin' do
+    assert_recognizes({"host"=>"sub.example.com", controller: 'devise/sessions', action: 'new'}, {host: "sub.example.com", path: '/sub_admin/sign_in', method: :get})
+  end
+
+  test 'does only map reader password' 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')
+  end
+
+  test 'map account with custom path name for session sign in' do
+    assert_recognizes({controller: 'devise/sessions', action: 'new', locale: 'en'}, '/en/accounts/login')
+  end
+
+  test 'map account with custom path name for session sign out' do
+    assert_recognizes({controller: 'devise/sessions', action: 'destroy', locale: 'en'}, '/en/accounts/logout')
+  end
+
+  test 'map account with custom path name for password' do
+    assert_recognizes({controller: 'devise/passwords', action: 'new', locale: 'en'}, '/en/accounts/secret/new')
+  end
+
+  test 'map account with custom path name for registration' do
+    assert_recognizes({controller: 'devise/registrations', action: 'new', locale: 'en'}, '/en/accounts/management/register')
+  end
+
+  test 'map account with custom path name for edit registration' do
+    assert_recognizes({controller: 'devise/registrations', action: 'edit', locale: 'en'}, '/en/accounts/management/edit/profile')
+  end
+
+  test 'map account with custom path name for cancel registration' do
+    assert_recognizes({controller: 'devise/registrations', action: 'cancel', locale: 'en'}, '/en/accounts/management/giveup')
+  end
+
+  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_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_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/posts/sign_out', method: :get})
+    end
+  end
+
+  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_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_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_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_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_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_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_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_recognizes({controller: 'devise/unlocks', action: 'show'}, {path: '/htmlonly_users/unlock.xml', method: :get})
+    end
+  end
+
+  test 'map with format false is not permanent' do
+    assert_equal "/set.xml", @routes.url_helpers.set_path(:xml)
+  end
+
+  test 'checks if mapping has proper configuration for omniauth callback' do
+    e = assert_raise ArgumentError do
+      routes = ActionDispatch::Routing::RouteSet.new
+      routes.draw do
+        devise_for :not_omniauthable, class_name: 'Admin', controllers: {omniauth_callbacks: "users/omniauth_callbacks"}
+      end
+    end
+    assert_match "Mapping omniauth_callbacks on a resource that is not omniauthable", e.message
+  end
+end
+
+class ScopedRoutingTest < ActionController::TestCase
+  test 'map publisher account' do
+    assert_recognizes({controller: 'publisher/registrations', action: 'new'}, {path: '/publisher/accounts/sign_up', method: :get})
+    assert_equal '/publisher/accounts/sign_up', @routes.url_helpers.new_publisher_account_registration_path
+  end
+
+  test 'map publisher account merges path names' do
+    assert_recognizes({controller: 'publisher/sessions', action: 'new'}, {path: '/publisher/accounts/get_in', method: :get})
+    assert_equal '/publisher/accounts/get_in', @routes.url_helpers.new_publisher_account_session_path
+  end
+end
diff --git a/test/support/action_controller/record_identifier.rb b/test/support/action_controller/record_identifier.rb
new file mode 100644
index 0000000..89b3483
--- /dev/null
+++ b/test/support/action_controller/record_identifier.rb
@@ -0,0 +1,10 @@
+# Since webrat uses ActionController::RecordIdentifier class that was moved to
+# ActionView namespace in Rails 4.1+
+
+unless defined?(ActionController::RecordIdentifier)
+  require 'action_view/record_identifier'
+
+  module ActionController
+    RecordIdentifier = ActionView::RecordIdentifier
+  end
+end
diff --git a/test/support/assertions.rb b/test/support/assertions.rb
new file mode 100644
index 0000000..864999e
--- /dev/null
+++ b/test/support/assertions.rb
@@ -0,0 +1,39 @@
+require 'active_support/test_case'
+
+class ActiveSupport::TestCase
+  def assert_not(assertion)
+    assert !assertion
+  end
+
+  def assert_blank(assertion)
+    assert assertion.blank?
+  end
+
+  def assert_present(assertion)
+    assert assertion.present?
+  end
+
+  def assert_email_sent(address = nil, &block)
+    assert_difference('ActionMailer::Base.deliveries.size', &block)
+    if address.present?
+      assert_equal address, ActionMailer::Base.deliveries.last['to'].to_s
+    end
+  end
+
+  def assert_email_not_sent(&block)
+    assert_no_difference('ActionMailer::Base.deliveries.size', &block)
+  end
+
+  def assert_same_content(result, expected)
+    assert expected.size == result.size, "the arrays doesn't have the same size"
+    expected.each do |element|
+      assert result.include?(element), "The array doesn't include '#{element}'."
+    end
+  end
+
+  def assert_raise_with_message(exception_klass, message, &block)
+    exception = assert_raise exception_klass, &block
+    assert_equal exception.message, message,
+      "The expected message was #{message} but your exception throwed #{exception.message}"
+  end
+end
diff --git a/test/support/helpers.rb b/test/support/helpers.rb
new file mode 100644
index 0000000..02e5c8d
--- /dev/null
+++ b/test/support/helpers.rb
@@ -0,0 +1,73 @@
+require 'active_support/test_case'
+
+class ActiveSupport::TestCase
+  VALID_AUTHENTICATION_TOKEN = 'AbCdEfGhIjKlMnOpQrSt'.freeze
+
+  def setup_mailer
+    ActionMailer::Base.deliveries = []
+  end
+
+  def store_translations(locale, translations, &block)
+    # Calling 'available_locales' before storing the translations to ensure
+    # that the I18n backend will be initialized before we store our custom
+    # translations, so they will always override the translations for the
+    # YML file.
+    I18n.available_locales
+    I18n.backend.store_translations(locale, translations)
+    yield
+  ensure
+    I18n.reload!
+  end
+
+  def generate_unique_email
+    @@email_count ||= 0
+    @@email_count += 1
+    "test#{@@email_count}@example.com"
+  end
+
+  def valid_attributes(attributes={})
+    { username: "usertest",
+      email: generate_unique_email,
+      password: '12345678',
+      password_confirmation: '12345678' }.update(attributes)
+  end
+
+  def new_user(attributes={})
+    User.new(valid_attributes(attributes))
+  end
+
+  def create_user(attributes={})
+    User.create!(valid_attributes(attributes))
+  end
+
+  def create_admin(attributes={})
+    valid_attributes = valid_attributes(attributes)
+    valid_attributes.delete(:username)
+    Admin.create!(valid_attributes)
+  end
+
+  # Execute the block setting the given values and restoring old values after
+  # the block is executed.
+  def swap(object, new_values)
+    old_values = {}
+    new_values.each do |key, value|
+      old_values[key] = object.send key
+      object.send :"#{key}=", value
+    end
+    clear_cached_variables(new_values)
+    yield
+  ensure
+    clear_cached_variables(new_values)
+    old_values.each do |key, value|
+      object.send :"#{key}=", value
+    end
+  end
+
+  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)
+      end
+    end
+  end
+end
diff --git a/test/support/integration.rb b/test/support/integration.rb
new file mode 100644
index 0000000..39111d5
--- /dev/null
+++ b/test/support/integration.rb
@@ -0,0 +1,92 @@
+require 'action_dispatch/testing/integration'
+
+class ActionDispatch::IntegrationTest
+  def warden
+    request.env['warden']
+  end
+
+  def create_user(options={})
+    @user ||= begin
+      user = User.create!(
+        username: 'usertest',
+        email: options[:email] || 'user at test.com',
+        password: options[:password] || '12345678',
+        password_confirmation: options[:password] || '12345678',
+        created_at: Time.now.utc
+      )
+      user.update_attribute(:confirmation_sent_at, options[:confirmation_sent_at]) if options[:confirmation_sent_at]
+      user.confirm! unless options[:confirm] == false
+      user.lock_access! if options[:locked] == true
+      user
+    end
+  end
+
+  def create_admin(options={})
+    @admin ||= begin
+      admin = Admin.create!(
+        email: options[:email] || 'admin at test.com',
+        password: '123456', password_confirmation: '123456',
+        active: options[:active]
+      )
+      admin.confirm! unless options[:confirm] == false
+      admin
+    end
+  end
+
+  def sign_in_as_user(options={}, &block)
+    user = create_user(options)
+    visit_with_option options[:visit], new_user_session_path
+    fill_in 'email', with: options[:email] || 'user at test.com'
+    fill_in 'password', with: options[:password] || '12345678'
+    check 'remember me' if options[:remember_me] == true
+    yield if block_given?
+    click_button 'Log In'
+    user
+  end
+
+  def sign_in_as_admin(options={}, &block)
+    admin = create_admin(options)
+    visit_with_option options[:visit], new_admin_session_path
+    fill_in 'email', with: 'admin at test.com'
+    fill_in 'password', with: '123456'
+    yield if block_given?
+    click_button 'Log In'
+    admin
+  end
+
+  # Fix assert_redirect_to in integration sessions because they don't take into
+  # account Middleware redirects.
+  #
+  def assert_redirected_to(url)
+    assert [301, 302].include?(@integration_session.status),
+           "Expected status to be 301 or 302, got #{@integration_session.status}"
+
+    assert_url url, @integration_session.headers["Location"]
+  end
+
+  def assert_current_url(expected)
+    assert_url expected, current_url
+  end
+
+  def assert_url(expected, actual)
+    assert_equal prepend_host(expected), prepend_host(actual)
+  end
+
+  protected
+
+    def visit_with_option(given, default)
+      case given
+      when String
+        visit given
+      when FalseClass
+        # Do nothing
+      else
+        visit default
+      end
+    end
+
+    def prepend_host(url)
+      url = "http://#{request.host}#{url}" if url[0] == ?/
+      url
+    end
+end
diff --git a/test/support/locale/en.yml b/test/support/locale/en.yml
new file mode 100644
index 0000000..e1f977b
--- /dev/null
+++ b/test/support/locale/en.yml
@@ -0,0 +1,8 @@
+en:
+  devise:
+    failure:
+      user:
+        does_not_exist: "User %{name} does not exist"
+  errors:
+    messages:
+      taken: "has already been taken"
diff --git a/test/support/mongoid.yml b/test/support/mongoid.yml
new file mode 100644
index 0000000..243ca14
--- /dev/null
+++ b/test/support/mongoid.yml
@@ -0,0 +1,6 @@
+test:
+  sessions:
+    default:
+      database: devise-test-suite
+      hosts:
+        - localhost:<%= ENV['MONGODB_PORT'] || '27017' %>
diff --git a/test/support/webrat/integrations/rails.rb b/test/support/webrat/integrations/rails.rb
new file mode 100644
index 0000000..03821d2
--- /dev/null
+++ b/test/support/webrat/integrations/rails.rb
@@ -0,0 +1,24 @@
+require 'webrat/core/elements/form'
+require 'action_dispatch/testing/integration'
+
+module Webrat
+  Form.class_eval do
+    def self.parse_rails_request_params(params)
+      Rack::Utils.parse_nested_query(params)
+    end
+  end
+
+  module Logging
+    # Avoid RAILS_DEFAULT_LOGGER deprecation warning
+    def logger # :nodoc:
+      ::Rails.logger
+    end
+  end
+end
+
+module ActionDispatch #:nodoc:
+  IntegrationTest.class_eval do
+    include Webrat::Methods
+    include Webrat::Matchers
+  end
+end
diff --git a/test/test_helper.rb b/test/test_helper.rb
new file mode 100644
index 0000000..9f36b48
--- /dev/null
+++ b/test/test_helper.rb
@@ -0,0 +1,34 @@
+ENV["RAILS_ENV"] = "test"
+DEVISE_ORM = (ENV["DEVISE_ORM"] || :active_record).to_sym
+
+$:.unshift File.dirname(__FILE__)
+puts "\n==> Devise.orm = #{DEVISE_ORM.inspect}"
+
+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/setup'
+require 'webrat'
+Webrat.configure do |config|
+  config.mode = :rails
+  config.open_error_files = false
+end
+
+if ActiveSupport.respond_to?(:test_order)
+  ActiveSupport.test_order = :random
+end
+
+OmniAuth.config.logger = Logger.new('/dev/null')
+
+# Add support to load paths so we can overwrite broken webrat setup
+$:.unshift File.expand_path('../support', __FILE__)
+Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
+
+# For generators
+require "rails/generators/test_case"
+require "generators/devise/install_generator"
+require "generators/devise/views_generator"
+require "generators/devise/controllers_generator"
diff --git a/test/test_helpers_test.rb b/test/test_helpers_test.rb
new file mode 100644
index 0000000..fd1a202
--- /dev/null
+++ b/test/test_helpers_test.rb
@@ -0,0 +1,163 @@
+require 'test_helper'
+
+class TestHelpersTest < ActionController::TestCase
+  tests UsersController
+  include Devise::TestHelpers
+
+  test "redirects if attempting to access a page unauthenticated" do
+    get :index
+    assert_redirected_to new_user_session_path
+    assert_equal "You need to sign in or sign up before continuing.", flash[:alert]
+  end
+
+  test "redirects if attempting to access a page with an unconfirmed account" do
+    swap Devise, allow_unconfirmed_access_for: 0.days do
+      user = create_user
+      assert !user.active_for_authentication?
+
+      sign_in user
+      get :index
+      assert_redirected_to new_user_session_path
+    end
+  end
+
+  test "returns nil if accessing current_user with an unconfirmed account" do
+    swap Devise, allow_unconfirmed_access_for: 0.days do
+      user = create_user
+      assert !user.active_for_authentication?
+
+      sign_in user
+      get :accept, id: user
+      assert_nil assigns(:current_user)
+    end
+  end
+
+  test "does not redirect with valid user" do
+    user = create_user
+    user.confirm!
+
+    sign_in user
+    get :index
+    assert_response :success
+  end
+
+  test "does not redirect with valid user after failed first attempt" do
+    get :index
+    assert_response :redirect
+
+    user = create_user
+    user.confirm!
+
+    sign_in user
+    get :index
+    assert_response :success
+  end
+
+  test "redirects if valid user signed out" do
+    user = create_user
+    user.confirm!
+
+    sign_in user
+    get :index
+
+    sign_out user
+    get :index
+    assert_redirected_to new_user_session_path
+  end
+
+  test "respects custom failure app" do
+    custom_failure_app = Class.new(Devise::FailureApp) do
+      def redirect
+        self.status = 306
+      end
+    end
+
+    swap Devise.warden_config, failure_app: custom_failure_app do
+      get :index
+      assert_response 306
+    end
+  end
+
+  test "passes given headers from the failure app to the response" do
+    custom_failure_app = Class.new(Devise::FailureApp) do
+      def respond
+        self.status = 401
+        self.response.headers["CUSTOMHEADER"] = 1
+      end
+    end
+
+    swap Devise.warden_config, failure_app: custom_failure_app do
+      sign_in create_user
+      get :index
+      assert_equal 1, @response.headers["CUSTOMHEADER"]
+    end
+  end
+
+  test "returns the body of a failure app" do
+    get :index
+    assert_equal response.body, "<html><body>You are being <a href=\"http://test.host/users/sign_in\">redirected</a>.</body></html>"
+  end
+
+  test "defined Warden after_authentication callback should not be called when sign_in is called" do
+    begin
+      Warden::Manager.after_authentication do |user, auth, opts|
+        flunk "callback was called while it should not"
+      end
+
+      user = create_user
+      user.confirm!
+      sign_in user
+    ensure
+      Warden::Manager._after_set_user.pop
+    end
+  end
+
+  test "defined Warden before_logout callback should not be called when sign_out is called" do
+    begin
+      Warden::Manager.before_logout do |user, auth, opts|
+        flunk "callback was called while it should not"
+      end
+      user = create_user
+      user.confirm!
+
+      sign_in user
+      sign_out user
+    ensure
+      Warden::Manager._before_logout.pop
+    end
+  end
+
+  test "before_failure call should work" do
+    begin
+      executed = false
+      Warden::Manager.before_failure do |env,opts|
+        executed = true
+      end
+
+      user = create_user
+      sign_in user
+
+      get :index
+      assert executed
+    ensure
+      Warden::Manager._before_failure.pop
+    end
+  end
+
+  test "allows to sign in with different users" do
+    first_user = create_user
+    first_user.confirm!
+
+    sign_in first_user
+    get :index
+    assert_match /User ##{first_user.id}/, @response.body
+    sign_out first_user
+
+    second_user = create_user
+    second_user.confirm!
+
+    sign_in second_user
+    get :index
+    assert_match /User ##{second_user.id}/, @response.body
+  end
+end
diff --git a/test/test_models.rb b/test/test_models.rb
new file mode 100644
index 0000000..ee19b84
--- /dev/null
+++ b/test/test_models.rb
@@ -0,0 +1,33 @@
+class Configurable < User
+  devise :database_authenticatable, :confirmable, :rememberable, :timeoutable, :lockable,
+         stretches: 15, pepper: 'abcdef', allow_unconfirmed_access_for: 5.days,
+         remember_for: 7.days, timeout_in: 15.minutes, unlock_in: 10.days
+end
+
+class WithValidation < Admin
+  devise :database_authenticatable, :validatable, password_length: 2..6
+end
+
+class UserWithValidation < User
+  validates_presence_of :username
+end
+
+class UserWithCustomEncryption < User
+  protected
+  def password_digest(password)
+    password.reverse
+  end
+end
+
+class UserWithVirtualAttributes < User
+  devise case_insensitive_keys: [ :email, :email_confirmation ]
+  validates :email, presence: true, confirmation: {on: :create}
+end
+
+class Several < Admin
+  devise :validatable
+  devise :lockable
+end
+
+class Inheritable < Admin
+end

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-ruby-extras/ruby-devise.git



More information about the Pkg-ruby-extras-commits mailing list