devise-4.7.1/0000755000004100000410000000000013541606342013036 5ustar www-datawww-datadevise-4.7.1/README.md0000644000004100000410000007441713541606342014332 0ustar www-datawww-data![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.svg?branch=master)](http://travis-ci.org/plataformatec/devise) [![Code Climate](https://codeclimate.com/github/plataformatec/devise.svg)](https://codeclimate.com/github/plataformatec/devise) 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 only what you really need. It's composed of 10 modules: * [Database Authenticatable](http://www.rubydoc.info/github/plataformatec/devise/master/Devise/Models/DatabaseAuthenticatable): hashes 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://www.rubydoc.info/github/plataformatec/devise/master/Devise/Models/Omniauthable): adds OmniAuth (https://github.com/omniauth/omniauth) support. * [Confirmable](http://www.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://www.rubydoc.info/github/plataformatec/devise/master/Devise/Models/Recoverable): resets the user password and sends reset instructions. * [Registerable](http://www.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://www.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://www.rubydoc.info/github/plataformatec/devise/master/Devise/Models/Trackable): tracks sign in count, timestamps and IP address. * [Timeoutable](http://www.rubydoc.info/github/plataformatec/devise/master/Devise/Models/Timeoutable): expires sessions that have not been active in a specified period of time. * [Validatable](http://www.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://www.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. ## Table of Contents - [Information](#information) - [The Devise wiki](#the-devise-wiki) - [Bug reports](#bug-reports) - [StackOverflow and Mailing List](#stackoverflow-and-mailing-list) - [RDocs](#rdocs) - [Example applications](#example-applications) - [Extensions](#extensions) - [Contributing](#contributing) - [Starting with Rails?](#starting-with-rails) - [Getting started](#getting-started) - [Controller filters and helpers](#controller-filters-and-helpers) - [Configuring Models](#configuring-models) - [Strong Parameters](#strong-parameters) - [Configuring views](#configuring-views) - [Configuring controllers](#configuring-controllers) - [Configuring routes](#configuring-routes) - [I18n](#i18n) - [Test helpers](#test-helpers) - [Controller tests](#controller-tests) - [Integration tests](#integration-tests) - [OmniAuth](#omniauth) - [Configuring multiple models](#configuring-multiple-models) - [ActiveJob Integration](#activejob-integration) - [Password reset tokens and Rails logs](#password-reset-tokens-and-rails-logs) - [Other ORMs](#other-orms) - [Rails API mode](#rails-api-mode) - [Additional information](#additional-information) - [Heroku](#heroku) - [Warden](#warden) - [Contributors](#contributors) - [License](#license) ## 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 have discovered a security related bug, please do *NOT* use the GitHub issue tracker. Send an email to opensource@plataformatec.com.br. ### StackOverflow and Mailing List If you have any questions, comments, or concerns, please use StackOverflow instead of the GitHub issue tracker: http://stackoverflow.com/questions/tagged/devise The deprecated mailing list can still be read on 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 `bin/test`. Devise works with multiple Ruby and Rails versions, and ActiveRecord and Mongoid ORMs, which means you can run the test suite with some modifiers: `DEVISE_ORM` and `BUNDLE_GEMFILE`. ### DEVISE_ORM Since Devise support both Mongoid and ActiveRecord, we rely on this variable to run specific code for each ORM. The default value of `DEVISE_ORM` is `active_record`. To run the tests for mongoid, you can pass `mongoid`: ``` DEVISE_ORM=mongoid bin/test ==> Devise.orm = :mongoid ``` When running the tests for Mongoid, you will need to have a MongoDB server (version 2.0 or newer) running on your system. Please note that the command output will show the variable value being used. ### BUNDLE_GEMFILE We can use this variable to tell bundler what Gemfile it should use (instead of the one in the current directory). Inside the [gemfiles](https://github.com/plataformatec/devise/tree/master/gemfiles) directory, we have one for each version of Rails we support. When you send us a pull request, it may happen that the test suite breaks on Travis using some of them. If that's the case, you can simulate the same environment using the `BUNDLE_GEMFILE` variable. For example, if the tests broke using Ruby 2.4.2 and Rails 4.1, you can do the following: ```bash rbenv shell 2.4.2 # or rvm use 2.4.2 BUNDLE_GEMFILE=gemfiles/Gemfile.rails-4.1-stable bundle install BUNDLE_GEMFILE=gemfiles/Gemfile.rails-4.1-stable bin/test ``` You can also combine both of them if the tests broke for Mongoid: ```bash BUNDLE_GEMFILE=gemfiles/Gemfile.rails-4.1-stable bundle install BUNDLE_GEMFILE=gemfiles/Gemfile.rails-4.1-stable DEVISE_ORM=mongoid bin/test ``` ### Running tests Devise uses [Mini Test](https://github.com/seattlerb/minitest) as test framework. * Running all tests: ```bash bin/test ``` * Running tests for an specific file: ```bash bin/test test/models/trackable_test.rb ``` * Running a specific test given a regex: ```bash bin/test test/models/trackable_test.rb:16 ``` ## Starting with Rails? If you are building your first Rails application, we recommend you *do 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 three resources that should help you get started: * Michael Hartl's online book: https://www.railstutorial.org/book/modeling_users * Ryan Bates' Railscast: http://railscasts.com/episodes/250-authentication-from-scratch * Codecademy's Ruby on Rails: Authentication and Authorization: https://www.codecademy.com/learn/rails-auth Once you have solidified your understanding of Rails and authentication mechanisms, we assure you Devise will be very pleasant to work with. :smiley: ## Getting started Devise 4.0 works with Rails 4.1 onwards. Add the following line to your Gemfile: ```ruby gem 'devise' ``` Then run `bundle install` Next, you need to run the generator: ```console $ rails generate devise:install ``` At this point, a number of instructions will appear in the console. Among these instructions, you'll 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 } ``` The generator will install an initializer which describes ALL of Devise's configuration options. It is *imperative* that you take a look at it. When you are done, you are ready to add Devise to any of your models using the generator. In the following command you will 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 the default Devise modules. The generator also configures your `config/routes.rb` file to point to the Devise controller. ```console $ rails generate devise MODEL ``` 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 `rails db:migrate` You should restart your application after changing Devise's configuration options (this includes stopping spring). Otherwise, you will run into strange errors, for example, 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! ``` For Rails 5, note that `protect_from_forgery` is no longer prepended to the `before_action` chain, so if you have set `authenticate_user` before `protect_from_forgery`, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or use `protect_from_forgery prepend: true`. 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 to. For instance, when using 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 hashing algorithm with: ```ruby devise :database_authenticatable, :registerable, :confirmable, :recoverable, stretches: 12 ``` 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. This file is usually located at `/config/initializers/devise.rb`. ### Strong Parameters ![The Parameter Sanitizer API has changed for Devise 4](http://messages.hellobits.com/warning.svg?message=The%20Parameter%20Sanitizer%20API%20has%20changed%20for%20Devise%204) *For previous Devise versions see https://github.com/plataformatec/devise/tree/3-stable#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 allow any set of parameters to be passed down to the model, therefore requiring sanitization. Their names and default permitted parameters 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 so using 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.permit(:sign_up, keys: [: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: ```ruby class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, address_attributes: [:country, :state, :city, :area, :postal_code]]) end end ``` 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.permit(:sign_in) do |user_params| user_params.permit(:username, :email) end 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 in the following way: ```ruby def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up) do |user_params| user_params.permit({ roles: [] }, :email, :password, :password_confirmation) end 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 a different parameter sanitizer per model. In this case, we recommend inheriting from `Devise::ParameterSanitizer` and adding your own logic: ```ruby class User::ParameterSanitizer < Devise::ParameterSanitizer def initialize(*) super permit(:sign_up, keys: [: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 would like to generate only a few sets of views, like the ones for the `registerable` 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 `users` as the scope, controllers will be created in `app/controllers/users/`. And the sessions controller will look like this: ```ruby class Users::SessionsController < Devise::SessionsController # GET /resource/sign_in # def new # super # end ... end ``` (Use the -c flag to specify a controller, for example: `rails generate devise:controllers users -c=sessions`) 2. Tell the router to use this controller: ```ruby devise_for :users, controllers: { sessions: 'users/sessions' } ``` 3. Copy the views from `devise/sessions` to `users/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 Users::SessionsController < Devise::SessionsController def create # custom sign-in code end end ``` Or you can simply add new behaviour to it: ```ruby class Users::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 unsuccessful. 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](http://www.rubydoc.info/github/plataformatec/devise/master/ActionDispatch/Routing/Mapper%3Adevise_for) 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 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. Please note: You will still need to add `devise_for` in your routes in order to use helper methods such as `current_user`. ```ruby devise_for :users, skip: :all ``` ### I18n Devise uses flash messages with I18n, in conjunction 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 controller and integration tests. In order to use them, you need to include the respective module in your test cases/specs. ### Controller tests Controller tests require that you include `Devise::Test::ControllerHelpers` on your test case or its parent `ActionController::TestCase` superclass. For Rails 5, include `Devise::Test::IntegrationHelpers` instead, since the superclass for controller tests has been changed to ActionDispatch::IntegrationTest (for more details, see the [Integration tests](#integration-tests) section). ```ruby class PostsControllerTest < ActionController::TestCase include Devise::Test::ControllerHelpers 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::Test::ControllerHelpers, type: :controller config.include Devise::Test::ControllerHelpers, type: :view end ``` Just be sure that this inclusion is made *after* the `require 'rspec/rails'` directive. Now you are ready to use the `sign_in` and `sign_out` methods on your controller tests: ```ruby sign_in @user sign_in @user, scope: :admin ``` 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 controller tests do not pass through the router, it needs to be stated explicitly. For example, if you are testing the user scope, simply use: ```ruby test 'GET new' do # Mimic the router behavior of setting the Devise scope through the env. @request.env['devise.mapping'] = Devise.mappings[:user] # Use the sign_in helper to sign in a fixture `User` record. sign_in users(:alice) get :new # assert something end ``` ### Integration tests Integration test helpers are available by including the `Devise::Test::IntegrationHelpers` module. ```ruby class PostsTests < ActionDispatch::IntegrationTest include Devise::Test::IntegrationHelpers end ``` Now you can use the following `sign_in` and `sign_out` methods in your integration tests: ```ruby sign_in users(:bob) sign_in users(:bob), scope: :admin sign_out :user ``` RSpec users can include the `IntegrationHelpers` module on their `:feature` specs. ```ruby RSpec.configure do |config| config.include Devise::Test::IntegrationHelpers, type: :feature end ``` Unlike controller tests, integration tests do not need to supply the `devise.mapping` `env` value, as the mapping can be inferred by the routes that are executed in your tests. You can read more about testing your Rails 3 - Rails 4 controllers with RSpec in the wiki: * https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-(and-RSpec) ### OmniAuth Devise comes with OmniAuth support out of the box to authenticate with other providers. To use it, simply 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 null: false end # Inside your Admin model devise :database_authenticatable, :timeoutable # Inside your routes devise_for :admins # Inside your protected controller before_action :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 that you 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 queuing back-end, 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 ``` ### Password reset tokens and Rails logs If you enable the [Recoverable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Recoverable) module, note that a stolen password reset token could give an attacker access to your application. Devise takes effort to generate random, secure tokens, and stores only token digests in the database, never plaintext. However the default logging behavior in Rails can cause plaintext tokens to leak into log files: 1. Action Mailer logs the entire contents of all outgoing emails to the DEBUG level. Password reset tokens delivered to users in email will be leaked. 2. Active Job logs all arguments to every enqueued job at the INFO level. If you configure Devise to use `deliver_later` to send password reset emails, password reset tokens will be leaked. Rails sets the production logger level to DEBUG by default. Consider changing your production logger level to WARN if you wish to prevent tokens from being leaked into your logs. In `config/environments/production.rb`: ```ruby config.log_level = :warn ``` ### Other ORMs Devise supports ActiveRecord (default) and Mongoid. To select another ORM, simply require it in the initializer file. ### Rails API Mode Rails 5+ has a built-in [API Mode](https://edgeguides.rubyonrails.org/api_app.html) which optimizes Rails for use as an API (only). One of the side effects is that it changes the order of the middleware stack, and this can cause problems for `Devise::Test::IntegrationHelpers`. This problem usually surfaces as an ```undefined method `[]=' for nil:NilClass``` error when using integration test helpers, such as `#sign_in`. The solution is simply to reorder the middlewares by adding the following to test.rb: ```ruby Rails.application.config.middleware.insert_before Warden::Manager, ActionDispatch::Cookies Rails.application.config.middleware.insert_before Warden::Manager, ActionDispatch::Session::CookieStore ``` For a deeper understanding of this, review [this issue](https://github.com/plataformatec/devise/issues/4696). ## Additional information ### Heroku Using Devise on Heroku with Ruby on Rails 3.2 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-2019 Plataformatec. http://plataformatec.com.br You are not granted rights or licenses to the trademarks of Plataformatec, including without limitation the Devise name or logo. devise-4.7.1/CHANGELOG.md0000644000004100000410000003754313541606342014663 0ustar www-datawww-data### Unreleased ### 4.7.1 - 2019-09-06 * bug fixes * Fix an edge case where records with a blank `confirmation_token` could be confirmed (by @tegon) * Fix typo inside `update_needs_confirmation` i18n key (by @lslm) ### 4.7.0 - 2019-08-19 * enhancements * Support Rails 6.0 * Update CI to rails 6.0.0.beta3 (by @tunnes) * refactor method name to be more consistent (by @saiqulhaq) * Fix rails 6.0.rc1 email uniqueness validation deprecation warning (by @Vasfed) * bug fixes * Add `autocomplete="new-password"` to `password_confirmation` fields (by @ferrl) * Fix rails_51_and_up? method for Rails 6.rc1 (by @igorkasyanchuk) ### 4.6.2 - 2019-03-26 * bug fixes * Revert "Set `encrypted_password` to `nil` when `password` is set to `nil`" since it broke backward compatibility with existing applications. See more on https://github.com/plataformatec/devise/issues/5033#issuecomment-476386275 (by @mracos) ### 4.6.1 - 2019-02-11 * bug fixes * Check if `root_path` is defined with `#respond_to?` instead of `#present` (by @tegon) ### 4.6.0 - 2019-02-07 * enhancements * Allow to skip email and password change notifications (by @iorme1) * Include the use of `nil` for `allow_unconfirmed_access_for` in the docs (by @joaumg) * Ignore useless files into the `.gem` file (by @huacnlee) * Explain the code that prevents enumeration attacks inside `Devise::Strategies::DatabaseAuthenticatable` (by @tegon) * Refactor the `devise_error_messages!` helper to render a partial (by @prograhamer) * Add an option (`Devise.sign_in_after_change_password`) to not automatically sign in a user after changing a password (by @knjko) * bug fixes * Fix missing comma in Simple Form generator (by @colinross) * Fix error with migration generator in Rails 6 (by @oystersauce8) * Set `encrypted_password` to `nil` when `password` is set to `nil` (by @sivagollapalli) * Consider whether the request supports flash messages inside `Devise::Controllers::Helpers#is_flashing_format?` (by @colinross) * Fix typo inside `Devise::Generators::ControllersGenerator` (by @kopylovvlad) * Sanitize parameters inside `Devise::Models::Authenticatable#find_or_initialize_with_errors` (by @rlue) * `#after_database_authentication` callback was not called after authentication on password reset (by @kanmaniselvan) * Fix corner case when `#confirmation_period_valid?` was called at the same second as `confirmation_sent_at` was set. Mostly true for date types that only have second precisions. (by @stanhu) * Fix unclosed `li` tag in `error_messages` partial (by @mracos) * Fix Routes issue when devise engine is mounted in another engine on Rails versions lower than 5.1 (by @a-barbieri) * Make `#increment_failed_attempts` concurrency safe (by @tegon) * Apply Test Helper fix to Rails 6.0 as well as 5.x (by @matthewrudy) * deprecations * The second argument of `DatabaseAuthenticatable`'s `#update_with_password` and `#update_without_password` is deprecated and will be removed in the next major version. It was added to support a feature deprecated in Rails 4, so you can safely remove it from your code. (by @ihatov08) * The `DeviseHelper.devise_error_messages!` is deprecated and will be removed in the next major version. Use the `devise/shared/error_messages` partial instead. (by @mracos) ### 4.5.0 - 2018-08-15 * enhancements * Use `before_action` instead of `before_filter` (by @edenthecat) * Allow people to extend devise failure app, through invoking `ActiveSupport.run_load_hooks` once `Devise::FailureApp` is loaded (by @wnm) * Use `update` instead of `update_attributes` (by @koic) * Split IP resolution from `update_tracked_fields` (by @mckramer) * upgrade dependencies for rails and responders (by @lancecarlson) * Add `autocomplete="new-password"` to new password fields (by @gssbzn) * Add `autocomplete="current-password"` to current password fields (by @gssbzn) * Remove redundant `self` from `database_authenticatable` module (by @abhishekkanojia) * Update `simple_form` templates with changes from https://github.com/plataformatec/devise/commit/16b3d6d67c7e017d461ea17ed29ea9738dc77e83 and https://github.com/plataformatec/devise/commit/6260c29a867b9a656f1e1557abe347a523178fab (by @gssbzn) * Remove `:trackable` from the default modules in the generators, to be more GDPR-friendly (by @fakenine) * bug fixes * Use same string on failed login regardless of whether account exists when in paranoid mode (by @TonyMK9068) * Fix error when params is not a hash inside `Devise::ParameterSanitizer` (by @b0nn1e) * Look for `secret_key_base` inside `Rails.application` (by @gencer) * Ensure `Devise::ParameterFilter` does not add missing keys when called with a hash that has a `default` / `default_proc` configured (by @joshpencheon) * Adds `is_navigational_format?` check to `after_sign_up_path_for` to keep consistency (by @iorme1) ### 4.4.3 - 2018-03-17 * bug fixes * Fix undefined method `rails5?` for Devise::Test:Module (by @tegon) * Fix: secret key was being required to be set inside credentials on Rails 5.2 (by @tegon) ### 4.4.2 - 2018-03-15 * enhancements * Support for :credentials on Rails v5.2.x. (by @gencer) * Improve documentation about the test suite. (by @tegon) * Test with Rails 5.2.rc1 on Travis. (by @jcoyne) * Allow test with Rails 6. (by @Fudoshiki) * Creating a new section for controller configuration on `devise.rb` template (by @Danilo-Araujo-Silva) * bug fixes * Preserve content_type for unauthenticated tests (by @gmcnaughton) * Check if the resource is persisted in `update_tracked_fields!` instead of performing validations (by @tegon) * Revert "Replace log_process_action to append_info_to_payload" (by @tegon) ### 4.4.1 - 2018-01-23 * bug fixes * Ensure Gemspec is loaded as utf-8. (by @segiddins) * Fix `ActiveRecord` check on `Confirmable`. (by @tegon) * Fix `signed_in?` docs without running auth hooks. by (@machty) ### 4.4.0 - 2017-12-29 * enhancements * Add `frozen_string_literal` pragma comment to all Ruby files. (by @pat) * Use `set_flash_method!` instead of `set_flash_method` in `Devise::OmniauthCallbacksController#failure`. (by @saichander17) * Clarify how `store_location_for` modifies URIs. (by @olivierlacan) * Move `failed_attempts` increment into its own function. by (@mobilutz) * Add `autocomplete="email"` to email fields. by (@MikeRogers0) * Add the ability to change the default migrations path introduced in Rails 5.0.3. (by @alexhifer) * Delete unnecessary condition for helper method. (by @davydovanton) * Support `id: :uuid` option for migrations. (by @filip373) * bug fixes * Fix syntax for MRI 2.5.0. (by @pat) * Validations were being ignored on singup in the `Trackable#update_tracked_fields!` method. (by @AshleyFoster) * Do not modify options for `#serializable_hash`. (by @guigs) * Email confirmations were being sent on sign in/sign out for application using `mongoid` and `mongoid-paperclip` gems. This is because previously we were checking if a model is from Active Record by checking if the method `after_commit` was defined - since `mongoid` doesn' have one - but `mongoid-paperclip` gem does define one, which cause this issue. (by @fjg) ### 4.3.0 - 2017-05-14 * Enhancements * Dependency support added for Rails 5.1.x. ### 4.2.1 - 2017-03-15 * removals * `Devise::Mailer#scope_name` and `Devise::Mailer#resource` are now protected methods instead of public. * bug fixes * Attempt to reset password without the password field in the request now results in a `:blank` validation error. Before this change, Devise would accept the reset password request and log the user in, without validating/changing the password. (by @victor-am) * Confirmation links now expire based on UTC time, working properly when using different timezones. (by @jjuliano) * enhancements * Notify the original email when it is changed with a new `Devise.send_email_changed_notification` setting. When using `reconfirmable`, the notification will be sent right away instead of when the unconfirmed email is confirmed. (original change by @ethirajsrinivasan) ### 4.2.0 - 2016-07-01 * removals * Remove the deprecated `Devise::ParameterSanitizer` API from Devise 3. Please use the `#permit` and `#sanitize` methods over `#for`. * Remove the deprecated OmniAuth URL helpers. Use the fully qualified helpers (`user_facebook_omniauth_authorize_path`) over the scope based helpers ( `user_omniauth_authorize_path(:facebook)`). * Remove the `Devise.bcrypt` method, use `Devise::Encryptor.digest` instead. * Remove the `Devise::Models::Confirmable#confirm!` method, use `confirm` instead. * Remove the `Devise::Models::Recoverable#reset_password!` method, use `reset_password` instead. * Remove the `Devise::Models::Recoverable#after_password_reset` method. * bug fixes * Fix an `ActionDispatch::IllegalStateError` when testing controllers with Rails 5 rc 2(by @hamadata). * Use `ActiveSupport.on_load` hooks to include Devise on `ActiveRecord` and `Mongoid`, avoiding autoloading these constants too soon (by @lucasmazza, @rafaelfranca). * enhancements * Display the minimum password length on `registrations/edit` view (by @Yanchek99). * You can disable Devise's routes reloading on boot by through the `reload_routes = false` config. This can reduce the time taken to boot the application but it might trigger some errors if you application (mostly your controllers) requires that Devise mappings be loaded during boot time (by @sidonath). * Added `Devise::Test::IntegrationHelpers` to bypass the sign in process using Warden test API (by @lucasmazza). * Define `inspect` in `Devise::Models::Authenticatable` to help ensure password hashes aren't included in exceptions or otherwise accidentally serialized (by @tkrajcar). * Add missing support of `Rails.application.config.action_controller.relative_url_root` (by @kosdiamantis). * deprecations * `Devise::TestHelpers` is deprecated in favor of `Devise::Test::ControllerHelpers` (by @lucasmazza). * The `sign_in` test helper has changed to use keyword arguments when passing a scope. `sign_in :admin, users(:alice)` should be rewritten as `sign_in users(:alice), scope: :admin` (by @lucasmazza). * The option `bypass` of `Devise::Controllers::SignInOut#sign_in` method is deprecated in favor of `Devise::Controllers::SignInOut#bypass_sign_in` method (by @ulissesalmeida). ### 4.1.1 - 2016-05-15 * bug fixes * Fix overwriting the remember_token when a valid one already exists (by @ralinchimev). ### 4.1.0 * bug fixes * Fix race condition of sending the confirmation instructions e-mail using background jobs. Using the previous `after_create` callback, the e-mail can be sent before the record be committed on database, generating a `ActiveRecord::NotFound` error. Now the confirmation e-mail will be only sent after the database commit, using the `after_commit` callback. It may break your test suite on Rails 4 if you are testing the sent e-mails or enqueued jobs using transactional fixtures enabled or `DatabaseCleaner` with `transaction` strategy. You can easily fix your test suite using the gem [test_after_commit](https://github.com/grosser/test_after_commit). For example, put in your Gemfile: ```ruby gem 'test_after_commit', :group => :test ``` On Rails 5 `after_commit` callbacks are triggered even using transactional fixtures, then this fix will not break your test suite. If you are using `DatabaseCleaner` with the `deletion` or `truncation` strategies it may not break your tests. (by @allenwq) * Fix strategy checking in `Lockable#unlock_strategy_enabled?` for `:none` and `:undefined` strategies. (by @f3ndot) * features * Humanize authentication keys in failure flash message (by @byzg) When you are configuring the translations of `devise.failure.invalid`, the `authentication_keys` is translated now. * deprecations * Remove code supporting old session serialization format (by @fphilipe). * Now the `email_regexp` default uses a more permissive regex: `/\A[^@\s]+@[^@\s]+\z/` (by @kimgb) * Now the `strip_whitespace_keys` default is `[:email]` (by @ulissesalmeida) * Now the `reconfirmable` default is `true` (by @ulissesalmeida) * Now the `skip_session_storage` default is `[:http_auth]` (by @ulissesalmeida) * Now the `sign_out_via` default is `:delete` (by @ulissesalmeida) * improvements * Avoids extra computation of friendly token for confirmation token (by @sbc100) ### 4.0.3 - 2016-05-15 * bug fixes * Fix overwriting the remember_token when a valid one already exists (by @ralinchimev). ### 4.0.2 - 2016-05-02 * bug fixes * Fix strategy checking in `Lockable#unlock_strategy_enabled?` for `:none` and `:undefined` strategies. (by @f3ndot) ### 4.0.1 - 2016-04-25 * bug fixes * Fix the e-mail confirmation instructions send when a user updates the email address from nil. (by @lmduc) * Remove unnecessary `attribute_will_change!` call. (by @cadejscroggins) * Consistent `permit!` check. (by @ulissesalmeida) ### 4.0.0 - 2016-04-18 * bug fixes * Fix the `extend_remember_period` configuration. When set to `false` it does not update the cookie expiration anymore.(by @ulissesalmeida) * deprecations * Added a warning of default value change in Devise 4.1 for users that uses the the default configuration of the following configurations: (by @ulissesalmeida) * `strip_whitespace_keys` - The default will be `[:email]`. * `skip_session_storage` - The default will be `[:http_auth]`. * `sign_out_via` - The default will be `:delete`. * `reconfirmable` - The default will be `true`. * `email_regexp` - The default will be `/\A[^@\s]+@[^@\s]+\z/`. * Removed deprecated argument of `Devise::Models::Rememberable#remember_me!` (by @ulissesalmeida) * Removed deprecated private method Devise::Controllers::Helpers#expire_session_data_after_sign_in! (by @bogdanvlviv) ### 4.0.0.rc2 - 2016-03-09 * enhancements * Introduced `DeviseController#set_flash_message!` for conditional flash messages setting to reduce complexity. * `rails g devise:install` will fail if the app does not have a ORM configured (by @arjunsharma) * Support to Rails 5 versioned migrations added. * deprecations * omniauth routes are no longer defined with a wildcard `:provider` parameter, and provider specific routes are defined instead, so route helpers like `user_omniauth_authorize_path(:github)` are deprecated in favor of `user_github_omniauth_authorize_path`. You can still use `omniauth_authorize_path(:user, :github)` if you need to call the helpers dynamically. ### 4.0.0.rc1 - 2016-02-01 * Support added to Rails 5 (by @twalpole). * Devise no longer supports Rails 3.2 and 4.0. * Devise no longer supports Ruby 1.9 and 2.0. * deprecations * The `devise_parameter_sanitize` API has changed: The `for` method was deprecated in favor of `permit`: ```ruby def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) << :subscribe_newsletter # Should become the following. devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter]) end ``` The customization through instance methods on the sanitizer implementation should be done through it's `initialize` method: ```ruby class User::ParameterSanitizer < Devise::ParameterSanitizer def sign_up default_params.permit(:username, :email) end end # The `sign_up` method can be a `permit` call on the sanitizer `initialize`. class User::ParameterSanitizer < Devise::ParameterSanitizer def initialize(*) super permit(:sign_up, keys: [:username, :email]) end end ``` You can check more examples and explanations on the [README section](README.md#strong-parameters) and on the [ParameterSanitizer docs](lib/devise/parameter_sanitizer.rb). Please check [3-stable](https://github.com/plataformatec/devise/blob/3-stable/CHANGELOG.md) for previous changes. devise-4.7.1/devise.gemspec0000644000004100000410000001671613541606342015675 0ustar www-datawww-data######################################################### # This file has been automatically generated by gem2tgz # ######################################################### # -*- encoding: utf-8 -*- # stub: devise 4.7.1 ruby lib Gem::Specification.new do |s| s.name = "devise".freeze s.version = "4.7.1" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Jos\u{e9} Valim".freeze, "Carlos Ant\u{f4}nio".freeze] s.date = "2019-09-06" s.description = "Flexible authentication solution for Rails with Warden".freeze s.email = "contact@plataformatec.com.br".freeze s.files = ["CHANGELOG.md".freeze, "MIT-LICENSE".freeze, "README.md".freeze, "app/controllers/devise/confirmations_controller.rb".freeze, "app/controllers/devise/omniauth_callbacks_controller.rb".freeze, "app/controllers/devise/passwords_controller.rb".freeze, "app/controllers/devise/registrations_controller.rb".freeze, "app/controllers/devise/sessions_controller.rb".freeze, "app/controllers/devise/unlocks_controller.rb".freeze, "app/controllers/devise_controller.rb".freeze, "app/helpers/devise_helper.rb".freeze, "app/mailers/devise/mailer.rb".freeze, "app/views/devise/confirmations/new.html.erb".freeze, "app/views/devise/mailer/confirmation_instructions.html.erb".freeze, "app/views/devise/mailer/email_changed.html.erb".freeze, "app/views/devise/mailer/password_change.html.erb".freeze, "app/views/devise/mailer/reset_password_instructions.html.erb".freeze, "app/views/devise/mailer/unlock_instructions.html.erb".freeze, "app/views/devise/passwords/edit.html.erb".freeze, "app/views/devise/passwords/new.html.erb".freeze, "app/views/devise/registrations/edit.html.erb".freeze, "app/views/devise/registrations/new.html.erb".freeze, "app/views/devise/sessions/new.html.erb".freeze, "app/views/devise/shared/_error_messages.html.erb".freeze, "app/views/devise/shared/_links.html.erb".freeze, "app/views/devise/unlocks/new.html.erb".freeze, "config/locales/en.yml".freeze, "lib/devise.rb".freeze, "lib/devise/controllers/helpers.rb".freeze, "lib/devise/controllers/rememberable.rb".freeze, "lib/devise/controllers/scoped_views.rb".freeze, "lib/devise/controllers/sign_in_out.rb".freeze, "lib/devise/controllers/store_location.rb".freeze, "lib/devise/controllers/url_helpers.rb".freeze, "lib/devise/delegator.rb".freeze, "lib/devise/encryptor.rb".freeze, "lib/devise/failure_app.rb".freeze, "lib/devise/hooks/activatable.rb".freeze, "lib/devise/hooks/csrf_cleaner.rb".freeze, "lib/devise/hooks/forgetable.rb".freeze, "lib/devise/hooks/lockable.rb".freeze, "lib/devise/hooks/proxy.rb".freeze, "lib/devise/hooks/rememberable.rb".freeze, "lib/devise/hooks/timeoutable.rb".freeze, "lib/devise/hooks/trackable.rb".freeze, "lib/devise/mailers/helpers.rb".freeze, "lib/devise/mapping.rb".freeze, "lib/devise/models.rb".freeze, "lib/devise/models/authenticatable.rb".freeze, "lib/devise/models/confirmable.rb".freeze, "lib/devise/models/database_authenticatable.rb".freeze, "lib/devise/models/lockable.rb".freeze, "lib/devise/models/omniauthable.rb".freeze, "lib/devise/models/recoverable.rb".freeze, "lib/devise/models/registerable.rb".freeze, "lib/devise/models/rememberable.rb".freeze, "lib/devise/models/timeoutable.rb".freeze, "lib/devise/models/trackable.rb".freeze, "lib/devise/models/validatable.rb".freeze, "lib/devise/modules.rb".freeze, "lib/devise/omniauth.rb".freeze, "lib/devise/omniauth/config.rb".freeze, "lib/devise/omniauth/url_helpers.rb".freeze, "lib/devise/orm/active_record.rb".freeze, "lib/devise/orm/mongoid.rb".freeze, "lib/devise/parameter_filter.rb".freeze, "lib/devise/parameter_sanitizer.rb".freeze, "lib/devise/rails.rb".freeze, "lib/devise/rails/routes.rb".freeze, "lib/devise/rails/warden_compat.rb".freeze, "lib/devise/secret_key_finder.rb".freeze, "lib/devise/strategies/authenticatable.rb".freeze, "lib/devise/strategies/base.rb".freeze, "lib/devise/strategies/database_authenticatable.rb".freeze, "lib/devise/strategies/rememberable.rb".freeze, "lib/devise/test/controller_helpers.rb".freeze, "lib/devise/test/integration_helpers.rb".freeze, "lib/devise/test_helpers.rb".freeze, "lib/devise/time_inflector.rb".freeze, "lib/devise/token_generator.rb".freeze, "lib/devise/version.rb".freeze, "lib/generators/active_record/devise_generator.rb".freeze, "lib/generators/active_record/templates/migration.rb".freeze, "lib/generators/active_record/templates/migration_existing.rb".freeze, "lib/generators/devise/controllers_generator.rb".freeze, "lib/generators/devise/devise_generator.rb".freeze, "lib/generators/devise/install_generator.rb".freeze, "lib/generators/devise/orm_helpers.rb".freeze, "lib/generators/devise/views_generator.rb".freeze, "lib/generators/mongoid/devise_generator.rb".freeze, "lib/generators/templates/README".freeze, "lib/generators/templates/controllers/README".freeze, "lib/generators/templates/controllers/confirmations_controller.rb".freeze, "lib/generators/templates/controllers/omniauth_callbacks_controller.rb".freeze, "lib/generators/templates/controllers/passwords_controller.rb".freeze, "lib/generators/templates/controllers/registrations_controller.rb".freeze, "lib/generators/templates/controllers/sessions_controller.rb".freeze, "lib/generators/templates/controllers/unlocks_controller.rb".freeze, "lib/generators/templates/devise.rb".freeze, "lib/generators/templates/markerb/confirmation_instructions.markerb".freeze, "lib/generators/templates/markerb/email_changed.markerb".freeze, "lib/generators/templates/markerb/password_change.markerb".freeze, "lib/generators/templates/markerb/reset_password_instructions.markerb".freeze, "lib/generators/templates/markerb/unlock_instructions.markerb".freeze, "lib/generators/templates/simple_form_for/confirmations/new.html.erb".freeze, "lib/generators/templates/simple_form_for/passwords/edit.html.erb".freeze, "lib/generators/templates/simple_form_for/passwords/new.html.erb".freeze, "lib/generators/templates/simple_form_for/registrations/edit.html.erb".freeze, "lib/generators/templates/simple_form_for/registrations/new.html.erb".freeze, "lib/generators/templates/simple_form_for/sessions/new.html.erb".freeze, "lib/generators/templates/simple_form_for/unlocks/new.html.erb".freeze] s.homepage = "https://github.com/plataformatec/devise".freeze s.licenses = ["MIT".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.1.0".freeze) s.rubygems_version = "2.5.2.1".freeze s.summary = "Flexible authentication solution for Rails with Warden".freeze if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q.freeze, ["~> 3.0"]) s.add_runtime_dependency(%q.freeze, ["~> 0.1"]) s.add_runtime_dependency(%q.freeze, [">= 4.1.0"]) s.add_runtime_dependency(%q.freeze, [">= 0"]) s.add_runtime_dependency(%q.freeze, ["~> 1.2.3"]) else s.add_dependency(%q.freeze, ["~> 3.0"]) s.add_dependency(%q.freeze, ["~> 0.1"]) s.add_dependency(%q.freeze, [">= 4.1.0"]) s.add_dependency(%q.freeze, [">= 0"]) s.add_dependency(%q.freeze, ["~> 1.2.3"]) end else s.add_dependency(%q.freeze, ["~> 3.0"]) s.add_dependency(%q.freeze, ["~> 0.1"]) s.add_dependency(%q.freeze, [">= 4.1.0"]) s.add_dependency(%q.freeze, [">= 0"]) s.add_dependency(%q.freeze, ["~> 1.2.3"]) end end devise-4.7.1/app/0000755000004100000410000000000013541606342013616 5ustar www-datawww-datadevise-4.7.1/app/helpers/0000755000004100000410000000000013541606342015260 5ustar www-datawww-datadevise-4.7.1/app/helpers/devise_helper.rb0000644000004100000410000000122513541606342020423 0ustar www-datawww-data# frozen_string_literal: true module DeviseHelper # Retain this method for backwards compatibility, deprecated in favour of modifying the # devise/shared/error_messages partial def devise_error_messages! ActiveSupport::Deprecation.warn <<-DEPRECATION.strip_heredoc [Devise] `DeviseHelper.devise_error_messages!` is deprecated and it will be removed in the next major version. To customize the errors styles please run `rails g devise:views` and modify the `devise/shared/error_messages` partial. DEPRECATION return "" if resource.errors.empty? render "devise/shared/error_messages", resource: resource end end devise-4.7.1/app/controllers/0000755000004100000410000000000013541606342016164 5ustar www-datawww-datadevise-4.7.1/app/controllers/devise_controller.rb0000644000004100000410000001424613541606342022242 0ustar www-datawww-data# frozen_string_literal: true # All Devise controllers are inherited from here. class DeviseController < Devise.parent_controller.constantize include Devise::Controllers::ScopedViews if respond_to?(:helper) helper DeviseHelper end if respond_to?(:helper_method) helpers = %w(resource scope_name resource_name signed_in_resource resource_class resource_params devise_mapping) helper_method(*helpers) end prepend_before_action :assert_is_devise_resource! respond_to :html if mimes_for_respond_to.empty? # 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. # # This method should be public as it is in ActionPack # itself. Changing its visibility may break other gems. def _prefixes #:nodoc: @_prefixes ||= if self.class.scoped_views? && request && devise_mapping ["#{devise_mapping.scoped_path}/#{controller_name}"] + super else super end end protected # 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 # 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_actions where no authentication is required. # # Example: # before_action :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 true end end # Sets the flash message with :key, using I18n. By default you are able # to set up your messages using specific resource scope, and if no message is # found we look to the default scope. Set the "now" options key to a true # value to populate the flash.now hash in lieu of the default flash hash (so # the flash message will be available to the current action instead of the # next action). # 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) if options[:now] flash.now[key] = message if message.present? else flash[key] = message if message.present? end end # Sets flash message if is_flashing_format? equals true def set_flash_message!(key, kind, options = {}) if is_flashing_format? set_flash_message(key, kind, options) end end # Sets minimum password length to show to user def set_minimum_password_length if devise_mapping.validatable? @minimum_password_length = resource_class.password_length.min end end def devise_i18n_options(options) options end # Get message for given def find_message(kind, options = {}) options[:scope] ||= translation_scope 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 # Controllers inheriting DeviseController are advised to override this # method so that other controllers inheriting from them would use # existing translations. def translation_scope "devise.#{controller_name}" 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 ActiveSupport.run_load_hooks(:devise_controller, self) end devise-4.7.1/app/controllers/devise/0000755000004100000410000000000013541606342017443 5ustar www-datawww-datadevise-4.7.1/app/controllers/devise/sessions_controller.rb0000644000004100000410000000461413541606342024106 0ustar www-datawww-data# frozen_string_literal: true class Devise::SessionsController < DeviseController prepend_before_action :require_no_authentication, only: [:new, :create] prepend_before_action :allow_params_authentication!, only: :create prepend_before_action :verify_signed_out_user, only: :destroy prepend_before_action(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) yield resource if block_given? 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) 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 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 def translation_scope 'devise.sessions' 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 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 devise-4.7.1/app/controllers/devise/confirmations_controller.rb0000644000004100000410000000303213541606342025104 0ustar www-datawww-data# frozen_string_literal: true 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) 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 def translation_scope 'devise.confirmations' end end devise-4.7.1/app/controllers/devise/omniauth_callbacks_controller.rb0000644000004100000410000000232313541606342026056 0ustar www-datawww-data# frozen_string_literal: true class Devise::OmniauthCallbacksController < DeviseController prepend_before_action { request.env["devise.skip_timeout"] = true } def passthru render status: 404, plain: "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 request.respond_to?(:get_header) ? request.get_header("omniauth.error.strategy") : request.env["omniauth.error.strategy"] end def failure_message exception = request.respond_to?(:get_header) ? request.get_header("omniauth.error") : request.env["omniauth.error"] error = exception.error_reason if exception.respond_to?(:error_reason) error ||= exception.error if exception.respond_to?(:error) error ||= (request.respond_to?(:get_header) ? request.get_header("omniauth.error.type") : request.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 def translation_scope 'devise.omniauth_callbacks' end end devise-4.7.1/app/controllers/devise/passwords_controller.rb0000644000004100000410000000524113541606342024262 0ustar www-datawww-data# frozen_string_literal: true class Devise::PasswordsController < DeviseController prepend_before_action :require_no_authentication # Render the #edit only if coming from a reset password email link append_before_action :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 set_minimum_password_length 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) if Devise.sign_in_after_reset_password flash_message = resource.active_for_authentication? ? :updated : :updated_not_active set_flash_message!(:notice, flash_message) resource.after_database_authentication sign_in(resource_name, resource) else set_flash_message!(:notice, :updated_not_active) end respond_with resource, location: after_resetting_password_path_for(resource) else set_minimum_password_length respond_with resource end end protected def after_resetting_password_path_for(resource) Devise.sign_in_after_reset_password ? after_sign_in_path_for(resource) : new_session_path(resource_name) 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 def translation_scope 'devise.passwords' end end devise-4.7.1/app/controllers/devise/registrations_controller.rb0000644000004100000410000001254613541606342025140 0ustar www-datawww-data# frozen_string_literal: true class Devise::RegistrationsController < DeviseController prepend_before_action :require_no_authentication, only: [:new, :create, :cancel] prepend_before_action :authenticate_scope!, only: [:edit, :update, :destroy] prepend_before_action :set_minimum_password_length, only: [:new, :edit] # GET /resource/sign_up def new build_resource yield resource if block_given? respond_with resource end # POST /resource def create build_resource(sign_up_params) resource.save yield resource if block_given? if resource.persisted? if resource.active_for_authentication? set_flash_message! :notice, :signed_up 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}" expire_data_after_sign_in! respond_with resource, location: after_inactive_sign_up_path_for(resource) end else clean_up_passwords resource set_minimum_password_length 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 set_flash_message_for_update(resource, prev_unconfirmed_email) bypass_sign_in resource, scope: resource_name if sign_in_after_change_password? respond_with resource, location: after_update_path_for(resource) else clean_up_passwords resource set_minimum_password_length 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 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 = {}) 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) if is_navigational_format? 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) sign_in_after_change_password? ? signed_in_root_path(resource) : new_session_path(resource_name) 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 def translation_scope 'devise.registrations' end private def set_flash_message_for_update(resource, prev_unconfirmed_email) return unless is_flashing_format? flash_key = if update_needs_confirmation?(resource, prev_unconfirmed_email) :update_needs_confirmation elsif sign_in_after_change_password? :updated else :updated_but_not_signed_in end set_flash_message :notice, flash_key end def sign_in_after_change_password? return true if account_update_params[:password].blank? Devise.sign_in_after_change_password end end devise-4.7.1/app/controllers/devise/unlocks_controller.rb0000644000004100000410000000262413541606342023715 0ustar www-datawww-data# frozen_string_literal: true class Devise::UnlocksController < DeviseController prepend_before_action :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 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 def translation_scope 'devise.unlocks' end end devise-4.7.1/app/views/0000755000004100000410000000000013541606342014753 5ustar www-datawww-datadevise-4.7.1/app/views/devise/0000755000004100000410000000000013541606342016232 5ustar www-datawww-datadevise-4.7.1/app/views/devise/registrations/0000755000004100000410000000000013541606342021127 5ustar www-datawww-datadevise-4.7.1/app/views/devise/registrations/new.html.erb0000644000004100000410000000150513541606342023356 0ustar www-datawww-data

Sign up

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> <%= render "devise/shared/error_messages", resource: resource %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
<%= f.label :password %> <% if @minimum_password_length %> (<%= @minimum_password_length %> characters minimum) <% end %>
<%= f.password_field :password, autocomplete: "new-password" %>
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, autocomplete: "new-password" %>
<%= f.submit "Sign up" %>
<% end %> <%= render "devise/shared/links" %> devise-4.7.1/app/views/devise/registrations/edit.html.erb0000644000004100000410000000274613541606342023522 0ustar www-datawww-data

Edit <%= resource_name.to_s.humanize %>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> <%= render "devise/shared/error_messages", resource: resource %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
Currently waiting confirmation for: <%= resource.unconfirmed_email %>
<% end %>
<%= f.label :password %> (leave blank if you don't want to change it)
<%= f.password_field :password, autocomplete: "new-password" %> <% if @minimum_password_length %>
<%= @minimum_password_length %> characters minimum <% end %>
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, autocomplete: "new-password" %>
<%= f.label :current_password %> (we need your current password to confirm your changes)
<%= f.password_field :current_password, autocomplete: "current-password" %>
<%= f.submit "Update" %>
<% end %>

Cancel my account

Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %>

<%= link_to "Back", :back %> devise-4.7.1/app/views/devise/unlocks/0000755000004100000410000000000013541606342017710 5ustar www-datawww-datadevise-4.7.1/app/views/devise/unlocks/new.html.erb0000644000004100000410000000074013541606342022137 0ustar www-datawww-data

Resend unlock instructions

<%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> <%= render "devise/shared/error_messages", resource: resource %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
<%= f.submit "Resend unlock instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-4.7.1/app/views/devise/shared/0000755000004100000410000000000013541606342017500 5ustar www-datawww-datadevise-4.7.1/app/views/devise/shared/_error_messages.html.erb0000644000004100000410000000061613541606342024317 0ustar www-datawww-data<% if resource.errors.any? %>

<%= I18n.t("errors.messages.not_saved", count: resource.errors.count, resource: resource.class.model_name.human.downcase) %>

    <% resource.errors.full_messages.each do |message| %>
  • <%= message %>
  • <% end %>
<% end %> devise-4.7.1/app/views/devise/shared/_links.html.erb0000644000004100000410000000216613541606342022421 0ustar www-datawww-data<%- if controller_name != 'sessions' %> <%= link_to "Log in", new_session_path(resource_name) %>
<% end %> <%- if devise_mapping.registerable? && controller_name != 'registrations' %> <%= link_to "Sign up", new_registration_path(resource_name) %>
<% end %> <%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> <%= link_to "Forgot your password?", new_password_path(resource_name) %>
<% end %> <%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
<% 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) %>
<% end %> <%- if devise_mapping.omniauthable? %> <%- resource_class.omniauth_providers.each do |provider| %> <%= link_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider) %>
<% end %> <% end %> devise-4.7.1/app/views/devise/mailer/0000755000004100000410000000000013541606342017503 5ustar www-datawww-datadevise-4.7.1/app/views/devise/mailer/email_changed.html.erb0000644000004100000410000000047213541606342023703 0ustar www-datawww-data

Hello <%= @email %>!

<% if @resource.try(:unconfirmed_email?) %>

We're contacting you to notify you that your email is being changed to <%= @resource.unconfirmed_email %>.

<% else %>

We're contacting you to notify you that your email has been changed to <%= @resource.email %>.

<% end %> devise-4.7.1/app/views/devise/mailer/reset_password_instructions.html.erb0000644000004100000410000000061113541606342027026 0ustar www-datawww-data

Hello <%= @resource.email %>!

Someone has requested a link to change your password. 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.

devise-4.7.1/app/views/devise/mailer/confirmation_instructions.html.erb0000644000004100000410000000030613541606342026453 0ustar www-datawww-data

Welcome <%= @email %>!

You can confirm your account email through the link below:

<%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %>

devise-4.7.1/app/views/devise/mailer/unlock_instructions.html.erb0000644000004100000410000000042413541606342025257 0ustar www-datawww-data

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) %>

devise-4.7.1/app/views/devise/mailer/password_change.html.erb0000644000004100000410000000016513541606342024311 0ustar www-datawww-data

Hello <%= @resource.email %>!

We're contacting you to notify you that your password has been changed.

devise-4.7.1/app/views/devise/passwords/0000755000004100000410000000000013541606342020257 5ustar www-datawww-datadevise-4.7.1/app/views/devise/passwords/new.html.erb0000644000004100000410000000074613541606342022514 0ustar www-datawww-data

Forgot your password?

<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> <%= render "devise/shared/error_messages", resource: resource %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
<%= f.submit "Send me reset password instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-4.7.1/app/views/devise/passwords/edit.html.erb0000644000004100000410000000153013541606342022640 0ustar www-datawww-data

Change your password

<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> <%= render "devise/shared/error_messages", resource: resource %> <%= f.hidden_field :reset_password_token %>
<%= f.label :password, "New password" %>
<% if @minimum_password_length %> (<%= @minimum_password_length %> characters minimum)
<% end %> <%= f.password_field :password, autofocus: true, autocomplete: "new-password" %>
<%= f.label :password_confirmation, "Confirm new password" %>
<%= f.password_field :password_confirmation, autocomplete: "new-password" %>
<%= f.submit "Change my password" %>
<% end %> <%= render "devise/shared/links" %> devise-4.7.1/app/views/devise/confirmations/0000755000004100000410000000000013541606342021105 5ustar www-datawww-datadevise-4.7.1/app/views/devise/confirmations/new.html.erb0000644000004100000410000000111313541606342023327 0ustar www-datawww-data

Resend confirmation instructions

<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> <%= render "devise/shared/error_messages", resource: resource %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true, autocomplete: "email", value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email) %>
<%= f.submit "Resend confirmation instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-4.7.1/app/views/devise/sessions/0000755000004100000410000000000013541606342020100 5ustar www-datawww-datadevise-4.7.1/app/views/devise/sessions/new.html.erb0000644000004100000410000000120713541606342022326 0ustar www-datawww-data

Log in

<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
<%= f.label :password %>
<%= f.password_field :password, autocomplete: "current-password" %>
<% if devise_mapping.rememberable? %>
<%= f.check_box :remember_me %> <%= f.label :remember_me %>
<% end %>
<%= f.submit "Log in" %>
<% end %> <%= render "devise/shared/links" %> devise-4.7.1/app/mailers/0000755000004100000410000000000013541606342015252 5ustar www-datawww-datadevise-4.7.1/app/mailers/devise/0000755000004100000410000000000013541606342016531 5ustar www-datawww-datadevise-4.7.1/app/mailers/devise/mailer.rb0000644000004100000410000000143213541606342020327 0ustar www-datawww-data# frozen_string_literal: true 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 def email_changed(record, opts={}) devise_mail(record, :email_changed, opts) end def password_change(record, opts={}) devise_mail(record, :password_change, opts) end end end devise-4.7.1/lib/0000755000004100000410000000000013541606342013604 5ustar www-datawww-datadevise-4.7.1/lib/devise.rb0000644000004100000410000004072213541606342015415 0ustar www-datawww-data# frozen_string_literal: true 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 :Encryptor, 'devise/encryptor' autoload :FailureApp, 'devise/failure_app' autoload :OmniAuth, 'devise/omniauth' autoload :ParameterFilter, 'devise/parameter_filter' autoload :ParameterSanitizer, 'devise/parameter_sanitizer' autoload :TestHelpers, 'devise/test_helpers' autoload :TimeInflector, 'devise/time_inflector' autoload :TokenGenerator, 'devise/token_generator' autoload :SecretKeyFinder, 'devise/secret_key_finder' 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 module Test autoload :ControllerHelpers, 'devise/test/controller_helpers' autoload :IntegrationHelpers, 'devise/test/integration_helpers' 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 = {} ROUTES = {} STRATEGIES = {} URL_HELPERS = {} # 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 # Custom domain or key for cookies. Not set by default mattr_accessor :rememberable_options @@rememberable_options = {} # The number of times to hash the password. mattr_accessor :stretches @@stretches = 11 # 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 = [:email] # 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 asserts that there are no # @ symbols or whitespaces in either the localpart or the domain, and that # there is a single @ symbol separating the localpart and the domain. mattr_accessor :email_regexp @@email_regexp = /\A[^@\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. mattr_accessor :reconfirmable @@reconfirmable = true # Time interval to timeout the user session without activity. mattr_accessor :timeout_in @@timeout_in = 30.minutes # Used to hash the password. Please generate one with rails secret. mattr_accessor :pepper @@pepper = nil # Used to send notification to the original user email when their email is changed. mattr_accessor :send_email_changed_notification @@send_email_changed_notification = false # Used to enable sending notification to user when their password is changed. mattr_accessor :send_password_change_notification @@send_password_change_notification = false # 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 # When set to false, resetting a password does not automatically sign in a user mattr_accessor :sign_in_after_reset_password @@sign_in_after_reset_password = true # 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 = [:http_auth] # 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 = :delete # 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 # When false, Devise will not attempt to reload routes on eager load. # This can reduce the time taken to boot the app but if your application # requires the Devise mappings to be loaded during boot time the application # won't boot properly. mattr_accessor :reload_routes @@reload_routes = true # PRIVATE CONFIGURATION # Store scopes mappings. mattr_reader :mappings @@mappings = {} # OmniAuth configurations. mattr_reader :omniauth_configs @@omniauth_configs = {} # 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 # When set to false, changing a password does not automatically sign in a user mattr_accessor :sign_in_after_change_password @@sign_in_after_change_password = true def self.rails51? # :nodoc: Rails.gem_version >= Gem::Version.new("5.1.x") end def self.activerecord51? # :nodoc: defined?(ActiveRecord) && ActiveRecord.gem_version >= Gem::Version.new("5.1.x") end # Default way to set up 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) ActiveSupport::Dependencies.reference(arg) Getter.new(arg) 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 # Register available devise modules. For the standard modules that Devise provides, this method is # called from lib/devise/modules.rb. Third-party modules need to be added explicitly using this method. # # Note that adding a module using this method does not cause it to be used in the authentication # process. That requires that the module be listed in the arguments passed to the 'devise' method # in the model class definition. # # == 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*. # +insert_at+ - Integer representing the order in which this module's model will be included # # 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') # Devise.add_module(:party_module, insert_at: 0) # def self.add_module(module_name, options = {}) options.assert_valid_keys(:strategy, :model, :controller, :route, :no_input, :insert_at) ALL.insert (options[:insert_at] || -1), module_name 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) 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 complete the setup of warden manager after routes are loaded. # See lib/devise/rails/routes.rb - ActionDispatch::Routing::RouteSet#finalize_with_devise! 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 |args| 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. # By default, length is 20 characters. def self.friendly_token(length = 20) # To calculate real characters, we must perform this operation. # See SecureRandom.urlsafe_base64 rlength = (length * 3) / 4 SecureRandom.urlsafe_base64(rlength).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' devise-4.7.1/lib/generators/0000755000004100000410000000000013541606342015755 5ustar www-datawww-datadevise-4.7.1/lib/generators/templates/0000755000004100000410000000000013541606342017753 5ustar www-datawww-datadevise-4.7.1/lib/generators/templates/devise.rb0000644000004100000410000003366613541606342021575 0ustar www-datawww-data# frozen_string_literal: true # 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. # Devise will use the `secret_key_base` as its `secret_key` # by default. You can change it below and use your own secret key. # config.secret_key = '<%= SecureRandom.hex(64) %>' # ==> Controller configuration # Configure the parent class to the devise controllers. # config.parent_controller = 'DeviseController' # ==> 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@example.com' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # Configure the parent class responsible to send e-mails. # config.parent_mailer = 'ActionMailer::Base' # ==> 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 # When false, Devise will not attempt to reload routes on eager load. # This can reduce the time taken to boot the app but if your application # requires the Devise mappings to be loaded during boot time the application # won't boot properly. # config.reload_routes = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 11. If # using other algorithms, it sets how many times you want the password to be hashed. # # 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 # algorithm), 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 : 11 # Set up a pepper to generate the hashed password. # config.pepper = '<%= SecureRandom.hex(64) %>' # Send a notification to the original email when the user's email is changed. # config.send_email_changed_notification = false # Send a notification email when the user's password is changed. # config.send_password_change_notification = false # ==> 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. # You can also set it to nil, which will allow the user to access the website # without confirming their account. # 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 = 6..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[^@\s]+@[^@\s]+\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 # ==> 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 # When set to false, does not sign a user in automatically after their password is # reset. Defaults to true, so a user is signed in automatically after a reset. # config.sign_in_after_reset_password = true # ==> Configuration for :encryptable # Allow you to use another hashing or encryption algorithm besides bcrypt (default). # You can use :sha1, :sha512 or algorithms 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' # ==> Turbolinks configuration # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly: # # ActiveSupport.on_load(:devise_failure_app) do # include Turbolinks::Controller # end # ==> Configuration for :registerable # When set to false, does not sign a user in automatically after their password is # changed. Defaults to true, so a user is signed in automatically after changing a password. # config.sign_in_after_change_password = true end devise-4.7.1/lib/generators/templates/controllers/0000755000004100000410000000000013541606342022321 5ustar www-datawww-datadevise-4.7.1/lib/generators/templates/controllers/sessions_controller.rb0000644000004100000410000000105413541606342026757 0ustar www-datawww-data# frozen_string_literal: true class <%= @scope_prefix %>SessionsController < Devise::SessionsController # before_action :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 # If you have extra params to permit, append them to the sanitizer. # def configure_sign_in_params # devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute]) # end end devise-4.7.1/lib/generators/templates/controllers/confirmations_controller.rb0000644000004100000410000000124413541606342027765 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/generators/templates/controllers/omniauth_callbacks_controller.rb0000644000004100000410000000125313541606342030735 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/generators/templates/controllers/passwords_controller.rb0000644000004100000410000000122713541606342027140 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/generators/templates/controllers/registrations_controller.rb0000644000004100000410000000265213541606342030013 0ustar www-datawww-data# frozen_string_literal: true class <%= @scope_prefix %>RegistrationsController < Devise::RegistrationsController # before_action :configure_sign_up_params, only: [:create] # before_action :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 # If you have extra params to permit, append them to the sanitizer. # def configure_sign_up_params # devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute]) # end # If you have extra params to permit, append them to the sanitizer. # def configure_account_update_params # devise_parameter_sanitizer.permit(:account_update, keys: [: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 devise-4.7.1/lib/generators/templates/controllers/README0000644000004100000410000000067013541606342023204 0ustar www-datawww-data=============================================================================== Some setup you must do manually if you haven't yet: Ensure you have overridden routes for generated controllers in your routes.rb. For example: Rails.application.routes.draw do devise_for :users, controllers: { sessions: 'users/sessions' } end =============================================================================== devise-4.7.1/lib/generators/templates/controllers/unlocks_controller.rb0000644000004100000410000000112313541606342026564 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/generators/templates/markerb/0000755000004100000410000000000013541606342021376 5ustar www-datawww-datadevise-4.7.1/lib/generators/templates/markerb/confirmation_instructions.markerb0000644000004100000410000000024313541606342030256 0ustar www-datawww-dataWelcome <%= @email %>! You can confirm your account through the link below: [Confirm my account](<%= confirmation_url(@resource, confirmation_token: @token) %>) devise-4.7.1/lib/generators/templates/markerb/reset_password_instructions.markerb0000644000004100000410000000054213541606342030634 0ustar www-datawww-dataHello <%= @resource.email %>! Someone has requested a link to change your password, and you can do this through the link below. [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. devise-4.7.1/lib/generators/templates/markerb/password_change.markerb0000644000004100000410000000014713541606342026114 0ustar www-datawww-dataHello <%= @resource.email %>! We're contacting you to notify you that your password has been changed. devise-4.7.1/lib/generators/templates/markerb/email_changed.markerb0000644000004100000410000000044113541606342025502 0ustar www-datawww-dataHello <%= @email %>! <% if @resource.try(:unconfirmed_email?) %> We're contacting you to notify you that your email is being changed to <%= @resource.unconfirmed_email %>. <% else %> We're contacting you to notify you that your email has been changed to <%= @resource.email %>. <% end %> devise-4.7.1/lib/generators/templates/markerb/unlock_instructions.markerb0000644000004100000410000000036013541606342027061 0ustar www-datawww-dataHello <%= @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: [Unlock my account](<%= unlock_url(@resource, unlock_token: @token) %>) devise-4.7.1/lib/generators/templates/README0000644000004100000410000000175713541606342020645 0ustar www-datawww-data=============================================================================== 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:

<%= notice %>

<%= alert %>

4. You can copy Devise views (for customization) to your app by running: rails g devise:views =============================================================================== devise-4.7.1/lib/generators/templates/simple_form_for/0000755000004100000410000000000013541606342023135 5ustar www-datawww-datadevise-4.7.1/lib/generators/templates/simple_form_for/registrations/0000755000004100000410000000000013541606342026032 5ustar www-datawww-datadevise-4.7.1/lib/generators/templates/simple_form_for/registrations/new.html.erb0000644000004100000410000000145713541606342030267 0ustar www-datawww-data

Sign up

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> <%= f.error_notification %>
<%= f.input :email, required: true, autofocus: true, input_html: { autocomplete: "email" }%> <%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length), input_html: { autocomplete: "new-password" } %> <%= f.input :password_confirmation, required: true, input_html: { autocomplete: "new-password" } %>
<%= f.button :submit, "Sign up" %>
<% end %> <%= render "devise/shared/links" %> devise-4.7.1/lib/generators/templates/simple_form_for/registrations/edit.html.erb0000644000004100000410000000243113541606342030414 0ustar www-datawww-data

Edit <%= resource_name.to_s.humanize %>

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> <%= f.error_notification %>
<%= f.input :email, required: true, autofocus: true %> <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>

Currently waiting confirmation for: <%= resource.unconfirmed_email %>

<% end %> <%= f.input :password, hint: "leave it blank if you don't want to change it", required: false, input_html: { autocomplete: "new-password" } %> <%= f.input :password_confirmation, required: false, input_html: { autocomplete: "new-password" } %> <%= f.input :current_password, hint: "we need your current password to confirm your changes", required: true, input_html: { autocomplete: "current-password" } %>
<%= f.button :submit, "Update" %>
<% end %>

Cancel my account

Unhappy? <%= link_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %>

<%= link_to "Back", :back %> devise-4.7.1/lib/generators/templates/simple_form_for/unlocks/0000755000004100000410000000000013541606342024613 5ustar www-datawww-datadevise-4.7.1/lib/generators/templates/simple_form_for/unlocks/new.html.erb0000644000004100000410000000104413541606342027040 0ustar www-datawww-data

Resend unlock instructions

<%= 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 %>
<%= f.input :email, required: true, autofocus: true, input_html: { autocomplete: "email" } %>
<%= f.button :submit, "Resend unlock instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-4.7.1/lib/generators/templates/simple_form_for/passwords/0000755000004100000410000000000013541606342025162 5ustar www-datawww-datadevise-4.7.1/lib/generators/templates/simple_form_for/passwords/new.html.erb0000644000004100000410000000100613541606342027405 0ustar www-datawww-data

Forgot your password?

<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> <%= f.error_notification %>
<%= f.input :email, required: true, autofocus: true, input_html: { autocomplete: "email" } %>
<%= f.button :submit, "Send me reset password instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-4.7.1/lib/generators/templates/simple_form_for/passwords/edit.html.erb0000644000004100000410000000164713541606342027554 0ustar www-datawww-data

Change your password

<%= 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 %>
<%= f.input :password, label: "New password", required: true, autofocus: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length), input_html: { autocomplete: "new-password" } %> <%= f.input :password_confirmation, label: "Confirm your new password", required: true, input_html: { autocomplete: "new-password" } %>
<%= f.button :submit, "Change my password" %>
<% end %> <%= render "devise/shared/links" %> devise-4.7.1/lib/generators/templates/simple_form_for/confirmations/0000755000004100000410000000000013541606342026010 5ustar www-datawww-datadevise-4.7.1/lib/generators/templates/simple_form_for/confirmations/new.html.erb0000644000004100000410000000124513541606342030240 0ustar www-datawww-data

Resend confirmation instructions

<%= 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 %>
<%= f.input :email, required: true, autofocus: true, value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email), input_html: { autocomplete: "email" } %>
<%= f.button :submit, "Resend confirmation instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-4.7.1/lib/generators/templates/simple_form_for/sessions/0000755000004100000410000000000013541606342025003 5ustar www-datawww-datadevise-4.7.1/lib/generators/templates/simple_form_for/sessions/new.html.erb0000644000004100000410000000116013541606342027227 0ustar www-datawww-data

Log in

<%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<%= f.input :email, required: false, autofocus: true, input_html: { autocomplete: "email" } %> <%= f.input :password, required: false, input_html: { autocomplete: "current-password" } %> <%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %>
<%= f.button :submit, "Log in" %>
<% end %> <%= render "devise/shared/links" %> devise-4.7.1/lib/generators/mongoid/0000755000004100000410000000000013541606342017411 5ustar www-datawww-datadevise-4.7.1/lib/generators/mongoid/devise_generator.rb0000644000004100000410000000332413541606342023265 0ustar www-datawww-data# frozen_string_literal: true 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 < < ActiveRecord::Migration<%= migration_version %> 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 null: false 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 devise-4.7.1/lib/generators/active_record/templates/migration.rb0000644000004100000410000000123213541606342025100 0ustar www-datawww-data# frozen_string_literal: true class DeviseCreate<%= table_name.camelize %> < ActiveRecord::Migration<%= migration_version %> def change create_table :<%= table_name %><%= primary_key_type %> do |t| <%= migration_data -%> <% attributes.each do |attribute| -%> t.<%= attribute.type %> :<%= attribute.name %> <% end -%> t.timestamps null: false 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 devise-4.7.1/lib/generators/active_record/devise_generator.rb0000644000004100000410000000641013541606342024441 0ustar www-datawww-data# frozen_string_literal: true 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" class_option :primary_key_type, type: :string, desc: "The type for primary key" 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", "#{migration_path}/add_devise_to_#{table_name}.rb", migration_version: migration_version else migration_template "migration.rb", "#{migration_path}/devise_create_#{table_name}.rb", migration_version: migration_version 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 <= 5 end def postgresql? config = ActiveRecord::Base.configurations[Rails.env] config && config['adapter'] == 'postgresql' end def migration_version if rails5_and_up? "[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]" end end def primary_key_type primary_key_string if rails5_and_up? end def primary_key_string key_string = options[:primary_key_type] ", id: :#{key_string}" if key_string end end end end devise-4.7.1/lib/generators/devise/0000755000004100000410000000000013541606342017234 5ustar www-datawww-datadevise-4.7.1/lib/generators/devise/controllers_generator.rb0000644000004100000410000000305213541606342024175 0ustar www-datawww-data# frozen_string_literal: true 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. Use -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::SessionsController < Devise::SessionsController 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 devise-4.7.1/lib/generators/devise/views_generator.rb0000644000004100000410000001062613541606342022771 0ustar www-datawww-data# frozen_string_literal: true 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 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", "#{plural_scope}/shared/links" else content end end end def target_path @target_path ||= "app/views/#{plural_scope || :devise}" end def plural_scope @plural_scope ||= scope.presence && scope.underscore.pluralize 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! def copy_views if options[:views] options[:views].delete('mailer') end super end 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/#{plural_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), type: :boolean hook_for :erb, desc: "Generate erb mail views", default: !defined?(Markerb), type: :boolean end end end devise-4.7.1/lib/generators/devise/orm_helpers.rb0000644000004100000410000000174513541606342022107 0ustar www-datawww-data# frozen_string_literal: true module Devise module Generators module OrmHelpers def model_contents buffer = <<-CONTENT # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable CONTENT buffer end private def model_exists? File.exist?(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 if Rails.version >= '5.0.3' db_migrate_path else @migration_path ||= File.join("db", "migrate") end end def model_path @model_path ||= File.join("app", "models", "#{file_path}.rb") end end end end devise-4.7.1/lib/generators/devise/devise_generator.rb0000644000004100000410000000152513541606342023111 0ustar www-datawww-data# frozen_string_literal: true 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}".dup 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 devise-4.7.1/lib/generators/devise/install_generator.rb0000644000004100000410000000224213541606342023275 0ustar www-datawww-data# frozen_string_literal: true require 'rails/generators/base' require 'securerandom' module Devise module Generators MissingORMError = Class.new(Thor::Error) 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 unless options[:orm] raise MissingORMError, <<-ERROR.strip_heredoc An ORM must be set to install Devise in your application. Be sure to have an ORM like Active Record or Mongoid loaded in your app or configure your own at `config/application.rb`. config.generators do |g| g.orm :your_orm_gem end ERROR end 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 devise-4.7.1/lib/devise/0000755000004100000410000000000013541606342015063 5ustar www-datawww-datadevise-4.7.1/lib/devise/parameter_filter.rb0000644000004100000410000000237013541606342020737 0ustar www-datawww-data# frozen_string_literal: true 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| next unless conditions.key?(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 devise-4.7.1/lib/devise/version.rb0000644000004100000410000000011413541606342017071 0ustar www-datawww-data# frozen_string_literal: true module Devise VERSION = "4.7.1".freeze end devise-4.7.1/lib/devise/test/0000755000004100000410000000000013541606342016042 5ustar www-datawww-datadevise-4.7.1/lib/devise/test/controller_helpers.rb0000644000004100000410000001316213541606342022277 0ustar www-datawww-data# frozen_string_literal: true module Devise module Test # `Devise::Test::ControllerHelpers` 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::Test::ControllerHelpers` in integration tests. # # Examples # # class PostsTest < ActionController::TestCase # include Devise::Test::ControllerHelpers # # test 'authenticated users can GET index' do # sign_in users(:bob) # # get :index # assert_response :success # end # end # # Important: you should not test Warden specific behavior (like callbacks) # using `Devise::Test::ControllerHelpers` since it is a stub of the actual # behavior. Such callbacks should be tested in your integration suite instead. module ControllerHelpers extend ActiveSupport::Concern included do setup :setup_controller_for_warden, :warden end # Override process to consider warden. def process(*) _catch_warden { super } @response end # We need to set up 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: @request.env['warden'] ||= begin manager = Warden::Manager.new(nil) do |config| config.merge! Devise.warden_config end 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. # # * +resource+ - The resource that should be authenticated # * +scope+ - An optional +Symbol+ with the scope where the resource # should be signed in with. # Examples: # # sign_in users(:alice) # sign_in users(:alice), scope: :admin def sign_in(resource, deprecated = nil, scope: nil) if deprecated.present? scope = resource resource = deprecated ActiveSupport::Deprecation.warn <<-DEPRECATION.strip_heredoc [Devise] sign_in(:#{scope}, resource) on controller tests is deprecated and will be removed from Devise. Please use sign_in(resource, scope: :#{scope}) instead. DEPRECATION end scope ||= Devise::Mapping.find_scope!(resource) 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 = request.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 request.env["PATH_INFO"] = "/#{options[:action]}" request.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.response.content_type = headers["Content-Type"] unless Rails::VERSION::MAJOR >= 5 @controller.status = status @controller.response.body = response.body 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) status, headers, body = *ret # ensure the controller response is set to our response. @controller.response ||= @response @response.status = status @response.headers.merge!(headers) @response.body = body end ret end end end end devise-4.7.1/lib/devise/test/integration_helpers.rb0000644000004100000410000000330613541606342022436 0ustar www-datawww-data# frozen_string_literal: true module Devise # Devise::Test::IntegrationHelpers is a helper module for facilitating # authentication on Rails integration tests to bypass the required steps for # signin in or signin out a record. # # Examples # # class PostsTest < ActionDispatch::IntegrationTest # include Devise::Test::IntegrationHelpers # # test 'authenticated users can see posts' do # sign_in users(:bob) # # get '/posts' # assert_response :success # end # end module Test module IntegrationHelpers def self.included(base) base.class_eval do include Warden::Test::Helpers setup :setup_integration_for_devise teardown :teardown_integration_for_devise end end # Signs in a specific resource, mimicking a successfull sign in # operation through +Devise::SessionsController#create+. # # * +resource+ - The resource that should be authenticated # * +scope+ - An optional +Symbol+ with the scope where the resource # should be signed in with. def sign_in(resource, scope: nil) scope ||= Devise::Mapping.find_scope!(resource) login_as(resource, scope: scope) end # Signs out a specific scope from the session. # # * +resource_or_scope+ - The resource or scope that should be signed out. def sign_out(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) logout scope end protected def setup_integration_for_devise Warden.test_mode! end def teardown_integration_for_devise Warden.test_reset! end end end end devise-4.7.1/lib/devise/test_helpers.rb0000644000004100000410000000073013541606342020111 0ustar www-datawww-data# frozen_string_literal: true module Devise module TestHelpers def self.included(base) base.class_eval do ActiveSupport::Deprecation.warn <<-DEPRECATION.strip_heredoc [Devise] including `Devise::TestHelpers` is deprecated and will be removed from Devise. For controller tests, please include `Devise::Test::ControllerHelpers` instead. DEPRECATION include Devise::Test::ControllerHelpers end end end end devise-4.7.1/lib/devise/secret_key_finder.rb0000644000004100000410000000144213541606342021075 0ustar www-datawww-data# frozen_string_literal: true module Devise class SecretKeyFinder def initialize(application) @application = application end def find if @application.respond_to?(:credentials) && key_exists?(@application.credentials) @application.credentials.secret_key_base elsif @application.respond_to?(:secrets) && key_exists?(@application.secrets) @application.secrets.secret_key_base elsif @application.config.respond_to?(:secret_key_base) && key_exists?(@application.config) @application.config.secret_key_base elsif @application.respond_to?(:secret_key_base) && key_exists?(@application) @application.secret_key_base end end private def key_exists?(object) object.secret_key_base.present? end end end devise-4.7.1/lib/devise/omniauth/0000755000004100000410000000000013541606342016707 5ustar www-datawww-datadevise-4.7.1/lib/devise/omniauth/url_helpers.rb0000644000004100000410000000200613541606342021556 0ustar www-datawww-data# frozen_string_literal: true module Devise module OmniAuth module UrlHelpers def omniauth_authorize_path(resource_or_scope, provider, *args) scope = Devise::Mapping.find_scope!(resource_or_scope) _devise_route_context.send("#{scope}_#{provider}_omniauth_authorize_path", *args) end def omniauth_authorize_url(resource_or_scope, provider, *args) scope = Devise::Mapping.find_scope!(resource_or_scope) _devise_route_context.send("#{scope}_#{provider}_omniauth_authorize_url", *args) end def omniauth_callback_path(resource_or_scope, provider, *args) scope = Devise::Mapping.find_scope!(resource_or_scope) _devise_route_context.send("#{scope}_#{provider}_omniauth_callback_path", *args) end def omniauth_callback_url(resource_or_scope, provider, *args) scope = Devise::Mapping.find_scope!(resource_or_scope) _devise_route_context.send("#{scope}_#{provider}_omniauth_callback_url", *args) end end end end devise-4.7.1/lib/devise/omniauth/config.rb0000644000004100000410000000260513541606342020504 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/devise/controllers/0000755000004100000410000000000013541606342017431 5ustar www-datawww-datadevise-4.7.1/lib/devise/controllers/helpers.rb0000644000004100000410000002654013541606342021427 0ustar www-datawww-data# frozen_string_literal: true 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 if respond_to?(:helper_method) helper_method :warden, :signed_in?, :devise_controller? end 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_action :authenticate_blogger! # Redirects unless either a user or an admin are authenticated # before_action ->{ 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 if respond_to?(:helper_method) helper_method "current_#{group_name}", "current_#{group_name.to_s.pluralize}", "#{group_name}_signed_in?" end 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_actions, # 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_action :authenticate_user! # Tell devise to use :user map # before_action :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 if respond_to?(:helper_method) helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session" end end end # The main accessor for the warden proxy instance def warden request.env['warden'] or raise MissingWarden 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_action :my_filter, unless: :devise_controller? def devise_controller? is_a?(::DeviseController) end # Set up 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 ||= Devise::ParameterSanitizer.new(resource_class, resource_name, params) 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: # # get '/users' => 'users#index', as: :user_root # creates user_root_path # # namespace :user do # root 'users#index' # 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? request.respond_to?(:flash) && is_navigational_format? end private def expire_data_after_sign_out! Devise.mappings.each { |_,m| instance_variable_set("@current_#{m.name}", nil) } super end end end class MissingWarden < StandardError def initialize super "Devise could not find the `Warden::Proxy` instance on your request environment.\n" + \ "Make sure that your application is loading Devise and Warden as expected and that " + \ "the `Warden::Manager` middleware is present in your middleware stack.\n" + \ "If you are seeing this on one of your tests, ensure that your tests are either " + \ "executing the Rails middleware stack or that your tests are using the `Devise::Test::ControllerHelpers` " + \ "module to inject the `request.env['warden']` object for you." end end end devise-4.7.1/lib/devise/controllers/rememberable.rb0000644000004100000410000000364413541606342022407 0ustar www-datawww-data# frozen_string_literal: true 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 def remember_me_is_active?(resource) return false unless resource.respond_to?(:remember_me) scope = Devise::Mapping.find_scope!(resource) _, token, generated_at = cookies.signed[remember_key(resource, scope)] resource.remember_me?(token, generated_at) end # Remembers the given resource by setting up a cookie def remember_me(resource) return if request.env["devise.skip_storage"] scope = Devise::Mapping.find_scope!(resource) resource.remember_me! 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 devise-4.7.1/lib/devise/controllers/url_helpers.rb0000644000004100000410000000467313541606342022314 0ustar www-datawww-data# frozen_string_literal: true 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}" define_method method do |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 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 devise-4.7.1/lib/devise/controllers/store_location.rb0000644000004100000410000000405213541606342023003 0ustar www-datawww-data# frozen_string_literal: true 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_facebook_omniauth_authorize_path # def store_location_for(resource_or_scope, location) session_key = stored_location_key_for(resource_or_scope) path = extract_path_from_location(location) session[session_key] = path if path 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 def extract_path_from_location(location) uri = parse_uri(location) if uri path = remove_domain_from_uri(uri) path = add_fragment_back_to_path(uri, path) path end end def remove_domain_from_uri(uri) [uri.path.sub(/\A\/+/, '/'), uri.query].compact.join('?') end def add_fragment_back_to_path(uri, path) [path, uri.fragment].compact.join('#') end end end end devise-4.7.1/lib/devise/controllers/sign_in_out.rb0000644000004100000410000001137613541606342022303 0ustar www-datawww-data# frozen_string_literal: true 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. This will run authentication hooks, which may # cause exceptions to be thrown from this method; if you simply want to check # if a scope has already previously been authenticated without running # authentication hooks, you can directly call `warden.authenticated?(scope: scope)` 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. # If you are using a custom warden strategy and the timeoutable module, you have to # set `env["devise.skip_timeout"] = true` in the request to use this method, like we do # in the sessions controller: https://github.com/plataformatec/devise/blob/master/app/controllers/devise/sessions_controller.rb#L7 # # 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) # 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] ActiveSupport::Deprecation.warn(<<-DEPRECATION.strip_heredoc, caller) [Devise] bypass option is deprecated and it will be removed in future version of Devise. Please use bypass_sign_in method instead. Example: bypass_sign_in(user) DEPRECATION 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 in a user bypassing the 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: # # bypass_sign_in @user, scope: :user # bypass_sign_in @user def bypass_sign_in(resource, scope: nil) scope ||= Devise::Mapping.find_scope!(resource) expire_data_after_sign_in! warden.session_serializer.store(resource, scope) 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.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 alias :expire_data_after_sign_out! :expire_data_after_sign_in! end end end devise-4.7.1/lib/devise/controllers/scoped_views.rb0000644000004100000410000000056013541606342022451 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/devise/time_inflector.rb0000644000004100000410000000045313541606342020415 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/devise/models/0000755000004100000410000000000013541606342016346 5ustar www-datawww-datadevise-4.7.1/lib/devise/models/trackable.rb0000644000004100000410000000330213541606342020621 0ustar www-datawww-data# frozen_string_literal: true 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, extract_ip_from(request) 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) # We have to check if the user is already persisted before running # `save` here because invalid users can be saved if we don't. # See https://github.com/plataformatec/devise/issues/4673 for more details. return if new_record? update_tracked_fields(request) save(validate: false) end protected def extract_ip_from(request) request.remote_ip end end end end devise-4.7.1/lib/devise/models/timeoutable.rb0000644000004100000410000000212313541606342021203 0ustar www-datawww-data# frozen_string_literal: true 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) !timeout_in.nil? && last_access && last_access <= timeout_in.ago end def timeout_in self.class.timeout_in end private module ClassMethods Devise::Models.config(self, :timeout_in) end end end end devise-4.7.1/lib/devise/models/omniauthable.rb0000644000004100000410000000122613541606342021344 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/devise/models/rememberable.rb0000644000004100000410000001300513541606342021314 0ustar www-datawww-data# frozen_string_literal: true require 'devise/strategies/rememberable' require 'devise/hooks/rememberable' require 'devise/hooks/forgetable' module Devise module Models # Rememberable manages generating and clearing token for remembering 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 def self.required_fields(klass) [:remember_created_at] end def remember_me! self.remember_token ||= self.class.remember_token if respond_to?(:remember_token) self.remember_created_at ||= Time.now.utc 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 def remember_expires_at self.class.remember_for.from_now end def extend_remember_period self.class.extend_remember_period end def rememberable_value if respond_to?(:remember_token) remember_token elsif respond_to?(:authenticatable_salt) && (salt = authenticatable_salt.presence) salt else raise "authenticatable_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 # A callback initiated after successfully being remembered. This can be # used to insert your own logic that is only run after the user is # remembered. # # Example: # # def after_remembered # self.update_attribute(:invite_code, nil) # end # def after_remembered end def remember_me?(token, generated_at) # TODO: Normalize the JSON type coercion along with the Timeoutable hook # in a single place https://github.com/plataformatec/devise/blob/ffe9d6d406e79108cf32a2c6a1d0b3828849c40b/lib/devise/hooks/timeoutable.rb#L14-L18 if generated_at.is_a?(String) generated_at = time_from_json(generated_at) end # The token is only valid if: # 1. we have a date # 2. the current time does not pass the expiry period # 3. the record has a remember_created_at date # 4. the token date is bigger than the remember_created_at # 5. the token matches generated_at.is_a?(Time) && (self.class.remember_for.ago < generated_at) && (generated_at > (remember_created_at || Time.now).utc) && Devise.secure_compare(rememberable_value, token) end private def time_from_json(value) if value =~ /\A\d+\.\d+\Z/ Time.at(value.to_f) else Time.parse(value) rescue nil end 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, Time.now.utc.to_f.to_s] end # Recreate the user based on the stored cookie def serialize_from_cookie(*args) id, token, generated_at = *args record = to_adapter.get(id) record if record && record.remember_me?(token, generated_at) 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 devise-4.7.1/lib/devise/models/validatable.rb0000644000004100000410000000526213541606342021150 0ustar www-datawww-data# frozen_string_literal: true 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 6..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? if Devise.activerecord51? validates_uniqueness_of :email, allow_blank: true, case_sensitive: true, if: :will_save_change_to_email? validates_format_of :email, with: email_regexp, allow_blank: true, if: :will_save_change_to_email? else validates_uniqueness_of :email, allow_blank: true, if: :email_changed? validates_format_of :email, with: email_regexp, allow_blank: true, if: :email_changed? end 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 devise-4.7.1/lib/devise/models/database_authenticatable.rb0000644000004100000410000002041413541606342023655 0ustar www-datawww-data# frozen_string_literal: true require 'devise/strategies/database_authenticatable' module Devise module Models # Authenticatable Module, responsible for hashing the password and # validating the authenticity of a user while signing in. # # == Options # # DatabaseAuthenticatable adds the following options to devise_for: # # * +pepper+: a random string used to provide a more secure hash. Use # `rails secret` to generate new keys. # # * +stretches+: the cost given to bcrypt. # # * +send_email_changed_notification+: notify original email when it changes. # # * +send_password_change_notification+: notify email when password changes. # # == Examples # # User.find(1).valid_password?('password123') # returns true/false # module DatabaseAuthenticatable extend ActiveSupport::Concern included do after_update :send_email_changed_notification, if: :send_email_changed_notification? after_update :send_password_change_notification, if: :send_password_change_notification? attr_reader :password, :current_password attr_accessor :password_confirmation end def initialize(*args, &block) @skip_email_changed_notification = false @skip_password_change_notification = false super end # Skips sending the email changed notification after_update def skip_email_changed_notification! @skip_email_changed_notification = true end # Skips sending the password change notification after_update def skip_password_change_notification! @skip_password_change_notification = true end def self.required_fields(klass) [:encrypted_password] + klass.authentication_keys end # Generates a hashed password based on the given value. # For legacy reasons, we use `encrypted_password` to store # the hashed password. def password=(new_password) @password = new_password self.encrypted_password = password_digest(@password) if @password.present? end # Verifies whether a password (ie from sign in) is the user password. def valid_password?(password) Devise::Encryptor.compare(self.class, encrypted_password, 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) if options.present? ActiveSupport::Deprecation.warn <<-DEPRECATION.strip_heredoc [Devise] The second argument of `DatabaseAuthenticatable#update_with_password` (`options`) is deprecated and it will be removed in the next major version. It was added to support a feature deprecated in Rails 4, so you can safely remove it from your code. DEPRECATION end 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(params, *options) else assign_attributes(params, *options) valid? 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) if options.present? ActiveSupport::Deprecation.warn <<-DEPRECATION.strip_heredoc [Devise] The second argument of `DatabaseAuthenticatable#update_without_password` (`options`) is deprecated and it will be removed in the next major version. It was added to support a feature deprecated in Rails 4, so you can safely remove it from your code. DEPRECATION end params.delete(:password) params.delete(:password_confirmation) result = update(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 valid? 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 if Devise.activerecord51? # Send notification to user when email changes. def send_email_changed_notification send_devise_notification(:email_changed, to: email_before_last_save) end else # Send notification to user when email changes. def send_email_changed_notification send_devise_notification(:email_changed, to: email_was) end end # Send notification to user when password changes. def send_password_change_notification send_devise_notification(:password_change) end protected # Hashes the password using bcrypt. Custom hash functions should override # this method to apply their own algorithm. # # See https://github.com/plataformatec/devise-encryptable for examples # of other hashing engines. def password_digest(password) Devise::Encryptor.digest(self.class, password) end if Devise.activerecord51? def send_email_changed_notification? self.class.send_email_changed_notification && saved_change_to_email? && !@skip_email_changed_notification end else def send_email_changed_notification? self.class.send_email_changed_notification && email_changed? && !@skip_email_changed_notification end end if Devise.activerecord51? def send_password_change_notification? self.class.send_password_change_notification && saved_change_to_encrypted_password? && !@skip_password_change_notification end else def send_password_change_notification? self.class.send_password_change_notification && encrypted_password_changed? && !@skip_password_change_notification end end module ClassMethods Devise::Models.config(self, :pepper, :stretches, :send_email_changed_notification, :send_password_change_notification) # 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 devise-4.7.1/lib/devise/models/authenticatable.rb0000644000004100000410000003022613541606342022033 0ustar www-datawww-data# frozen_string_literal: true 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 can 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 # Redefine 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 serializable_hash(options = nil) options = options.try(:dup) || {} 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 # Redefine inspect using serializable_hash, to ensure we don't accidentally # leak passwords into exceptions. def inspect inspection = serializable_hash.collect do |k,v| "#{k}: #{respond_to?(:attribute_for_inspect) ? attribute_for_inspect(k) : v.inspect}" end "#<#{self.class} #{inspection.join(", ")}>" 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 (active job, 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. # # The following example uses Active Job's `deliver_later` : # # class User # devise :database_authenticatable, :confirmable # # after_commit :send_pending_devise_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_devise_notifications << [notification, args] # else # render_and_send_devise_message(notification, *args) # end # end # # private # # def send_pending_devise_notifications # pending_devise_notifications.each do |notification, args| # render_and_send_devise_message(notification, *args) # 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_devise_notifications.clear # end # # def pending_devise_notifications # @pending_devise_notifications ||= [] # end # # def render_and_send_devise_message(notification, *args) # message = devise_mailer.send(notification, self, *args) # # # Deliver later with Active Job's `deliver_later` # if message.respond_to?(:deliver_later) # message.deliver_later # # Remove once we move to Rails 4.2+ only, as `deliver` is deprecated. # elsif message.respond_to?(:deliver_now) # message.deliver_now # else # message.deliver # end # 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 a 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 or 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 or initialize a record with group of attributes based on a list of required attributes. def find_or_initialize_with_errors(required_attributes, attributes, error=:invalid) #:nodoc: attributes.try(:permit!) attributes = attributes.to_h.with_indifferent_access .slice(*required_attributes) .delete_if { |key, value| value.blank? } if attributes.size == required_attributes.size record = find_first_by_auth_conditions(attributes) and return record end new(devise_parameter_filter.filter(attributes)).tap do |record| required_attributes.each do |key| record.errors.add(key, attributes[key].blank? ? :blank : error) end end end protected def devise_parameter_filter @devise_parameter_filter ||= Devise::ParameterFilter.new(case_insensitive_keys, strip_whitespace_keys) end end end end end devise-4.7.1/lib/devise/models/lockable.rb0000644000004100000410000001661113541606342020454 0ustar www-datawww-data# frozen_string_literal: true 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 set up 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 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 increment_failed_attempts if attempts_exceeded? lock_access! unless access_locked? else save(validate: false) end false end end def increment_failed_attempts self.class.increment_counter(:failed_attempts, id) reload 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 # List of strategies that are enabled/supported if :both is used. BOTH_STRATEGIES = [:time, :email] # 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) self.unlock_strategy == strategy || (self.unlock_strategy == :both && BOTH_STRATEGIES.include?(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 devise-4.7.1/lib/devise/models/confirmable.rb0000644000004100000410000004033413541606342021160 0ustar www-datawww-data# frozen_string_literal: true 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. # # Confirmable tracks the following columns: # # * confirmation_token - A unique random token # * confirmed_at - A timestamp when the user clicked the confirmation link # * confirmation_sent_at - A timestamp when the confirmation_token was generated (not sent) # * unconfirmed_email - An email address copied from the email attr. After confirmation # this value is copied to the email attr then cleared # # == 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 set up (t.reconfirmable in migrations). Until confirmed, new email is # stored in unconfirmed email column, and copied to email column on successful # confirmation. Also, when used in conjunction with `send_email_changed_notification`, # the notification is sent to the original email when the change is requested, # not when the unconfirmed email is confirmed. # * +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. # Confirmable will not generate a new token if a repeat confirmation is requested # during this time frame, unless the user's email changed too. # # == 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 included do before_create :generate_confirmation_token, if: :confirmation_required? after_create :skip_reconfirmation_in_callback!, if: :send_confirmation_notification? if defined?(ActiveRecord) && self < ActiveRecord::Base # ActiveRecord after_commit :send_on_create_confirmation_instructions, on: :create, if: :send_confirmation_notification? after_commit :send_reconfirmation_instructions, on: :update, if: :reconfirmation_required? else # Mongoid after_create :send_on_create_confirmation_instructions, if: :send_confirmation_notification? after_update :send_reconfirmation_instructions, if: :reconfirmation_required? end before_update :postpone_email_change_until_confirmation_and_regenerate_confirmation_token, if: :postpone_email_change? end def initialize(*args, &block) @bypass_confirmation_postpone = false @skip_reconfirmation_in_callback = 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(args={}) 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.confirmed_at = Time.now.utc saved = if pending_reconfirmation? 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: args[:ensure_valid] == true) 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 # To not require reconfirmation after creating with #save called in a # callback call skip_create_confirmation! def skip_reconfirmation_in_callback! @skip_reconfirmation_in_callback = true end # 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. # allow_unconfirmed_access_for 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? return true if self.class.allow_unconfirmed_access_for.nil? return false if self.class.allow_unconfirmed_access_for == 0.days 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 && self.confirmation_sent_at && (Time.now.utc > self.confirmation_sent_at.utc + 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 in confirmation_sent_at def generate_confirmation_token if self.confirmation_token && !confirmation_period_expired? @raw_confirmation_token = self.confirmation_token else self.confirmation_token = @raw_confirmation_token = Devise.friendly_token self.confirmation_sent_at = Time.now.utc end end def generate_confirmation_token! generate_confirmation_token && save(validate: false) end if Devise.activerecord51? def postpone_email_change_until_confirmation_and_regenerate_confirmation_token @reconfirmation_required = true self.unconfirmed_email = self.email self.email = self.email_in_database self.confirmation_token = nil generate_confirmation_token end else def postpone_email_change_until_confirmation_and_regenerate_confirmation_token @reconfirmation_required = true self.unconfirmed_email = self.email self.email = self.email_was self.confirmation_token = nil generate_confirmation_token end end if Devise.activerecord51? def postpone_email_change? postpone = self.class.reconfirmable && will_save_change_to_email? && !@bypass_confirmation_postpone && self.email.present? && (!@skip_reconfirmation_in_callback || !self.email_in_database.nil?) @bypass_confirmation_postpone = false postpone end else def postpone_email_change? postpone = self.class.reconfirmable && email_changed? && !@bypass_confirmation_postpone && self.email.present? && (!@skip_reconfirmation_in_callback || !self.email_was.nil?) @bypass_confirmation_postpone = false postpone end end def reconfirmation_required? self.class.reconfirmable && @reconfirmation_required && (self.email.present? || self.unconfirmed_email.present?) end def send_confirmation_notification? confirmation_required? && !@skip_confirmation_notification && self.email.present? end # With reconfirmable, notify the original email when the user first # requests the email change, instead of when the change is confirmed. def send_email_changed_notification? if self.class.reconfirmable self.class.send_email_changed_notification && reconfirmation_required? else super end end # A callback initiated after successfully confirming. This can be # used to insert your own logic that is only run after the user successfully # confirms. # # Example: # # def after_confirmation # self.update_attribute(:invite_code, nil) # 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) # When the `confirmation_token` parameter is blank, if there are any users with a blank # `confirmation_token` in the database, the first one would be confirmed here. # The error is being manually added here to ensure no users are confirmed by mistake. # This was done in the model for convenience, since validation errors are automatically # displayed in the view. if confirmation_token.blank? confirmable = new confirmable.errors.add(:confirmation_token, :blank) return confirmable end confirmable = find_first_by_auth_conditions(confirmation_token: confirmation_token) unless confirmable confirmation_digest = Devise.token_generator.digest(self, :confirmation_token, confirmation_token) confirmable = find_or_initialize_with_error_by(:confirmation_token, confirmation_digest) end # TODO: replace above lines with # confirmable = find_or_initialize_with_error_by(:confirmation_token, confirmation_token) # after enough time has passed that Devise clients do not use digested tokens confirmable.confirm if confirmable.persisted? confirmable end # Find a record for confirmation by unconfirmed email field def find_by_unconfirmed_email_with_errors(attributes = {}) attributes = attributes.slice(*confirmation_keys).permit!.to_h if attributes.respond_to? :permit 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 devise-4.7.1/lib/devise/models/registerable.rb0000644000004100000410000000147113541606342021346 0ustar www-datawww-data# frozen_string_literal: true 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 Devise::Models.config(self, :sign_in_after_change_password) end end end end devise-4.7.1/lib/devise/models/recoverable.rb0000644000004100000410000001545613541606342021177 0ustar www-datawww-data# frozen_string_literal: true 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 # * +reset_password_within+: the time period within which the password must be reset or the token expires. # * +sign_in_after_reset_password+: whether or not to sign in the user automatically after a password reset. # # == Examples # # # resets the user password and save the record, true if valid passwords are given, otherwise false # User.find(1).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 included do before_update :clear_reset_password_token, if: :clear_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) if new_password.present? self.password = new_password self.password_confirmation = new_password_confirmation save else errors.add(:password, :blank) false end 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.utc end protected # Removes reset_password token def clear_reset_password_token self.reset_password_token = nil self.reset_password_sent_at = nil 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 save(validate: false) raw end def send_reset_password_instructions_notification(token) send_devise_notification(:reset_password_instructions, token, {}) end if Devise.activerecord51? def clear_reset_password_token? encrypted_password_changed = respond_to?(:will_save_change_to_encrypted_password?) && will_save_change_to_encrypted_password? authentication_keys_changed = self.class.authentication_keys.any? do |attribute| respond_to?("will_save_change_to_#{attribute}?") && send("will_save_change_to_#{attribute}?") end authentication_keys_changed || encrypted_password_changed end else def clear_reset_password_token? encrypted_password_changed = respond_to?(:encrypted_password_changed?) && encrypted_password_changed? authentication_keys_changed = self.class.authentication_keys.any? do |attribute| respond_to?("#{attribute}_changed?") && send("#{attribute}_changed?") end authentication_keys_changed || encrypted_password_changed end 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 if recoverable.reset_password_token.present? recoverable end Devise::Models.config(self, :reset_password_keys, :reset_password_within, :sign_in_after_reset_password) end end end end devise-4.7.1/lib/devise/strategies/0000755000004100000410000000000013541606342017235 5ustar www-datawww-datadevise-4.7.1/lib/devise/strategies/base.rb0000644000004100000410000000117613541606342020501 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/devise/strategies/rememberable.rb0000644000004100000410000000366513541606342022216 0ustar www-datawww-data# frozen_string_literal: true 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) if extend_remember_me?(resource) resource.after_remembered success!(resource) end end # No need to clean up the CSRF when using rememberable. # In fact, cleaning it up here would be a bug because # rememberable is triggered on GET requests which means # we would render a page on first access with all csrf # tokens expired. def clean_up_csrf? false end private def extend_remember_me?(resource) resource.respond_to?(:extend_remember_period) && resource.extend_remember_period 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) devise-4.7.1/lib/devise/strategies/database_authenticatable.rb0000644000004100000410000000232213541606342024542 0ustar www-datawww-data# frozen_string_literal: true 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 = password.present? && mapping.to.find_for_database_authentication(authentication_hash) hashed = false if validate(resource){ hashed = true; resource.valid_password?(password) } remember_me(resource) resource.after_database_authentication success!(resource) end # In paranoid mode, hash the password even when a resource doesn't exist for the given authentication key. # This is necessary to prevent enumeration attacks - e.g. the request is faster when a resource doesn't # exist in the database if the password hashing algorithm is not called. mapping.to.new.password = password if !hashed && Devise.paranoid unless resource Devise.paranoid ? fail(:invalid) : fail(:not_found_in_database) end end end end end Warden::Strategies.add(:database_authenticatable, Devise::Strategies::DatabaseAuthenticatable) devise-4.7.1/lib/devise/strategies/authenticatable.rb0000644000004100000410000001414113541606342022720 0ustar www-datawww-data# frozen_string_literal: true 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? # A block that will be triggered while validating can be optionally # given as parameter. Check Devise::Models::Authenticatable.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 http 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 # Note: unlike `Model.valid_password?`, this method does not actually # ensure that the password in the params matches the password stored in # the database. It only checks if the password is *present*. Do not rely # on this method for validating that a given password is correct. def valid_password? password.present? end # Helper to decode credentials from HTTP. def decode_credentials return [] unless request.authorization && request.authorization =~ /^Basic (.*)/mi 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 devise-4.7.1/lib/devise/orm/0000755000004100000410000000000013541606342015660 5ustar www-datawww-datadevise-4.7.1/lib/devise/orm/active_record.rb0000644000004100000410000000022213541606342021012 0ustar www-datawww-data# frozen_string_literal: true require 'orm_adapter/adapters/active_record' ActiveSupport.on_load(:active_record) do extend Devise::Models end devise-4.7.1/lib/devise/orm/mongoid.rb0000644000004100000410000000026013541606342017637 0ustar www-datawww-data# frozen_string_literal: true ActiveSupport.on_load(:mongoid) do require 'orm_adapter/adapters/mongoid' Mongoid::Document::ClassMethods.send :include, Devise::Models end devise-4.7.1/lib/devise/rails/0000755000004100000410000000000013541606342016175 5ustar www-datawww-datadevise-4.7.1/lib/devise/rails/routes.rb0000644000004100000410000004726213541606342020056 0ustar www-datawww-data# frozen_string_literal: true require "active_support/core_ext/object/try" require "active_support/core_ext/hash/slice" module Devise module RouteSet def finalize! result = super @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 end end 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. prepend Devise::RouteSet 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: set up 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 set up path name that will be used, as rails routes does. # The following route configuration would set up your route as /accounts instead of /users: # # devise_for :users, path: 'accounts' # # * singular: set up the singular name for the given resource. This is used as the helper methods # names in controller ("authenticate_#{singular}!", "#{singular}_signed_in?", "current_#{singular}" # and "#{singular}_session"), as the scope name in routes and as the scope given to warden. # # devise_for :admins, singular: :manager # # devise_scope :manager do # ... # end # # class ManagerController < ApplicationController # before_action authenticate_manager! # # def show # @manager = current_manager # ... # end # end # # * 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: :delete), # if you wish to restrict this to accept only :post or :delete requests you should do: # # devise_for :users, sign_out_via: [:get, :post] # # 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 targeted. # # 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` to the `devise_for` call and extract omniauth options to another `devise_for` call outside the scope. Here is an example: devise_for :users, only: :omniauth_callbacks, controllers: {omniauth_callbacks: 'users/omniauth_callbacks'} scope '/(:locale)', locale: /ru|en/ do devise_for :users, skip: :omniauth_callbacks end ERROR end current_scope = @scope.dup if @scope.respond_to? :new @scope = @scope.new path: nil else @scope[:path] = nil end path_prefix = Devise.omniauth_path_prefix || "/#{mapping.fullpath}/auth".squeeze("/") set_omniauth_path_prefix!(path_prefix) mapping.to.omniauth_providers.each do |provider| match "#{path_prefix}/#{provider}", to: "#{controllers[:omniauth_callbacks]}#passthru", as: "#{provider}_omniauth_authorize", via: [:get, :post] match "#{path_prefix}/#{provider}/callback", to: "#{controllers[:omniauth_callbacks]}##{provider}", as: "#{provider}_omniauth_callback", via: [:get, :post] end ensure @scope = current_scope 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)) if @scope.respond_to? :new @scope = @scope.new exclusive else exclusive.each_pair { |key, value| @scope[key] = value } end 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 devise-4.7.1/lib/devise/rails/warden_compat.rb0000644000004100000410000000035113541606342021344 0ustar www-datawww-data# frozen_string_literal: true module Warden::Mixins::Common def request @request ||= ActionDispatch::Request.new(env) end def reset_session! request.reset_session end def cookies request.cookie_jar end end devise-4.7.1/lib/devise/mapping.rb0000644000004100000410000001261413541606342017047 0ustar www-datawww-data# frozen_string_literal: true 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) obj = obj.devise_scope if obj.respond_to?(:devise_scope) 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 devise-4.7.1/lib/devise/models.rb0000644000004100000410000000673713541606342016710 0ustar www-datawww-data# frozen_string_literal: true 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::Models::DatabaseAuthenticatable, :stretches) # # 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' devise-4.7.1/lib/devise/omniauth.rb0000644000004100000410000000201013541606342017225 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/devise/rails.rb0000644000004100000410000000252213541606342016523 0ustar www-datawww-data# frozen_string_literal: true 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 do |app| app.reload_routes! if Devise.reload_routes end initializer "devise.url_helpers" do Devise.include_helpers(Devise::Controllers) end initializer "devise.omniauth", after: :load_config_initializers, before: :build_middleware_stack 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| Devise.secret_key ||= Devise::SecretKeyFinder.new(app).find Devise.token_generator ||= if secret_key = Devise.secret_key Devise::TokenGenerator.new( ActiveSupport::CachingKeyGenerator.new(ActiveSupport::KeyGenerator.new(secret_key)) ) end end end end devise-4.7.1/lib/devise/parameter_sanitizer.rb0000644000004100000410000001313413541606342021462 0ustar www-datawww-data# frozen_string_literal: true module Devise # The +ParameterSanitizer+ deals with permitting specific parameters values # for each +Devise+ scope in the application. # # The sanitizer knows about Devise default parameters (like +password+ and # +password_confirmation+ for the `RegistrationsController`), and you can # extend or change the permitted parameters list on your controllers. # # === Permitting new parameters # # You can add new parameters to the permitted list using the +permit+ method # in a +before_action+ method, for instance. # # class ApplicationController < ActionController::Base # before_action :configure_permitted_parameters, if: :devise_controller? # # protected # # def configure_permitted_parameters # # Permit the `subscribe_newsletter` parameter along with the other # # sign up parameters. # devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter]) # end # end # # Using a block yields an +ActionController::Parameters+ object so you can # permit nested parameters and have more control over how the parameters are # permitted in your controller. # # def configure_permitted_parameters # devise_parameter_sanitizer.permit(:sign_up) do |user| # user.permit(newsletter_preferences: []) # end # end class ParameterSanitizer DEFAULT_PERMITTED_ATTRIBUTES = { sign_in: [:password, :remember_me], sign_up: [:password, :password_confirmation], account_update: [:password, :password_confirmation, :current_password] } def initialize(resource_class, resource_name, params) @auth_keys = extract_auth_keys(resource_class) @params = params @resource_name = resource_name @permitted = {} DEFAULT_PERMITTED_ATTRIBUTES.each_pair do |action, keys| permit(action, keys: keys) end end # Sanitize the parameters for a specific +action+. # # === Arguments # # * +action+ - A +Symbol+ with the action that the controller is # performing, like +sign_up+, +sign_in+, etc. # # === Examples # # # Inside the `RegistrationsController#create` action. # resource = build_resource(devise_parameter_sanitizer.sanitize(:sign_up)) # resource.save # # Returns an +ActiveSupport::HashWithIndifferentAccess+ with the permitted # attributes. def sanitize(action) permissions = @permitted[action] if permissions.respond_to?(:call) cast_to_hash permissions.call(default_params) elsif permissions.present? cast_to_hash permit_keys(default_params, permissions) else unknown_action!(action) end end # Add or remove new parameters to the permitted list of an +action+. # # === Arguments # # * +action+ - A +Symbol+ with the action that the controller is # performing, like +sign_up+, +sign_in+, etc. # * +keys:+ - An +Array+ of keys that also should be permitted. # * +except:+ - An +Array+ of keys that shouldn't be permitted. # * +block+ - A block that should be used to permit the action # parameters instead of the +Array+ based approach. The block will be # called with an +ActionController::Parameters+ instance. # # === Examples # # # Adding new parameters to be permitted in the `sign_up` action. # devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter]) # # # Removing the `password` parameter from the `account_update` action. # devise_parameter_sanitizer.permit(:account_update, except: [:password]) # # # Using the block form to completely override how we permit the # # parameters for the `sign_up` action. # devise_parameter_sanitizer.permit(:sign_up) do |user| # user.permit(:email, :password, :password_confirmation) # end # # # Returns nothing. def permit(action, keys: nil, except: nil, &block) if block_given? @permitted[action] = block end if keys.present? @permitted[action] ||= @auth_keys.dup @permitted[action].concat(keys) end if except.present? @permitted[action] ||= @auth_keys.dup @permitted[action] = @permitted[action] - except end end private # Cast a sanitized +ActionController::Parameters+ to a +HashWithIndifferentAccess+ # that can be used elsewhere. # # Returns an +ActiveSupport::HashWithIndifferentAccess+. def cast_to_hash(params) # TODO: Remove the `with_indifferent_access` method call when we only support Rails 5+. params && params.to_h.with_indifferent_access end def default_params if hashable_resource_params? @params.fetch(@resource_name) else empty_params end end def hashable_resource_params? @params[@resource_name].respond_to?(:permit) end def empty_params ActionController::Parameters.new({}) end def permit_keys(parameters, keys) parameters.permit(*keys) end def extract_auth_keys(klass) auth_keys = klass.authentication_keys auth_keys.respond_to?(:keys) ? auth_keys.keys : auth_keys end def unknown_action!(action) raise NotImplementedError, <<-MESSAGE.strip_heredoc "Devise doesn't know how to sanitize parameters for '#{action}'". If you want to define a new set of parameters to be sanitized use the `permit` method first: devise_parameter_sanitizer.permit(:#{action}, keys: [:param1, :param2, :param3]) MESSAGE end end end devise-4.7.1/lib/devise/token_generator.rb0000644000004100000410000000131413541606342020575 0ustar www-datawww-data# frozen_string_literal: true require 'openssl' 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 end devise-4.7.1/lib/devise/hooks/0000755000004100000410000000000013541606342016206 5ustar www-datawww-datadevise-4.7.1/lib/devise/hooks/proxy.rb0000644000004100000410000000074613541606342017723 0ustar www-datawww-data# frozen_string_literal: true 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, :request, to: :warden def initialize(warden) @warden = warden end def session warden.request.session end end end end devise-4.7.1/lib/devise/hooks/trackable.rb0000644000004100000410000000103513541606342020462 0ustar www-datawww-data# frozen_string_literal: true # 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 devise-4.7.1/lib/devise/hooks/timeoutable.rb0000644000004100000410000000246213541606342021051 0ustar www-datawww-data# frozen_string_literal: true # 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 && !env['devise.skip_timeoutable'] 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'] && !proxy.remember_me_is_active?(record) Devise.sign_out_all_scopes ? proxy.sign_out : proxy.sign_out(scope) 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 devise-4.7.1/lib/devise/hooks/forgetable.rb0000644000004100000410000000072013541606342020644 0ustar www-datawww-data# frozen_string_literal: true # 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 devise-4.7.1/lib/devise/hooks/rememberable.rb0000644000004100000410000000050413541606342021154 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/devise/hooks/activatable.rb0000644000004100000410000000101013541606342021002 0ustar www-datawww-data# frozen_string_literal: true # 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 devise-4.7.1/lib/devise/hooks/csrf_cleaner.rb0000644000004100000410000000057213541606342021165 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/devise/hooks/lockable.rb0000644000004100000410000000072613541606342020314 0ustar www-datawww-data# frozen_string_literal: true # 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]) unless record.failed_attempts.to_i.zero? record.failed_attempts = 0 record.save(validate: false) end end end devise-4.7.1/lib/devise/failure_app.rb0000644000004100000410000002023213541606342017676 0ustar www-datawww-data# frozen_string_literal: true require "action_controller/metal" module Devise # Failure application that will be called every time :warden is thrown from # any strategy or hook. It is responsible for redirecting the user to the sign # in page based on current scope and mapping. If no scope is given, it # redirects to the default_url. class FailureApp < ActionController::Metal 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 # Try retrieving the URL options from the parent controller (usually # ApplicationController). Instance methods are not supported at the moment, # so only the class-level attribute is used. def self.default_url_options(*args) if defined?(Devise.parent_controller.constantize) Devise.parent_controller.constantize.try(:default_url_options) || {} 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 header_info = if relative_url_root? base_path = Pathname.new(relative_url_root) full_path = Pathname.new(attempted_path) { "SCRIPT_NAME" => relative_url_root, "PATH_INFO" => '/' + full_path.relative_path_from(base_path).to_s } else { "PATH_INFO" => attempted_path } end header_info.each do | var, value| if request.respond_to?(:set_header) request.set_header(var, value) else request.env[var] = value end end flash.now[:alert] = i18n_message(:invalid) if is_flashing_format? # self.response = recall_app(warden_options[:recall]).call(env) self.response = recall_app(warden_options[:recall]).call(request.env) end def redirect store_location! if is_flashing_format? if flash[:timedout] && flash[:alert] flash.keep(:timedout) flash.keep(:alert) else flash[:alert] = i18n_message end 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] auth_keys = scope_class.authentication_keys keys = (auth_keys.respond_to?(:keys) ? auth_keys.keys : auth_keys).map { |key| scope_class.human_attribute_name(key) } options[:authentication_keys] = 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 if is_flashing_format? path = if request.get? attempted_path else request.referrer end path || scope_url else scope_url end end def route(scope) :"new_#{scope}_session_url" end def scope_url opts = {} # Initialize script_name with nil to prevent infinite loops in # authenticated mounted engines in rails 4.2 and 5.0 opts[:script_name] = nil route = route(scope) opts[:format] = request_format unless skip_format? router_name = Devise.mappings[scope].router_name || Devise.available_router_name context = send(router_name) if relative_url_root? opts[:script_name] = relative_url_root # We need to add the rootpath to `script_name` manually for applications that use a Rails # version lower than 5.1. Otherwise, it is going to generate a wrong path for Engines # that use Devise. Remove it when the support of Rails 5.0 is droped. elsif root_path_defined?(context) && !rails_51_and_up? rootpath = context.routes.url_helpers.root_path opts[:script_name] = rootpath.chomp('/') if rootpath.length > 1 end 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 an 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 doesn't 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 request.respond_to?(:get_header) ? request.get_header("warden") : request.env["warden"] end def warden_options request.respond_to?(:get_header) ? request.get_header("warden.options") : request.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 can't use # the 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 # Check if flash messages should be emitted. Default is to do it on # navigational formats def is_flashing_format? request.respond_to?(:flash) && is_navigational_format? end def request_format @request_format ||= request.format.try(:ref) end def relative_url_root @relative_url_root ||= begin config = Rails.application.config config.try(:relative_url_root) || config.action_controller.try(:relative_url_root) end end def relative_url_root? relative_url_root.present? end ActiveSupport.run_load_hooks(:devise_failure_app, self) private def root_path_defined?(context) defined?(context.routes) && context.routes.url_helpers.respond_to?(:root_path) end def rails_51_and_up? Rails.gem_version >= Gem::Version.new("5.1") end end end devise-4.7.1/lib/devise/delegator.rb0000644000004100000410000000064713541606342017365 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/lib/devise/encryptor.rb0000644000004100000410000000124313541606342017435 0ustar www-datawww-data# frozen_string_literal: true require 'bcrypt' module Devise module Encryptor def self.digest(klass, password) if klass.pepper.present? password = "#{password}#{klass.pepper}" end ::BCrypt::Password.create(password, cost: klass.stretches).to_s end def self.compare(klass, hashed_password, password) return false if hashed_password.blank? bcrypt = ::BCrypt::Password.new(hashed_password) if klass.pepper.present? password = "#{password}#{klass.pepper}" end password = ::BCrypt::Engine.hash_secret(password, bcrypt.salt) Devise.secure_compare(password, hashed_password) end end end devise-4.7.1/lib/devise/mailers/0000755000004100000410000000000013541606342016517 5ustar www-datawww-datadevise-4.7.1/lib/devise/mailers/helpers.rb0000644000004100000410000000476113541606342020516 0ustar www-datawww-data# frozen_string_literal: true module Devise module Mailers module Helpers extend ActiveSupport::Concern included do include Devise::Controllers::ScopedViews end protected attr_reader :scope_name, :resource # Configure default email options def devise_mail(record, action, opts = {}, &block) initialize_from_record(record) mail headers_for(action, opts), &block 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 # Set up 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 devise-4.7.1/lib/devise/modules.rb0000644000004100000410000000212313541606342017056 0ustar www-datawww-data# frozen_string_literal: true 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 devise-4.7.1/config/0000755000004100000410000000000013541606342014303 5ustar www-datawww-datadevise-4.7.1/config/locales/0000755000004100000410000000000013541606342015725 5ustar www-datawww-datadevise-4.7.1/config/locales/en.yml0000644000004100000410000001027513541606342017057 0ustar www-datawww-data# 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" email_changed: subject: "Email Changed" password_change: subject: "Password Changed" 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 confirmation link to confirm your new email address." updated: "Your account has been updated successfully." updated_but_not_signed_in: "Your account has been updated successfully, but since your password was changed, you need to sign in again" 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:" devise-4.7.1/MIT-LICENSE0000644000004100000410000000207713541606342014500 0ustar www-datawww-dataCopyright 2009-2019 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.