├── examples └── rails5_app │ ├── log │ └── .keep │ ├── tmp │ └── .keep │ ├── lib │ ├── assets │ │ └── .keep │ └── tasks │ │ └── .keep │ ├── public │ ├── favicon.ico │ ├── apple-touch-icon.png │ ├── apple-touch-icon-precomposed.png │ ├── robots.txt │ ├── 500.html │ ├── 422.html │ └── 404.html │ ├── test │ ├── helpers │ │ └── .keep │ ├── mailers │ │ └── .keep │ ├── models │ │ └── .keep │ ├── controllers │ │ └── .keep │ ├── fixtures │ │ ├── .keep │ │ └── files │ │ │ └── .keep │ ├── integration │ │ └── .keep │ └── test_helper.rb │ ├── app │ ├── assets │ │ ├── images │ │ │ └── .keep │ │ ├── javascripts │ │ │ ├── channels │ │ │ │ └── .keep │ │ │ ├── cable.js │ │ │ └── application.js │ │ ├── config │ │ │ └── manifest.js │ │ └── stylesheets │ │ │ └── application.css │ ├── models │ │ ├── concerns │ │ │ └── .keep │ │ ├── application_record.rb │ │ ├── email.rb │ │ └── user.rb │ ├── controllers │ │ ├── concerns │ │ │ └── .keep │ │ └── application_controller.rb │ ├── views │ │ └── layouts │ │ │ ├── mailer.text.erb │ │ │ ├── mailer.html.erb │ │ │ └── application.html.erb │ ├── helpers │ │ └── application_helper.rb │ ├── jobs │ │ └── application_job.rb │ ├── channels │ │ └── application_cable │ │ │ ├── channel.rb │ │ │ └── connection.rb │ └── mailers │ │ └── application_mailer.rb │ ├── vendor │ └── assets │ │ ├── javascripts │ │ └── .keep │ │ └── stylesheets │ │ └── .keep │ ├── bin │ ├── rake │ ├── bundle │ ├── rails │ ├── update │ └── setup │ ├── config │ ├── spring.rb │ ├── boot.rb │ ├── environment.rb │ ├── cable.yml │ ├── initializers │ │ ├── session_store.rb │ │ ├── mime_types.rb │ │ ├── application_controller_renderer.rb │ │ ├── filter_parameter_logging.rb │ │ ├── cookies_serializer.rb │ │ ├── backtrace_silencers.rb │ │ ├── assets.rb │ │ ├── wrap_parameters.rb │ │ ├── inflections.rb │ │ ├── new_framework_defaults.rb │ │ └── devise.rb │ ├── routes.rb │ ├── application.rb │ ├── database.yml │ ├── locales │ │ ├── en.yml │ │ └── devise.en.yml │ ├── secrets.yml │ ├── environments │ │ ├── test.rb │ │ ├── development.rb │ │ └── production.rb │ └── puma.rb │ ├── config.ru │ ├── db │ ├── migrate │ │ ├── 20170307145547_add_password_salt_to_users.rb │ │ └── 20170307140813_devise_create_users.rb │ ├── seeds.rb │ └── schema.rb │ ├── Rakefile │ ├── README.md │ ├── .gitignore │ ├── Gemfile │ └── Gemfile.lock ├── spec ├── rails_app │ ├── public │ │ ├── favicon.ico │ │ ├── 422.html │ │ ├── 404.html │ │ └── 500.html │ ├── app │ │ ├── views │ │ │ ├── home │ │ │ │ └── index.html.erb │ │ │ └── layouts │ │ │ │ └── application.html.erb │ │ ├── models │ │ │ ├── email.rb │ │ │ └── user.rb │ │ ├── controllers │ │ │ ├── home_controller.rb │ │ │ └── application_controller.rb │ │ └── helpers │ │ │ └── application_helper.rb │ ├── config │ │ ├── initializers │ │ │ ├── inflections.rb │ │ │ ├── session_store.rb │ │ │ ├── secret_token.rb │ │ │ ├── devise-multi_email.rb │ │ │ ├── backtrace_silencers.rb │ │ │ └── devise.rb │ │ ├── routes.rb │ │ ├── environment.rb │ │ ├── boot.rb │ │ ├── database.yml │ │ ├── application.rb │ │ └── environments │ │ │ ├── development.rb │ │ │ ├── test.rb │ │ │ └── production.rb │ ├── bin │ │ ├── rake │ │ ├── bundle │ │ └── rails │ ├── config.ru │ ├── Rakefile │ └── db │ │ ├── migrate │ │ └── 20160101102949_create_tables.rb │ │ └── schema.rb ├── rails_helper.rb ├── orm │ └── active_record.rb ├── features │ ├── validatable_spec.rb │ ├── registerable_spec.rb │ ├── authenticatable_spec.rb │ ├── recoverable_spec.rb │ └── confirmable_spec.rb ├── support │ └── features.rb ├── models │ └── parent_model_manager_spec.rb ├── multi_email_spec.rb └── spec_helper.rb ├── .rspec ├── gemfiles ├── rails_5_1.gemfile ├── rails_5_2.gemfile └── rails_6_0.gemfile ├── lib └── devise │ ├── multi_email │ ├── version.rb │ ├── email_model_manager.rb │ ├── email_model_extensions.rb │ ├── parent_model_extensions.rb │ ├── association_manager.rb │ ├── parent_model_manager.rb │ └── models │ │ ├── authenticatable.rb │ │ ├── confirmable.rb │ │ └── validatable.rb │ └── multi_email.rb ├── Gemfile ├── Rakefile ├── bin ├── setup └── console ├── .gitignore ├── .travis.yml ├── LICENSE.txt ├── devise-multi_email.gemspec ├── CODE_OF_CONDUCT.md ├── CHANGELOG.md └── README.md /examples/rails5_app/log/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/tmp/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spec/rails_app/public/favicon.ico: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/lib/assets/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/lib/tasks/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/public/favicon.ico: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/test/helpers/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/test/mailers/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/test/models/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/app/assets/images/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/test/controllers/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/test/fixtures/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/test/integration/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --format documentation 2 | --color 3 | -------------------------------------------------------------------------------- /examples/rails5_app/app/models/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/public/apple-touch-icon.png: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/test/fixtures/files/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/app/controllers/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/vendor/assets/javascripts/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/vendor/assets/stylesheets/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spec/rails_app/app/views/home/index.html.erb: -------------------------------------------------------------------------------- 1 | Home! -------------------------------------------------------------------------------- /examples/rails5_app/app/assets/javascripts/channels/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/public/apple-touch-icon-precomposed.png: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/rails5_app/app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /examples/rails5_app/app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | module ApplicationHelper 2 | end 3 | -------------------------------------------------------------------------------- /examples/rails5_app/app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | end 3 | -------------------------------------------------------------------------------- /spec/rails_app/app/models/email.rb: -------------------------------------------------------------------------------- 1 | class Email < ActiveRecord::Base 2 | belongs_to :user 3 | end 4 | -------------------------------------------------------------------------------- /spec/rails_app/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | ActiveSupport::Inflector.inflections do |inflect| 2 | end 3 | -------------------------------------------------------------------------------- /gemfiles/rails_5_1.gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | gem "rails", "~> 5.1.1" 4 | 5 | gemspec path: "../" 6 | -------------------------------------------------------------------------------- /gemfiles/rails_5_2.gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | gem "rails", "~> 5.2.0" 4 | 5 | gemspec path: "../" 6 | -------------------------------------------------------------------------------- /lib/devise/multi_email/version.rb: -------------------------------------------------------------------------------- 1 | module Devise 2 | module MultiEmail 3 | VERSION = "3.0.1" 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /gemfiles/rails_6_0.gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | gem "rails", ">= 6.0.2.1", "< 6.1" 4 | 5 | gemspec path: "../" 6 | -------------------------------------------------------------------------------- /spec/rails_app/app/controllers/home_controller.rb: -------------------------------------------------------------------------------- 1 | class HomeController < ApplicationController 2 | def index 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /spec/rails_app/bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require_relative '../config/boot' 3 | require 'rake' 4 | Rake.application.run 5 | -------------------------------------------------------------------------------- /examples/rails5_app/bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require_relative '../config/boot' 3 | require 'rake' 4 | Rake.application.run 5 | -------------------------------------------------------------------------------- /examples/rails5_app/app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /examples/rails5_app/app/models/email.rb: -------------------------------------------------------------------------------- 1 | class Email < ApplicationRecord 2 | belongs_to :user 3 | 4 | table_name 'user_emails' 5 | end 6 | -------------------------------------------------------------------------------- /spec/rails_app/config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | RailsApp::Application.config.session_store :cookie_store, key: '_rails_app_session' 2 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gem 'rails' 4 | 5 | # Specify your gem's dependencies in devise-multi_email.gemspec 6 | gemspec 7 | 8 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require "bundler/gem_tasks" 2 | require "rspec/core/rake_task" 3 | 4 | RSpec::Core::RakeTask.new(:spec) 5 | 6 | task :default => :spec 7 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | 5 | bundle install 6 | 7 | # Do any other automated setup that you need to do here 8 | -------------------------------------------------------------------------------- /examples/rails5_app/app/channels/application_cable/channel.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Channel < ActionCable::Channel::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /examples/rails5_app/app/assets/config/manifest.js: -------------------------------------------------------------------------------- 1 | //= link_tree ../images 2 | //= link_directory ../javascripts .js 3 | //= link_directory ../stylesheets .css 4 | -------------------------------------------------------------------------------- /examples/rails5_app/app/channels/application_cable/connection.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Connection < ActionCable::Connection::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /spec/rails_app/bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /examples/rails5_app/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | protect_from_forgery with: :exception 3 | end 4 | -------------------------------------------------------------------------------- /examples/rails5_app/app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | default from: 'from@example.com' 3 | layout 'mailer' 4 | end 5 | -------------------------------------------------------------------------------- /examples/rails5_app/bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /examples/rails5_app/config/spring.rb: -------------------------------------------------------------------------------- 1 | %w( 2 | .ruby-version 3 | .rbenv-vars 4 | tmp/restart.txt 5 | tmp/caching-dev.txt 6 | ).each { |path| Spring.watch(path) } 7 | -------------------------------------------------------------------------------- /spec/rails_app/config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | # Users scope 3 | devise_for :users 4 | 5 | root to: 'home#index', via: [:get, :post] 6 | end 7 | -------------------------------------------------------------------------------- /examples/rails5_app/config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 2 | 3 | require 'bundler/setup' # Set up gems listed in the Gemfile. 4 | -------------------------------------------------------------------------------- /spec/rails_app/app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | # Methods added to this helper will be available to all templates in the application. 2 | module ApplicationHelper 3 | end 4 | -------------------------------------------------------------------------------- /examples/rails5_app/config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require_relative 'config/environment' 4 | 5 | run Rails.application 6 | -------------------------------------------------------------------------------- /examples/rails5_app/bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_PATH = File.expand_path('../config/application', __dir__) 3 | require_relative '../config/boot' 4 | require 'rails/commands' 5 | -------------------------------------------------------------------------------- /spec/rails_app/bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_PATH = File.expand_path('../../config/application', __FILE__) 3 | require_relative '../config/boot' 4 | require 'rails/commands' 5 | -------------------------------------------------------------------------------- /examples/rails5_app/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require_relative 'application' 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /examples/rails5_app/config/cable.yml: -------------------------------------------------------------------------------- 1 | development: 2 | adapter: async 3 | 4 | test: 5 | adapter: async 6 | 7 | production: 8 | adapter: redis 9 | url: redis://localhost:6379/1 10 | -------------------------------------------------------------------------------- /spec/rails_app/config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require ::File.expand_path('../config/environment', __FILE__) 4 | run RailsApp::Application 5 | -------------------------------------------------------------------------------- /examples/rails5_app/config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Rails.application.config.session_store :cookie_store, key: '_rails5_app_session' 4 | -------------------------------------------------------------------------------- /examples/rails5_app/config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | devise_for :users 3 | # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html 4 | end 5 | -------------------------------------------------------------------------------- /spec/rails_app/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the rails application. 2 | require File.expand_path('../application', __FILE__) 3 | 4 | # Initialize the rails application. 5 | RailsApp::Application.initialize! 6 | -------------------------------------------------------------------------------- /spec/rails_app/config/boot.rb: -------------------------------------------------------------------------------- 1 | # Set up gems listed in the Gemfile. 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) 3 | require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) 4 | -------------------------------------------------------------------------------- /examples/rails5_app/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /examples/rails5_app/db/migrate/20170307145547_add_password_salt_to_users.rb: -------------------------------------------------------------------------------- 1 | class AddPasswordSaltToUsers < ActiveRecord::Migration[5.0] 2 | def change 3 | add_column :users, :password_salt, :string 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /Gemfile.lock 4 | /_yardoc/ 5 | /coverage/ 6 | /doc/ 7 | /pkg/ 8 | /spec/reports/ 9 | /tmp/ 10 | /spec/rails_app/log/* 11 | /.ruby-version 12 | /.idea/ 13 | /gemfiles/*gemfile.lock 14 | -------------------------------------------------------------------------------- /spec/rails_app/config/initializers/secret_token.rb: -------------------------------------------------------------------------------- 1 | config = Rails.application.config 2 | 3 | config.secret_key_base = 'd588e99efff13a86461fd6ab82327823ad2f8feb5dc217ce652cdd9f0dfc5eb4b5a62a92d24d2574d7d51dfb1ea8dd453ea54e00cf672159a13104a135422a10' 4 | -------------------------------------------------------------------------------- /examples/rails5_app/config/initializers/application_controller_renderer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # ApplicationController.renderer.defaults.merge!( 4 | # http_host: 'example.org', 5 | # https: false 6 | # ) 7 | -------------------------------------------------------------------------------- /examples/rails5_app/public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | # 3 | # To ban all spiders from the entire site uncomment the next two lines: 4 | # User-agent: * 5 | # Disallow: / 6 | -------------------------------------------------------------------------------- /spec/rails_app/config/initializers/devise-multi_email.rb: -------------------------------------------------------------------------------- 1 | 2 | Devise::MultiEmail.configure do |config| 3 | #config.autosave_emails = false 4 | #config.primary_email_method_name = :primary_email 5 | #config.only_login_with_primary_email = false 6 | end 7 | -------------------------------------------------------------------------------- /examples/rails5_app/config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /examples/rails5_app/Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require_relative 'config/application' 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /spec/rails_app/app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ActiveRecord::Base 2 | has_many :emails 3 | 4 | devise :multi_email_authenticatable, :multi_email_confirmable, :lockable, :recoverable, :registerable, 5 | :rememberable, :timeoutable, :trackable, :multi_email_validatable 6 | end 7 | -------------------------------------------------------------------------------- /spec/rails_app/Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require File.expand_path('../config/application', __FILE__) 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | 3 | rvm: 4 | - 2.4 5 | - 2.5 6 | - 2.6 7 | gemfile: 8 | - gemfiles/rails_5_2.gemfile 9 | - gemfiles/rails_5_1.gemfile 10 | - gemfiles/rails_6_0.gemfile 11 | 12 | jobs: 13 | exclude: 14 | - rvm: 2.4 15 | gemfile: gemfiles/rails_6_0.gemfile 16 | 17 | -------------------------------------------------------------------------------- /examples/rails5_app/config/initializers/cookies_serializer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Specify a serializer for the signed and encrypted cookie jars. 4 | # Valid options are :json, :marshal, and :hybrid. 5 | Rails.application.config.action_dispatch.cookies_serializer = :json 6 | -------------------------------------------------------------------------------- /examples/rails5_app/app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /examples/rails5_app/test/test_helper.rb: -------------------------------------------------------------------------------- 1 | ENV['RAILS_ENV'] ||= 'test' 2 | require File.expand_path('../../config/environment', __FILE__) 3 | require 'rails/test_help' 4 | 5 | class ActiveSupport::TestCase 6 | # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. 7 | fixtures :all 8 | 9 | # Add more helper methods to be used by all tests here... 10 | end 11 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require "bundler/setup" 4 | require "devise/multi_email" 5 | 6 | # You can add fixtures and/or initialization code here to make experimenting 7 | # with your gem easier. You can also use a different console, if you like. 8 | 9 | # (If you use this, don't forget to add pry to your Gemfile!) 10 | # require "pry" 11 | # Pry.start 12 | 13 | require "irb" 14 | IRB.start 15 | -------------------------------------------------------------------------------- /examples/rails5_app/db/seeds.rb: -------------------------------------------------------------------------------- 1 | # This file should contain all the record creation needed to seed the database with its default values. 2 | # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). 3 | # 4 | # Examples: 5 | # 6 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) 7 | # Character.create(name: 'Luke', movie: movies.first) 8 | -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | ENV['RAILS_ENV'] = 'test' 2 | 3 | require 'spec_helper' 4 | require 'capybara/rspec' 5 | require 'rails_app/config/environment' 6 | require 'orm/active_record' 7 | 8 | Capybara.app = RailsApp::Application 9 | 10 | RSpec.configure do |config| 11 | config.include RailsApp::Application.routes.url_helpers 12 | end 13 | 14 | Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } 15 | -------------------------------------------------------------------------------- /examples/rails5_app/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Rails5App 5 | <%= csrf_meta_tags %> 6 | 7 | <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> 8 | <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> 9 | 10 | 11 | 12 | <%= yield %> 13 | 14 | 15 | -------------------------------------------------------------------------------- /lib/devise/multi_email/email_model_manager.rb: -------------------------------------------------------------------------------- 1 | require 'devise/multi_email/email_model_extensions' 2 | 3 | module Devise 4 | module MultiEmail 5 | class EmailModelManager 6 | 7 | def initialize(email_record) 8 | @email_record = email_record 9 | end 10 | 11 | def parent 12 | @email_record.__send__(@email_record.class.multi_email_association.name) 13 | end 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /examples/rails5_app/app/assets/javascripts/cable.js: -------------------------------------------------------------------------------- 1 | // Action Cable provides the framework to deal with WebSockets in Rails. 2 | // You can generate new channels where WebSocket features live using the rails generate channel command. 3 | // 4 | //= require action_cable 5 | //= require_self 6 | //= require_tree ./channels 7 | 8 | (function() { 9 | this.App || (this.App = {}); 10 | 11 | App.cable = ActionCable.createConsumer(); 12 | 13 | }).call(this); 14 | -------------------------------------------------------------------------------- /spec/rails_app/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /examples/rails5_app/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /spec/rails_app/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | # Filters added to this controller apply to all controllers in the application. 2 | # Likewise, all the methods added will be available for all controllers. 3 | 4 | class ApplicationController < ActionController::Base 5 | protect_from_forgery 6 | before_action :current_user, unless: :devise_controller? 7 | before_action :authenticate_user!, if: :devise_controller? 8 | respond_to *Mime::SET.map(&:to_sym) 9 | end 10 | 11 | -------------------------------------------------------------------------------- /examples/rails5_app/app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ApplicationRecord 2 | has_many :emails 3 | # Include default devise modules. Others available are: 4 | # :lockable, :timeoutable and :omniauthable 5 | devise :multi_email_authenticatable, :multi_email_confirmable, :multi_email_validatable, 6 | :recoverable, :registerable, :rememberable, :trackable, 7 | # Below are for testing purpose, not required by default 8 | :encryptable, encryptor: :sha512 9 | end 10 | -------------------------------------------------------------------------------- /examples/rails5_app/README.md: -------------------------------------------------------------------------------- 1 | # README 2 | 3 | This README would normally document whatever steps are necessary to get the 4 | application up and running. 5 | 6 | Things you may want to cover: 7 | 8 | * Ruby version 9 | 10 | * System dependencies 11 | 12 | * Configuration 13 | 14 | * Database creation 15 | 16 | * Database initialization 17 | 18 | * How to run the test suite 19 | 20 | * Services (job queues, cache servers, search engines, etc.) 21 | 22 | * Deployment instructions 23 | 24 | * ... 25 | -------------------------------------------------------------------------------- /examples/rails5_app/config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Version of your assets, change this if you want to expire all your assets. 4 | Rails.application.config.assets.version = '1.0' 5 | 6 | # Add additional assets to the asset load path 7 | # Rails.application.config.assets.paths << Emoji.images_path 8 | 9 | # Precompile additional assets. 10 | # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. 11 | # Rails.application.config.assets.precompile += %w( search.js ) 12 | -------------------------------------------------------------------------------- /spec/orm/active_record.rb: -------------------------------------------------------------------------------- 1 | ActiveRecord::Migration.verbose = false 2 | 3 | migration_path = File.expand_path('../../rails_app/db/migrate/', __FILE__) 4 | # https://github.com/plataformatec/devise/blob/master/test/orm/active_record.rb 5 | # Run any available migration 6 | if Rails.version.start_with? '6' 7 | ActiveRecord::MigrationContext.new(migration_path, ActiveRecord::SchemaMigration).migrate 8 | elsif Rails.version.start_with? '5.2' 9 | ActiveRecord::MigrationContext.new(migration_path).migrate 10 | else 11 | ActiveRecord::Migrator.migrate(migration_path) 12 | end 13 | -------------------------------------------------------------------------------- /spec/rails_app/config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite version 3.x 2 | # gem install sqlite3-ruby (not necessary on OS X Leopard) 3 | development: 4 | adapter: sqlite3 5 | database: db/development.sqlite3 6 | pool: 5 7 | timeout: 5000 8 | 9 | # Warning: The database defined as "test" will be erased and 10 | # re-generated from your development database when you run "rake". 11 | # Do not set this db to the same as development or production. 12 | test: 13 | adapter: sqlite3 14 | database: ":memory:" 15 | 16 | production: 17 | adapter: sqlite3 18 | database: ":memory:" 19 | -------------------------------------------------------------------------------- /examples/rails5_app/config/application.rb: -------------------------------------------------------------------------------- 1 | require_relative 'boot' 2 | 3 | require 'rails/all' 4 | 5 | # Require the gems listed in Gemfile, including any gems 6 | # you've limited to :test, :development, or :production. 7 | Bundler.require(*Rails.groups) 8 | 9 | module Rails5App 10 | class Application < Rails::Application 11 | # Settings in config/environments/* take precedence over those specified here. 12 | # Application configuration should go into files in config/initializers 13 | # -- all .rb files in that directory are automatically loaded. 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /examples/rails5_app/config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /lib/devise/multi_email/email_model_extensions.rb: -------------------------------------------------------------------------------- 1 | require 'devise/multi_email/association_manager' 2 | require 'devise/multi_email/email_model_manager' 3 | 4 | module Devise 5 | module MultiEmail 6 | module EmailModelExtensions 7 | extend ActiveSupport::Concern 8 | 9 | def multi_email 10 | @multi_email ||= EmailModelManager.new(self) 11 | end 12 | 13 | module ClassMethods 14 | def multi_email_association 15 | @multi_email ||= AssociationManager.new(self, Devise::MultiEmail.parent_association_name) 16 | end 17 | end 18 | end 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /spec/rails_app/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | Devise Multi Email Test App 6 | 7 | 8 |
9 | <%- flash.each do |name, msg| -%> 10 | <%= content_tag :div, msg, id: "flash_#{name}" %> 11 | <%- end -%> 12 | 13 | <% if user_signed_in? -%> 14 |

Hello User <%= current_user.email %>! You are signed in!

15 | <% end -%> 16 | 17 | <%= yield %> 18 |
19 | 20 | 21 | -------------------------------------------------------------------------------- /examples/rails5_app/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore the default SQLite database. 11 | /db/*.sqlite3 12 | /db/*.sqlite3-journal 13 | 14 | # Ignore all logfiles and tempfiles. 15 | /log/* 16 | /tmp/* 17 | !/log/.keep 18 | !/tmp/.keep 19 | 20 | # Ignore Byebug command history file. 21 | .byebug_history 22 | -------------------------------------------------------------------------------- /examples/rails5_app/config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite version 3.x 2 | # gem install sqlite3 3 | # 4 | # Ensure the SQLite 3 gem is defined in your Gemfile 5 | # gem 'sqlite3' 6 | # 7 | default: &default 8 | adapter: sqlite3 9 | pool: 5 10 | timeout: 5000 11 | 12 | development: 13 | <<: *default 14 | database: db/development.sqlite3 15 | 16 | # Warning: The database defined as "test" will be erased and 17 | # re-generated from your development database when you run "rake". 18 | # Do not set this db to the same as development or production. 19 | test: 20 | <<: *default 21 | database: db/test.sqlite3 22 | 23 | production: 24 | <<: *default 25 | database: db/production.sqlite3 26 | -------------------------------------------------------------------------------- /examples/rails5_app/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /examples/rails5_app/config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # To learn more, please read the Rails Internationalization guide 20 | # available at http://guides.rubyonrails.org/i18n.html. 21 | 22 | en: 23 | hello: "Hello world" 24 | -------------------------------------------------------------------------------- /spec/features/validatable_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'Validatable', type: :feature do 4 | before { visit new_user_session_path } 5 | 6 | describe 'User Sign Up' do 7 | it 'shows the error message when inputs are not valid' do 8 | click_link 'Sign up' 9 | expect(page).to have_selector('div', text: '(7 characters minimum)') 10 | 11 | fill_in 'user_email', with: '@test.com' 12 | fill_in 'user_password', with: 'lol' 13 | fill_in 'user_password_confirmation', with: 'lol' 14 | click_button 'Sign up' 15 | 16 | expect(page).to have_selector('div', text: 'Email is invalid') 17 | expect(page).to have_selector('div', text: 'Password is too short (minimum is 7 characters)') 18 | end 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /examples/rails5_app/app/assets/stylesheets/application.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a manifest file that'll be compiled into application.css, which will include all the files 3 | * listed below. 4 | * 5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, 6 | * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. 7 | * 8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the 9 | * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS 10 | * files in this directory. Styles in this file should be added after the last require_* statement. 11 | * It is generally better to create a new file per style scope. 12 | * 13 | *= require_tree . 14 | *= require_self 15 | */ 16 | -------------------------------------------------------------------------------- /spec/rails_app/public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

The change you wanted was rejected.

23 |

Maybe you tried to change something you didn't have access to.

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /examples/rails5_app/app/assets/javascripts/application.js: -------------------------------------------------------------------------------- 1 | // This is a manifest file that'll be compiled into application.js, which will include all the files 2 | // listed below. 3 | // 4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, 5 | // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. 6 | // 7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 8 | // compiled file. JavaScript code in this file should be added after the last require_* statement. 9 | // 10 | // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details 11 | // about supported directives. 12 | // 13 | //= require jquery 14 | //= require jquery_ujs 15 | //= require turbolinks 16 | //= require_tree . 17 | -------------------------------------------------------------------------------- /spec/rails_app/public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

The page you were looking for doesn't exist.

23 |

You may have mistyped the address or the page may have moved.

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/rails_app/public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

We're sorry, but something went wrong.

23 |

We've been notified about this issue and we'll take a look at it shortly.

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /examples/rails5_app/bin/update: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'pathname' 3 | require 'fileutils' 4 | include FileUtils 5 | 6 | # path to your application root. 7 | APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) 8 | 9 | def system!(*args) 10 | system(*args) || abort("\n== Command #{args} failed ==") 11 | end 12 | 13 | chdir APP_ROOT do 14 | # This script is a way to update your development environment automatically. 15 | # Add necessary update steps to this file. 16 | 17 | puts '== Installing dependencies ==' 18 | system! 'gem install bundler --conservative' 19 | system('bundle check') || system!('bundle install') 20 | 21 | puts "\n== Updating database ==" 22 | system! 'bin/rails db:migrate' 23 | 24 | puts "\n== Removing old logs and tempfiles ==" 25 | system! 'bin/rails log:clear tmp:clear' 26 | 27 | puts "\n== Restarting application server ==" 28 | system! 'bin/rails restart' 29 | end 30 | -------------------------------------------------------------------------------- /spec/features/registerable_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'Registerable', type: :feature do 4 | before { visit new_user_session_path } 5 | 6 | describe 'User Sign Up' do 7 | it 'creates an account which is blocked by confirmation' do 8 | click_link 'Sign up' 9 | 10 | fill_in 'user_email', with: 'new_user@test.com' 11 | fill_in 'user_password', with: 'new_user123' 12 | fill_in 'user_password_confirmation', with: 'new_user123' 13 | expect { click_button 'Sign up' }.to change(ActionMailer::Base.deliveries, :count).by(1) 14 | 15 | expect(page).to have_selector('div', text: 'A message with a confirmation link has been sent to your email address. Please follow the link to activate your account.') 16 | 17 | user = User.last 18 | expect(user.email).to eq 'new_user@test.com' 19 | expect(user).not_to be_confirmed 20 | end 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /lib/devise/multi_email/parent_model_extensions.rb: -------------------------------------------------------------------------------- 1 | require 'devise/multi_email/email_model_extensions' 2 | require 'devise/multi_email/association_manager' 3 | require 'devise/multi_email/parent_model_manager' 4 | 5 | module Devise 6 | module MultiEmail 7 | module ParentModelExtensions 8 | extend ActiveSupport::Concern 9 | 10 | included do 11 | multi_email_association.configure_autosave! 12 | multi_email_association.include_module(EmailModelExtensions) 13 | end 14 | 15 | delegate Devise::MultiEmail.primary_email_method_name, to: :multi_email, allow_nil: false 16 | 17 | def multi_email 18 | @multi_email ||= ParentModelManager.new(self) 19 | end 20 | 21 | module ClassMethods 22 | def multi_email_association 23 | @multi_email ||= AssociationManager.new(self, Devise::MultiEmail.emails_association_name) 24 | end 25 | end 26 | end 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /examples/rails5_app/config/secrets.yml: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key is used for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rails secret` to generate a secure secret key. 9 | 10 | # Make sure the secrets in this file are kept private 11 | # if you're sharing your code publicly. 12 | 13 | development: 14 | secret_key_base: e12d93ce7de5aafe0eb35ef3b91171d8879174c7ee582e725d2c5793ae675978ec395a7285157b0a669b529b15eb333adf4cc088f7e4831dd5a9dbe5ae58ddd9 15 | 16 | test: 17 | secret_key_base: df1df12152839d4a1e777add2cf15954fd80f7116eeb777cce98edeffadaea22136a0cdc8f3a6a4aad847d601ae1ac0dda120f62d74c01338a9ca17cb90e1d4b 18 | 19 | # Do not keep production secrets in the repository, 20 | # instead read values from the environment. 21 | production: 22 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 23 | -------------------------------------------------------------------------------- /examples/rails5_app/bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'pathname' 3 | require 'fileutils' 4 | include FileUtils 5 | 6 | # path to your application root. 7 | APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) 8 | 9 | def system!(*args) 10 | system(*args) || abort("\n== Command #{args} failed ==") 11 | end 12 | 13 | chdir APP_ROOT do 14 | # This script is a starting point to setup your application. 15 | # Add necessary setup steps to this file. 16 | 17 | puts '== Installing dependencies ==' 18 | system! 'gem install bundler --conservative' 19 | system('bundle check') || system!('bundle install') 20 | 21 | # puts "\n== Copying sample files ==" 22 | # unless File.exist?('config/database.yml') 23 | # cp 'config/database.yml.sample', 'config/database.yml' 24 | # end 25 | 26 | puts "\n== Preparing database ==" 27 | system! 'bin/rails db:setup' 28 | 29 | puts "\n== Removing old logs and tempfiles ==" 30 | system! 'bin/rails log:clear tmp:clear' 31 | 32 | puts "\n== Restarting application server ==" 33 | system! 'bin/rails restart' 34 | end 35 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 WANG QIANG 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /examples/rails5_app/config/initializers/new_framework_defaults.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | # 3 | # This file contains migration options to ease your Rails 5.0 upgrade. 4 | # 5 | # Read the Guide for Upgrading Ruby on Rails for more info on each option. 6 | 7 | # Enable per-form CSRF tokens. Previous versions had false. 8 | Rails.application.config.action_controller.per_form_csrf_tokens = true 9 | 10 | # Enable origin-checking CSRF mitigation. Previous versions had false. 11 | Rails.application.config.action_controller.forgery_protection_origin_check = true 12 | 13 | # Make Ruby 2.4 preserve the timezone of the receiver when calling `to_time`. 14 | # Previous versions had false. 15 | ActiveSupport.to_time_preserves_timezone = true 16 | 17 | # Require `belongs_to` associations by default. Previous versions had false. 18 | Rails.application.config.active_record.belongs_to_required_by_default = true 19 | 20 | # Do not halt callback chains when a callback returns false. Previous versions had true. 21 | ActiveSupport.halt_callback_chains_on_return_false = false 22 | 23 | # Configure SSL options to enable HSTS with subdomains. Previous versions had false. 24 | Rails.application.config.ssl_options = { hsts: { subdomains: true } } 25 | -------------------------------------------------------------------------------- /spec/rails_app/config/application.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../boot', __FILE__) 2 | 3 | require 'action_controller/railtie' 4 | require 'action_mailer/railtie' 5 | require 'active_record/railtie' 6 | require 'rails/test_unit/railtie' 7 | 8 | require 'devise/multi_email' 9 | 10 | module RailsApp 11 | class Application < Rails::Application 12 | # Add additional load paths for your own custom dirs 13 | config.autoload_paths.reject! { |p| p =~ /\/app\/(\w+)$/ && !%w(controllers helpers mailers models views).include?($1) } 14 | 15 | # Configure generators values. Many other options are available, be sure to check the documentation. 16 | # config.generators do |g| 17 | # g.orm :active_record 18 | # g.template_engine :erb 19 | # g.test_framework :test_unit, fixture: true 20 | # end 21 | 22 | # Configure sensitive parameters which will be filtered from the log file. 23 | config.filter_parameters << :password 24 | # config.assets.enabled = false 25 | 26 | config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } 27 | 28 | # This was used to break devise in some situations 29 | config.to_prepare do 30 | Devise::SessionsController.layout 'application' 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /spec/rails_app/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | RailsApp::Application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports and disable caching. 13 | config.consider_all_requests_local = true 14 | config.action_controller.perform_caching = false 15 | 16 | # Don't care if the mailer can't send. 17 | config.action_mailer.raise_delivery_errors = false 18 | 19 | # Print deprecation notices to the Rails logger. 20 | config.active_support.deprecation = :log 21 | 22 | # Only use best-standards-support built into browsers. 23 | config.action_dispatch.best_standards_support = :builtin 24 | 25 | # Raise an error on page load if there are pending migrations 26 | config.active_record.migration_error = :page_load 27 | 28 | # Debug mode disables concatenation and preprocessing of assets. 29 | config.assets.debug = true 30 | end 31 | -------------------------------------------------------------------------------- /lib/devise/multi_email/association_manager.rb: -------------------------------------------------------------------------------- 1 | 2 | module Devise 3 | module MultiEmail 4 | class AssociationManager 5 | 6 | attr_reader :name 7 | 8 | def initialize(klass, association_name) 9 | @klass = klass 10 | @name = association_name 11 | end 12 | 13 | def include_module(mod) 14 | model_class.__send__ :include, mod 15 | end 16 | 17 | # Specify a block with alternative behavior which should be 18 | # run when `autosave` is not enabled. 19 | def configure_autosave!(&block) 20 | unless autosave_enabled? 21 | if Devise::MultiEmail.autosave_emails? 22 | reflection.autosave = true 23 | else 24 | yield if block_given? 25 | end 26 | end 27 | end 28 | 29 | def autosave_enabled? 30 | reflection.options[:autosave] == true 31 | end 32 | 33 | def model_class 34 | @model_class ||= reflection.class_name.constantize 35 | end 36 | 37 | def reflection 38 | @reflection ||= @klass.reflect_on_association(name) || 39 | raise("#{@klass}##{name} association not found: It might be because your declaration is after `devise :multi_email_confirmable`.") 40 | end 41 | end 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /devise-multi_email.gemspec: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | lib = File.expand_path('../lib', __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require 'devise/multi_email/version' 5 | 6 | Gem::Specification.new do |spec| 7 | spec.name = 'devise-multi_email' 8 | spec.version = Devise::MultiEmail::VERSION 9 | spec.authors = ['ALLEN WANG QIANG', 'Joel Van Horn'] 10 | spec.email = ['rovingbreeze@gmail.com', 'joel@joelvanhorn.com'] 11 | 12 | spec.summary = %q{Let devise support multiple emails.} 13 | spec.description = %q{Devise authenticatable, confirmable and validatable with multiple emails.} 14 | spec.homepage = 'https://github.com/allenwq/devise-multi_email.git' 15 | spec.license = 'MIT' 16 | 17 | spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } 18 | spec.bindir = 'exe' 19 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } 20 | spec.require_paths = ['lib'] 21 | 22 | spec.add_runtime_dependency 'devise' 23 | 24 | spec.add_development_dependency 'bundler' 25 | spec.add_development_dependency 'rake', '~> 10.0' 26 | spec.add_development_dependency 'rspec' 27 | spec.add_development_dependency 'sqlite3' 28 | spec.add_development_dependency 'capybara' 29 | spec.add_development_dependency 'coveralls' 30 | end 31 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. 4 | 5 | We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion. 6 | 7 | Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. 8 | 9 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. 10 | 11 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. 12 | 13 | This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/) 14 | -------------------------------------------------------------------------------- /spec/rails_app/db/migrate/20160101102949_create_tables.rb: -------------------------------------------------------------------------------- 1 | BASE_CLASS = Rails::VERSION::MAJOR >= 5 ? ActiveRecord::Migration[4.2] : ActiveRecord::Migration 2 | 3 | class CreateTables < BASE_CLASS 4 | def change 5 | create_table :users do |t| 6 | t.string :username 7 | 8 | ## Database authenticatable 9 | t.string :encrypted_password, null: false, default: '' 10 | 11 | ## Recoverable 12 | t.string :reset_password_token 13 | t.datetime :reset_password_sent_at 14 | 15 | ## Rememberable 16 | t.datetime :remember_created_at 17 | 18 | ## Trackable 19 | t.integer :sign_in_count, default: 0 20 | t.datetime :current_sign_in_at 21 | t.datetime :last_sign_in_at 22 | t.string :current_sign_in_ip 23 | t.string :last_sign_in_ip 24 | 25 | ## Lockable 26 | t.integer :failed_attempts, default: 0 # Only if lock strategy is :failed_attempts 27 | t.string :unlock_token # Only if unlock strategy is :email or :both 28 | t.datetime :locked_at 29 | 30 | t.timestamps null: false 31 | end 32 | 33 | create_table :emails do |t| 34 | t.integer :user_id, null: false 35 | t.string :email, null: false 36 | t.boolean :primary, default: false, null: true 37 | 38 | ## Confirmable 39 | t.string :confirmation_token 40 | t.datetime :confirmed_at 41 | t.datetime :confirmation_sent_at 42 | t.string :unconfirmed_email 43 | 44 | t.timestamps null: false 45 | end 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /examples/rails5_app/db/migrate/20170307140813_devise_create_users.rb: -------------------------------------------------------------------------------- 1 | class DeviseCreateUsers < ActiveRecord::Migration[5.0] 2 | def change 3 | create_table :users do |t| 4 | ## Database authenticatable 5 | t.string :encrypted_password, null: false, default: "" 6 | 7 | ## Recoverable 8 | t.string :reset_password_token 9 | t.datetime :reset_password_sent_at 10 | 11 | ## Rememberable 12 | t.datetime :remember_created_at 13 | 14 | ## Trackable 15 | t.integer :sign_in_count, default: 0, null: false 16 | t.datetime :current_sign_in_at 17 | t.datetime :last_sign_in_at 18 | t.string :current_sign_in_ip 19 | t.string :last_sign_in_ip 20 | 21 | ## Lockable 22 | # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts 23 | # t.string :unlock_token # Only if unlock strategy is :email or :both 24 | # t.datetime :locked_at 25 | 26 | 27 | t.timestamps null: false 28 | end 29 | 30 | add_index :users, :reset_password_token, unique: true 31 | # add_index :users, :unlock_token, unique: true 32 | 33 | create_table :user_emails do |t| 34 | t.integer :user_id, null: false 35 | t.string :email, null: false 36 | t.string :unconfirmed_email 37 | t.boolean :primary, default: false 38 | 39 | ## Confirmable 40 | t.string :confirmation_token 41 | t.datetime :confirmed_at 42 | t.datetime :confirmation_sent_at 43 | 44 | t.timestamps null: false 45 | end 46 | 47 | add_index :user_emails, :confirmation_token, unique: true 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /spec/support/features.rb: -------------------------------------------------------------------------------- 1 | module RailsTestHelpers 2 | def generate_email 3 | "user_#{SecureRandom.hex}@test.com" 4 | end 5 | 6 | def create_user(options={}) 7 | user = User.create!( 8 | username: 'usertest', 9 | email: options[:email] || generate_email, 10 | password: options[:password] || '12345678', 11 | password_confirmation: options[:password] || '12345678', 12 | created_at: Time.now.utc 13 | ) 14 | user.primary_email_record.update_attribute(:confirmation_sent_at, options[:confirmation_sent_at]) if options[:confirmation_sent_at] 15 | user.confirm unless options[:confirm] == false 16 | user 17 | end 18 | 19 | def create_email(user, options = {}) 20 | email_address = options[:email] || generate_email 21 | user.multi_email.find_or_build_for_email(email_address) 22 | 23 | email = user.emails.to_a.find { |record| record.email == email_address } 24 | email.update_attribute(:confirmation_sent_at, options[:confirmation_sent_at]) if options[:confirmation_sent_at] 25 | 26 | if options[:confirm] == false 27 | user.save 28 | else 29 | email.confirm 30 | end 31 | 32 | email 33 | end 34 | 35 | def sign_in_as_user(options={}, &block) 36 | user = create_user(options) 37 | visit_with_option options[:visit], new_user_session_path 38 | fill_in 'email', with: options[:email] || 'user@test.com' 39 | fill_in 'password', with: options[:password] || '12345678' 40 | check 'remember me' if options[:remember_me] == true 41 | yield if block_given? 42 | click_button 'Log In' 43 | user 44 | end 45 | end 46 | 47 | RSpec.configure do |config| 48 | config.include RailsTestHelpers 49 | end 50 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ### Unreleased 2 | * Fix ActiveModel::Errors#keys deprecation in Rails 6.1 3 | 4 | ### 3.0.0 - 2019-11-06 5 | * Deprecate the support of Rails 4 (although it might still work) 6 | * Fix warnings in Rails 6 7 | 8 | ### 2.0.1 - 2017-05-16 9 | 10 | * Refactored to simplify some logic and start moving toward mimicking default Devise lifecycle behavior 11 | * Added `Devise::MultiEmail.only_login_with_primary_email` option to restrict login to only primary emails 12 | * Added `Devise::MultiEmail.autosave_emails` option to automatically enable `autosave` on "emails" association 13 | 14 | ### 2.0.0 - 2017-05-12 15 | 16 | * New `Devise::MultiEmail#configure` setup with options for `user` and `emails` associations and `primary_email_record` method names 17 | * Refactor to expose `_multi_email_*` prefixed methods on models 18 | * Changed logic when changing an email address to look up existing email record, otherwise creating a new one, then marking it "primary" 19 | * Changed logic when changing an email address to mark all others as `primary = false` 20 | * Changed logic when changing an email address to `nil` to mark as `primary = false` rather than deleting records 21 | 22 | Many thanks to [joelvh](https://github.com/joelvh) for the great work! 23 | 24 | ### 1.0.5 - 2016-12-29 25 | 26 | * New `.find_by_email` method. Thanks to [mrjlynch](https://github.com/mrjlynch). 27 | 28 | ### 1.0.4 - 2016-08-13 29 | 30 | * Bug fix: Case-insentive configuration of email is ignored (#1). Thanks to [@fonglh](https://github.com/fonglh). 31 | 32 | ### 1.0.3 - 2016-02-18 33 | 34 | * Bug fix: Fix a wrong error message which shows "Email can't be blank" when email does not exist. 35 | 36 | ### 1.0.2 - 2016-01-12 37 | 38 | First stable release. 39 | -------------------------------------------------------------------------------- /examples/rails5_app/public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

If you are the application owner check the logs for more information.

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /lib/devise/multi_email.rb: -------------------------------------------------------------------------------- 1 | require 'devise/multi_email/version' 2 | require 'devise' 3 | 4 | module Devise 5 | module MultiEmail 6 | class << self 7 | def configure(&block) 8 | yield self 9 | end 10 | 11 | @autosave_emails = false 12 | 13 | def autosave_emails? 14 | @autosave_emails == true 15 | end 16 | 17 | def autosave_emails=(value) 18 | @autosave_emails = (value == true) 19 | end 20 | 21 | @only_login_with_primary_email = false 22 | 23 | def only_login_with_primary_email? 24 | @only_login_with_primary_email == true 25 | end 26 | 27 | def only_login_with_primary_email=(value) 28 | @only_login_with_primary_email = (value == true) 29 | end 30 | 31 | def parent_association_name 32 | @parent_association_name ||= :user 33 | end 34 | 35 | def parent_association_name=(name) 36 | @parent_association_name = name.try(:to_sym) 37 | end 38 | 39 | def emails_association_name 40 | @emails_association_name ||= :emails 41 | end 42 | 43 | def emails_association_name=(name) 44 | @emails_association_name = name.try(:to_sym) 45 | end 46 | 47 | def primary_email_method_name 48 | @primary_email_method_name ||= :primary_email_record 49 | end 50 | 51 | def primary_email_method_name=(name) 52 | @primary_email_method_name = name.try(:to_sym) 53 | end 54 | end 55 | end 56 | end 57 | 58 | Devise.add_module :multi_email_authenticatable, model: 'devise/multi_email/models/authenticatable' 59 | Devise.add_module :multi_email_confirmable, model: 'devise/multi_email/models/confirmable' 60 | Devise.add_module :multi_email_validatable, model: 'devise/multi_email/models/validatable' 61 | -------------------------------------------------------------------------------- /examples/rails5_app/public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

Maybe you tried to change something you didn't have access to.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /examples/rails5_app/public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

You may have mistyped the address or the page may have moved.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /examples/rails5_app/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure public file server for tests with Cache-Control for performance. 16 | config.public_file_server.enabled = true 17 | config.public_file_server.headers = { 18 | 'Cache-Control' => 'public, max-age=3600' 19 | } 20 | 21 | # Show full error reports and disable caching. 22 | config.consider_all_requests_local = true 23 | config.action_controller.perform_caching = false 24 | 25 | # Raise exceptions instead of rendering exception templates. 26 | config.action_dispatch.show_exceptions = false 27 | 28 | # Disable request forgery protection in test environment. 29 | config.action_controller.allow_forgery_protection = false 30 | config.action_mailer.perform_caching = false 31 | 32 | # Tell Action Mailer not to deliver emails to the real world. 33 | # The :test delivery method accumulates sent emails in the 34 | # ActionMailer::Base.deliveries array. 35 | config.action_mailer.delivery_method = :test 36 | 37 | # Print deprecation notices to the stderr. 38 | config.active_support.deprecation = :stderr 39 | 40 | # Raises error for missing translations 41 | # config.action_view.raise_on_missing_translations = true 42 | end 43 | -------------------------------------------------------------------------------- /spec/models/parent_model_manager_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe Devise::MultiEmail::ParentModelManager, type: :model do 4 | subject(:user) { create_user } 5 | 6 | let(:new_email) { generate_email } 7 | 8 | describe 'multi_email API' do 9 | describe '#current_email_record' do 10 | it 'returns the primary email if not logged in' do 11 | expect(user.multi_email.current_email_record).to be user.primary_email_record 12 | end 13 | end 14 | 15 | describe '#change_primary_email_to' do 16 | it 'un-sets primary email if given nil' do 17 | expect(user.primary_email_record).not_to be_nil 18 | user.multi_email.change_primary_email_to(nil) 19 | expect(user.primary_email_record).to be_nil 20 | end 21 | 22 | it 'changes primary email to a new one when allow_unconfirmed is true' do 23 | user.multi_email.change_primary_email_to(new_email, allow_unconfirmed: true) 24 | expect(user.primary_email_record.email).to eq(new_email) 25 | expect(user.primary_email_record.confirmed?).to eq(false) 26 | expect(user.primary_email_record.confirmed?).to eq(false) 27 | end 28 | 29 | it 'changes primary email and confirms it if allow_unconfirmed & skip_confirmations are true' do 30 | user.multi_email.change_primary_email_to(new_email, allow_unconfirmed: true, skip_confirmations: true) 31 | expect(user.primary_email_record.email).to eq(new_email) 32 | expect(user.primary_email_record.confirmed?).to eq(true) 33 | end 34 | end 35 | 36 | describe '#(un)confirmed_emails' do 37 | it 'works correctly' do 38 | new_email_record = user.multi_email.find_or_build_for_email(new_email) 39 | expect(user.multi_email.unconfirmed_emails).to include(new_email_record) 40 | new_email_record.confirm 41 | expect(user.multi_email.confirmed_emails).to include(new_email_record) 42 | end 43 | end 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /examples/rails5_app/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | git_source(:github) do |repo_name| 4 | repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") 5 | "https://github.com/#{repo_name}.git" 6 | end 7 | 8 | 9 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' 10 | gem 'rails', '~> 5.0.2' 11 | # Use sqlite3 as the database for Active Record 12 | gem 'sqlite3' 13 | # Use Puma as the app server 14 | gem 'puma', '~> 3.0' 15 | # Use SCSS for stylesheets 16 | gem 'sass-rails', '~> 5.0' 17 | # Use Uglifier as compressor for JavaScript assets 18 | gem 'uglifier', '>= 1.3.0' 19 | # See https://github.com/rails/execjs#readme for more supported runtimes 20 | # gem 'therubyracer', platforms: :ruby 21 | 22 | # Use jquery as the JavaScript library 23 | gem 'jquery-rails' 24 | # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks 25 | gem 'turbolinks', '~> 5' 26 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 27 | gem 'jbuilder', '~> 2.5' 28 | # Use Redis adapter to run Action Cable in production 29 | # gem 'redis', '~> 3.0' 30 | # Use ActiveModel has_secure_password 31 | # gem 'bcrypt', '~> 3.1.7' 32 | 33 | # Use Capistrano for deployment 34 | # gem 'capistrano-rails', group: :development 35 | 36 | group :development, :test do 37 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 38 | gem 'byebug', platform: :mri 39 | end 40 | 41 | group :development do 42 | # Access an IRB console on exception pages or by using <%= console %> anywhere in the code. 43 | gem 'web-console', '>= 3.3.0' 44 | gem 'listen', '~> 3.0.5' 45 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 46 | gem 'spring' 47 | gem 'spring-watcher-listen', '~> 2.0.0' 48 | end 49 | 50 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 51 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 52 | 53 | gem 'devise' 54 | gem 'devise-multi_email' 55 | gem 'devise-encryptable' 56 | -------------------------------------------------------------------------------- /examples/rails5_app/config/puma.rb: -------------------------------------------------------------------------------- 1 | # Puma can serve each request in a thread from an internal thread pool. 2 | # The `threads` method setting takes two numbers a minimum and maximum. 3 | # Any libraries that use thread pools should be configured to match 4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 5 | # and maximum, this matches the default thread size of Active Record. 6 | # 7 | threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i 8 | threads threads_count, threads_count 9 | 10 | # Specifies the `port` that Puma will listen on to receive requests, default is 3000. 11 | # 12 | port ENV.fetch("PORT") { 3000 } 13 | 14 | # Specifies the `environment` that Puma will run in. 15 | # 16 | environment ENV.fetch("RAILS_ENV") { "development" } 17 | 18 | # Specifies the number of `workers` to boot in clustered mode. 19 | # Workers are forked webserver processes. If using threads and workers together 20 | # the concurrency of the application would be max `threads` * `workers`. 21 | # Workers do not work on JRuby or Windows (both of which do not support 22 | # processes). 23 | # 24 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 25 | 26 | # Use the `preload_app!` method when specifying a `workers` number. 27 | # This directive tells Puma to first boot the application and load code 28 | # before forking the application. This takes advantage of Copy On Write 29 | # process behavior so workers use less memory. If you use this option 30 | # you need to make sure to reconnect any threads in the `on_worker_boot` 31 | # block. 32 | # 33 | # preload_app! 34 | 35 | # The code in the `on_worker_boot` will be called if you are using 36 | # clustered mode by specifying a number of `workers`. After each worker 37 | # process is booted this block will be run, if you are using `preload_app!` 38 | # option you will want to use this block to reconnect to any threads 39 | # or connections that may have been created at application boot, Ruby 40 | # cannot share connections between processes. 41 | # 42 | # on_worker_boot do 43 | # ActiveRecord::Base.establish_connection if defined?(ActiveRecord) 44 | # end 45 | 46 | # Allow puma to be restarted by `rails restart` command. 47 | plugin :tmp_restart 48 | -------------------------------------------------------------------------------- /spec/rails_app/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | RailsApp::Application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Disable serving static files from the `/public` folder by default since 16 | # Apache or NGINX already handles this. 17 | if Rails.version >= '4.2.0' 18 | config.serve_static_files = true 19 | else 20 | config.serve_static_assets = true 21 | end 22 | 23 | if Rails.version >= '5.0.0' 24 | config.public_file_server.headers = {'Cache-Control' => 'public, max-age=3600'} 25 | else 26 | config.static_cache_control = 'public, max-age=3600' 27 | end 28 | 29 | if Rails.version >= '5.2.0' && Rails.version < '6.0' 30 | config.active_record.sqlite3.represent_boolean_as_integer = true 31 | end 32 | 33 | # Show full error reports and disable caching. 34 | config.consider_all_requests_local = true 35 | config.action_controller.perform_caching = false 36 | 37 | # Raise exceptions instead of rendering exception templates. 38 | config.action_dispatch.show_exceptions = false 39 | 40 | # Disable request forgery protection in test environment. 41 | config.action_controller.allow_forgery_protection = false 42 | 43 | # Tell Action Mailer not to deliver emails to the real world. 44 | # The :test delivery method accumulates sent emails in the 45 | # ActionMailer::Base.deliveries array. 46 | config.action_mailer.delivery_method = :test 47 | 48 | # Print deprecation notices to the stderr. 49 | config.active_support.deprecation = :stderr 50 | 51 | config.active_support.test_order = :random 52 | end 53 | -------------------------------------------------------------------------------- /examples/rails5_app/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports. 13 | config.consider_all_requests_local = true 14 | 15 | # Enable/disable caching. By default caching is disabled. 16 | if Rails.root.join('tmp/caching-dev.txt').exist? 17 | config.action_controller.perform_caching = true 18 | 19 | config.cache_store = :memory_store 20 | config.public_file_server.headers = { 21 | 'Cache-Control' => 'public, max-age=172800' 22 | } 23 | else 24 | config.action_controller.perform_caching = false 25 | 26 | config.cache_store = :null_store 27 | end 28 | 29 | # Don't care if the mailer can't send. 30 | config.action_mailer.raise_delivery_errors = false 31 | 32 | config.action_mailer.perform_caching = false 33 | 34 | # Print deprecation notices to the Rails logger. 35 | config.active_support.deprecation = :log 36 | 37 | # Raise an error on page load if there are pending migrations. 38 | config.active_record.migration_error = :page_load 39 | 40 | # Debug mode disables concatenation and preprocessing of assets. 41 | # This option may cause significant delays in view rendering with a large 42 | # number of complex assets. 43 | config.assets.debug = true 44 | 45 | # Suppress logger output for asset requests. 46 | config.assets.quiet = true 47 | 48 | # Raises error for missing translations 49 | # config.action_view.raise_on_missing_translations = true 50 | 51 | # Use an evented file watcher to asynchronously detect changes in source code, 52 | # routes, locales, etc. This feature depends on the listen gem. 53 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 54 | 55 | config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } 56 | end 57 | -------------------------------------------------------------------------------- /spec/rails_app/db/schema.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # This file is auto-generated from the current state of the database. Instead 3 | # of editing this file, please use the migrations feature of Active Record to 4 | # incrementally modify your database, and then regenerate this schema definition. 5 | # 6 | # Note that this schema.rb definition is the authoritative source for your 7 | # database schema. If you need to create the application database on another 8 | # system, you should be using db:schema:load, not running all the migrations 9 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 10 | # you'll amass, the slower it'll run and the greater likelihood for issues). 11 | # 12 | # It's strongly recommended that you check this file into your version control system. 13 | ActiveRecord::Base.establish_connection 14 | 15 | ActiveRecord::Schema.define(version: 20160101102949) do 16 | 17 | create_table "emails", force: :cascade do |t| 18 | t.integer "user_id", null: false 19 | t.string "email", null: false 20 | t.boolean "primary", default: false 21 | t.string "confirmation_token" 22 | t.datetime "confirmed_at" 23 | t.datetime "confirmation_sent_at" 24 | t.string "unconfirmed_email" 25 | t.datetime "created_at", null: false 26 | t.datetime "updated_at", null: false 27 | end 28 | 29 | create_table "users", force: :cascade do |t| 30 | t.string "username" 31 | t.string "encrypted_password", default: "", null: false 32 | t.string "reset_password_token" 33 | t.datetime "reset_password_sent_at" 34 | t.datetime "remember_created_at" 35 | t.integer "sign_in_count", default: 0 36 | t.datetime "current_sign_in_at" 37 | t.datetime "last_sign_in_at" 38 | t.string "current_sign_in_ip" 39 | t.string "last_sign_in_ip" 40 | t.integer "failed_attempts", default: 0 41 | t.string "unlock_token" 42 | t.datetime "locked_at" 43 | t.datetime "created_at", null: false 44 | t.datetime "updated_at", null: false 45 | end 46 | 47 | end 48 | -------------------------------------------------------------------------------- /examples/rails5_app/db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # Note that this schema.rb definition is the authoritative source for your 6 | # database schema. If you need to create the application database on another 7 | # system, you should be using db:schema:load, not running all the migrations 8 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 9 | # you'll amass, the slower it'll run and the greater likelihood for issues). 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 20170307145547) do 14 | 15 | create_table "user_emails", force: :cascade do |t| 16 | t.integer "user_id", null: false 17 | t.string "email", null: false 18 | t.string "unconfirmed_email" 19 | t.boolean "primary", default: false 20 | t.string "confirmation_token" 21 | t.datetime "confirmed_at" 22 | t.datetime "confirmation_sent_at" 23 | t.datetime "created_at", null: false 24 | t.datetime "updated_at", null: false 25 | t.index ["confirmation_token"], name: "index_emails_on_confirmation_token", unique: true 26 | end 27 | 28 | create_table "users", force: :cascade do |t| 29 | t.string "encrypted_password", default: "", null: false 30 | t.string "reset_password_token" 31 | t.datetime "reset_password_sent_at" 32 | t.datetime "remember_created_at" 33 | t.integer "sign_in_count", default: 0, null: false 34 | t.datetime "current_sign_in_at" 35 | t.datetime "last_sign_in_at" 36 | t.string "current_sign_in_ip" 37 | t.string "last_sign_in_ip" 38 | t.datetime "created_at", null: false 39 | t.datetime "updated_at", null: false 40 | t.string "password_salt" 41 | t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 42 | end 43 | 44 | end 45 | -------------------------------------------------------------------------------- /lib/devise/multi_email/parent_model_manager.rb: -------------------------------------------------------------------------------- 1 | require 'devise/multi_email/email_model_extensions' 2 | 3 | module Devise 4 | module MultiEmail 5 | class ParentModelManager 6 | 7 | def initialize(parent_record) 8 | @parent_record = parent_record 9 | end 10 | 11 | def current_email_record 12 | login_email_record || primary_email_record 13 | end 14 | 15 | def login_email_record 16 | if @parent_record.current_login_email.present? 17 | formatted_email = format_email(@parent_record.current_login_email) 18 | filtered_emails.find { |item| item.email == formatted_email } 19 | end 20 | end 21 | 22 | # Gets the primary email record. 23 | def primary_email_record 24 | filtered_emails.find(&:primary?) 25 | end 26 | alias_method Devise::MultiEmail.primary_email_method_name, :primary_email_record 27 | 28 | # :allow_unconfirmed option sets this email record to primary 29 | # :skip_confirmations option confirms this email record (without saving) 30 | # @see `set_primary_record_to` 31 | def change_primary_email_to(new_email, options = {}) 32 | # mark none as primary when set to nil 33 | if new_email.nil? 34 | filtered_emails.each { |item| item.primary = false } 35 | 36 | # select or build an email record 37 | else 38 | record = find_or_build_for_email(new_email) 39 | 40 | if record.try(:confirmed?) || primary_email_record.nil? || options[:allow_unconfirmed] 41 | set_primary_record_to(record, options) 42 | end 43 | end 44 | 45 | record 46 | end 47 | 48 | # Use Devise formatting settings for emails 49 | def format_email(email) 50 | @parent_record.class.__send__(:devise_parameter_filter).filter(email: email)[:email] 51 | end 52 | 53 | def find_or_build_for_email(email) 54 | formatted_email = format_email(email) 55 | record = filtered_emails.find { |item| item.email == formatted_email } 56 | record || emails.build(email: formatted_email) 57 | end 58 | 59 | def emails 60 | @parent_record.__send__(@parent_record.class.multi_email_association.name) 61 | end 62 | 63 | # Gets the email records that have not been deleted 64 | def filtered_emails(options = {}) 65 | emails.to_a.reject(&:destroyed?).reject(&:marked_for_destruction?) 66 | end 67 | 68 | def confirmed_emails 69 | filtered_emails.select { |record| record.try(:confirmed?) } 70 | end 71 | 72 | def unconfirmed_emails 73 | filtered_emails.reject { |record| record.try(:confirmed?) } 74 | end 75 | 76 | protected 77 | 78 | # :skip_confirmations option confirms this email record (without saving) 79 | def set_primary_record_to(record, options = {}) 80 | # Toggle primary flag for all emails 81 | filtered_emails.each { |other| other.primary = (other.email == record.email) } 82 | 83 | if options[:skip_confirmations] 84 | record.try(:skip_confirmation!) 85 | record.try(:skip_reconfirmation!) 86 | end 87 | end 88 | end 89 | end 90 | end 91 | -------------------------------------------------------------------------------- /spec/features/authenticatable_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'Authenticatable', type: :feature do 4 | describe 'User sign in' do 5 | context 'with primary email' do 6 | it 'signs the user in' do 7 | user = create_user 8 | visit new_user_session_path 9 | 10 | fill_in 'user_email', with: user.email 11 | fill_in 'user_password', with: '12345678' 12 | click_button 'Log in' 13 | 14 | expect(current_path).to eq root_path 15 | expect(page).to have_selector('div', text: 'Signed in successfully.') 16 | end 17 | end 18 | 19 | context 'with non-primary email' do 20 | before do 21 | Devise::MultiEmail.only_login_with_primary_email = false 22 | end 23 | after do 24 | Devise::MultiEmail.only_login_with_primary_email = false 25 | end 26 | 27 | it 'signs the user in when allowed to sign in with non-primary email' do 28 | user = create_user 29 | secondary_email = create_email(user) 30 | visit new_user_session_path 31 | 32 | fill_in 'user_email', with: secondary_email.email 33 | fill_in 'user_password', with: '12345678' 34 | click_button 'Log in' 35 | 36 | expect(current_path).to eq root_path 37 | expect(page).to have_selector('div', text: 'Signed in successfully.') 38 | end 39 | 40 | it 'does not sign the user in when not allowed to sign in with non-primary email' do 41 | Devise::MultiEmail.only_login_with_primary_email = true 42 | 43 | user = create_user 44 | secondary_email = create_email(user) 45 | visit new_user_session_path 46 | 47 | fill_in 'user_email', with: secondary_email.email 48 | fill_in 'user_password', with: '12345678' 49 | click_button 'Log in' 50 | 51 | expect(current_path).to eq new_user_session_path 52 | expect(page).to have_selector('div', text: 'Invalid Email or password.') 53 | end 54 | end 55 | 56 | context 'with upper case email' do 57 | it 'signs the user in' do 58 | user = create_user 59 | visit new_user_session_path 60 | 61 | fill_in 'user_email', with: user.email.upcase! 62 | fill_in 'user_password', with: '12345678' 63 | click_button 'Log in' 64 | 65 | expect(current_path).to eq root_path 66 | expect(page).to have_selector('div', text: 'Signed in successfully.') 67 | end 68 | end 69 | end 70 | 71 | describe 'User Has Multiple Emails' do 72 | context 'when changing primary email' do 73 | it 'toggles and persists primary value for all emails' do 74 | user = create_user 75 | second_email = create_email(user) 76 | third_email = create_email(user) 77 | 78 | user.save 79 | 80 | expect(user.errors.size).to eq 0 81 | expect(user.emails.all?(&:persisted?)).to eq true 82 | expect(user.emails.any?(&:changed?)).to eq false 83 | 84 | user.email = second_email.email 85 | user.email = third_email.email 86 | 87 | expect(user.emails.select(&:primary?).size).to eq 1 88 | 89 | user.save 90 | user.reload 91 | user.emails.reload 92 | 93 | expect(user.emails.select(&:primary?).size).to eq 1 94 | expect(user.multi_email.primary_email_record.email).to eq third_email.email 95 | end 96 | end 97 | end 98 | end 99 | -------------------------------------------------------------------------------- /lib/devise/multi_email/models/authenticatable.rb: -------------------------------------------------------------------------------- 1 | require 'devise/multi_email/parent_model_extensions' 2 | 3 | module Devise 4 | module Models 5 | module EmailAuthenticatable 6 | def devise_scope 7 | self.class.multi_email_association.model_class 8 | end 9 | end 10 | 11 | module MultiEmailAuthenticatable 12 | extend ActiveSupport::Concern 13 | 14 | included do 15 | include Devise::MultiEmail::ParentModelExtensions 16 | 17 | attr_accessor :current_login_email 18 | 19 | devise :database_authenticatable 20 | 21 | include AuthenticatableExtensions 22 | end 23 | 24 | def self.required_fields(klass) 25 | [] 26 | end 27 | 28 | module AuthenticatableExtensions 29 | extend ActiveSupport::Concern 30 | 31 | included do 32 | multi_email_association.configure_autosave!{ include AuthenticatableAutosaveExtensions } 33 | multi_email_association.include_module(EmailAuthenticatable) 34 | end 35 | 36 | delegate :skip_confirmation!, to: Devise::MultiEmail.primary_email_method_name, allow_nil: false 37 | 38 | # Gets the primary email address of the user. 39 | def email 40 | multi_email.primary_email_record.try(:email) 41 | end 42 | 43 | # Sets the default email address of the user. 44 | def email=(new_email) 45 | multi_email.change_primary_email_to(new_email, allow_unconfirmed: true) 46 | end 47 | end 48 | 49 | module AuthenticatableAutosaveExtensions 50 | extend ActiveSupport::Concern 51 | 52 | included do 53 | # Toggle `primary` value for all emails if `autosave` is not on 54 | after_save do 55 | multi_email.filtered_emails.each do |email| 56 | # update value in database without persisting any other changes 57 | email.save if email.changes.key?(:primary) 58 | end 59 | end 60 | end 61 | end 62 | 63 | module ClassMethods 64 | def find_first_by_auth_conditions(tainted_conditions, opts = {}) 65 | filtered_conditions = devise_parameter_filter.filter(tainted_conditions.dup) 66 | criteria = filtered_conditions.extract!(:email, :unconfirmed_email) 67 | 68 | if criteria.keys.any? 69 | conditions = filtered_conditions.to_h.merge(opts). 70 | reverse_merge(build_conditions(criteria)) 71 | 72 | resource = joins(multi_email_association.name).find_by(conditions) 73 | resource.current_login_email = criteria.values.first if resource 74 | resource 75 | else 76 | super(tainted_conditions, opts) 77 | end 78 | end 79 | 80 | def find_by_email(email) 81 | joins(multi_email_association.name).where(build_conditions email: email).first 82 | end 83 | 84 | def build_conditions(criteria) 85 | criteria = devise_parameter_filter.filter(criteria) 86 | # match the primary email record if the `unconfirmed_email` column is specified 87 | if Devise::MultiEmail.only_login_with_primary_email? || criteria[:unconfirmed_email] 88 | criteria.merge!(primary: true) 89 | end 90 | 91 | { multi_email_association.reflection.table_name.to_sym => criteria } 92 | end 93 | end 94 | end 95 | end 96 | end 97 | -------------------------------------------------------------------------------- /spec/rails_app/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | RailsApp::Application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both thread web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Enable Rack::Cache to put a simple HTTP cache in front of your application 18 | # Add `rack-cache` to your Gemfile before enabling this. 19 | # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. 20 | # config.action_dispatch.rack_cache = true 21 | 22 | # Disable Rails's static asset server (Apache or nginx will already do this). 23 | if Rails.version >= "4.2.0" 24 | config.serve_static_files = false 25 | else 26 | config.serve_static_assets = false 27 | end 28 | 29 | # Compress JavaScripts and CSS. 30 | config.assets.js_compressor = :uglifier 31 | # config.assets.css_compressor = :sass 32 | 33 | # Whether to fallback to assets pipeline if a precompiled asset is missed. 34 | config.assets.compile = false 35 | 36 | # Generate digests for assets URLs. 37 | config.assets.digest = true 38 | 39 | # Version of your assets, change this if you want to expire all your assets. 40 | config.assets.version = '1.0' 41 | 42 | # Specifies the header that your server uses for sending files. 43 | # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache 44 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx 45 | 46 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 47 | # config.force_ssl = true 48 | 49 | # Set to :debug to see everything in the log. 50 | config.log_level = :info 51 | 52 | # Prepend all log lines with the following tags. 53 | # config.log_tags = [:subdomain, :uuid] 54 | 55 | # Use a different logger for distributed setups. 56 | # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) 57 | 58 | # Use a different cache store in production. 59 | # config.cache_store = :mem_cache_store 60 | 61 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 62 | # config.action_controller.asset_host = "http://assets.example.com" 63 | 64 | # Precompile additional assets. 65 | # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. 66 | # config.assets.precompile += %w( search.js ) 67 | 68 | # Ignore bad email addresses and do not raise email delivery errors. 69 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 70 | # config.action_mailer.raise_delivery_errors = false 71 | 72 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 73 | # the I18n.default_locale when a translation can not be found). 74 | config.i18n.fallbacks = true 75 | 76 | # Send deprecation notices to registered listeners. 77 | config.active_support.deprecation = :notify 78 | 79 | # Disable automatic flushing of the log to improve performance. 80 | # config.autoflush_log = false 81 | 82 | # Use default logging formatter so that PID and timestamp are not suppressed. 83 | config.log_formatter = ::Logger::Formatter.new 84 | end 85 | -------------------------------------------------------------------------------- /spec/multi_email_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'Devise Multi Email' do 4 | describe '.required_fields' do 5 | it 'does not raise any errors' do 6 | expect { Devise::Models.check_fields!(User) }.to_not raise_error 7 | expect { Devise::Models.check_fields!(Email) }.to_not raise_error 8 | end 9 | end 10 | 11 | describe 'Authenticatable' do 12 | context 'when emails association is not detected' do 13 | it 'raises an error' do 14 | expect do 15 | class UserWithoutEmail < ActiveRecord::Base 16 | self.table_name = 'users' 17 | 18 | devise :multi_email_authenticatable 19 | end 20 | end.to raise_error(RuntimeError) 21 | end 22 | end 23 | 24 | context 'when user association is not detected' do 25 | it 'raises an error' do 26 | expect do 27 | class EmailWithoutUser < ActiveRecord::Base 28 | self.table_name = 'emails' 29 | end 30 | 31 | class UserWithEmails < ActiveRecord::Base 32 | self.table_name = 'users' 33 | 34 | has_many :emails, class_name: EmailWithoutUser.name 35 | devise :multi_email_authenticatable 36 | end 37 | 38 | EmailWithoutUser.new.devise_scope 39 | end.to raise_error(RuntimeError) 40 | end 41 | end 42 | 43 | describe '#email=' do 44 | let(:user) { create_user } 45 | 46 | it 'creates a new Email' do 47 | expect(user.emails.length).to eq(1) 48 | expect(user.emails[0]).to be_primary 49 | end 50 | 51 | it 'deletes the only email address when assigning nil' do 52 | user.email = nil 53 | expect(user.email).to eq(nil) 54 | end 55 | end 56 | 57 | describe '.find_by_email()' do 58 | let(:user) { create_user } 59 | 60 | it 'returns user from email' do 61 | expect(User.find_by_email(user.email)).to eq(user) 62 | end 63 | end 64 | 65 | describe '#skip_confirmation!' do 66 | context 'on the user object' do 67 | let(:user) { create_user(confirm: false) } 68 | 69 | it 'confirms user' do 70 | expect{user.skip_confirmation!}.to change{user.confirmed?}.from(false).to(true) 71 | end 72 | end 73 | 74 | context 'on the email object' do 75 | let(:user) { create_user(confirm: false) } 76 | let(:primary_email_record) { user.primary_email_record } 77 | 78 | it 'confirms user' do 79 | expect{primary_email_record.skip_confirmation!}.to change{user.confirmed?}.from(false).to(true) 80 | end 81 | end 82 | end 83 | end 84 | 85 | describe 'Validatable' do 86 | context 'when email is a nested attribute' do 87 | class UserWithNestedAttributes < ActiveRecord::Base 88 | self.table_name = 'users' 89 | has_many :emails, foreign_key: :user_id 90 | 91 | devise :multi_email_authenticatable, :multi_email_validatable 92 | 93 | accepts_nested_attributes_for :emails 94 | end 95 | 96 | it 'propagates the errors to user' do 97 | user = UserWithNestedAttributes.new(username: 'user', email: 'inavlid_email@') 98 | expect(user).not_to be_valid 99 | expect(user.errors[:email]).to be_present 100 | expect(user.errors.details[:email].first[:error]).to eq(:invalid) if user.errors.respond_to?(:details) 101 | end 102 | end 103 | end 104 | 105 | describe 'the gem itself' do 106 | it 'presents a VERSION' do 107 | expect(Devise::MultiEmail::VERSION).to be_a(String) 108 | end 109 | end 110 | end 111 | -------------------------------------------------------------------------------- /lib/devise/multi_email/models/confirmable.rb: -------------------------------------------------------------------------------- 1 | require 'devise/multi_email/parent_model_extensions' 2 | 3 | module Devise 4 | module Models 5 | module EmailConfirmable 6 | extend ActiveSupport::Concern 7 | 8 | included do 9 | devise :confirmable 10 | 11 | include ConfirmableExtensions 12 | end 13 | 14 | module ConfirmableExtensions 15 | def confirmation_period_valid? 16 | primary? ? super : false 17 | end 18 | end 19 | end 20 | 21 | module MultiEmailConfirmable 22 | extend ActiveSupport::Concern 23 | 24 | included do 25 | include Devise::MultiEmail::ParentModelExtensions 26 | 27 | devise :confirmable 28 | 29 | include ConfirmableExtensions 30 | end 31 | 32 | def self.required_fields(klass) 33 | [] 34 | end 35 | 36 | module ConfirmableExtensions 37 | extend ActiveSupport::Concern 38 | 39 | included do 40 | multi_email_association.include_module(EmailConfirmable) 41 | end 42 | 43 | # delegate before creating overriding methods 44 | delegate :skip_confirmation!, :skip_confirmation_notification!, :skip_reconfirmation!, :confirmation_required?, 45 | :confirmation_token, :confirmed_at, :confirmed_at=, :confirmation_sent_at, :confirm, :confirmed?, :unconfirmed_email, 46 | :reconfirmation_required?, :pending_reconfirmation?, to: Devise::MultiEmail.primary_email_method_name, allow_nil: true 47 | 48 | # In case email updates are being postponed, don't change anything 49 | # when the postpone feature tries to switch things back 50 | def email=(new_email) 51 | multi_email.change_primary_email_to(new_email, allow_unconfirmed: unconfirmed_access_possible?) 52 | end 53 | 54 | # This need to be forwarded to the email that the user logged in with 55 | def active_for_authentication? 56 | login_email = multi_email.login_email_record 57 | 58 | if login_email && !login_email.primary? 59 | super && login_email.active_for_authentication? 60 | else 61 | super 62 | end 63 | end 64 | 65 | # Shows email not confirmed instead of account inactive when the email that user used to login is not confirmed 66 | def inactive_message 67 | login_email = multi_email.login_email_record 68 | 69 | if login_email && !login_email.primary? && !login_email.confirmed? 70 | :unconfirmed 71 | else 72 | super 73 | end 74 | end 75 | 76 | protected 77 | 78 | # Overrides Devise::Models::Confirmable#postpone_email_change? 79 | def postpone_email_change? 80 | false 81 | end 82 | 83 | # Email should handle the confirmation token. 84 | def generate_confirmation_token 85 | end 86 | 87 | # Email will send reconfirmation instructions. 88 | def send_reconfirmation_instructions 89 | end 90 | 91 | # Email will send confirmation instructions. 92 | def send_on_create_confirmation_instructions 93 | end 94 | 95 | private 96 | 97 | def unconfirmed_access_possible? 98 | Devise.allow_unconfirmed_access_for.nil? || \ 99 | Devise.allow_unconfirmed_access_for > 0.days 100 | end 101 | 102 | module ClassMethods 103 | delegate :confirm_by_token, :send_confirmation_instructions, to: 'multi_email_association.model_class', allow_nil: false 104 | end 105 | end 106 | end 107 | end 108 | end 109 | -------------------------------------------------------------------------------- /spec/features/recoverable_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'Recoverable', type: :feature do 4 | def visit_new_password_path 5 | visit new_user_session_path 6 | click_link 'Forgot your password?' 7 | end 8 | 9 | def request_forgot_password(&block) 10 | visit_new_password_path 11 | 12 | fill_in 'user_email', with: 'user@test.com' 13 | yield if block_given? 14 | 15 | click_button 'Send me reset password instructions' 16 | end 17 | 18 | context 'with primary email' do 19 | it 'sends the password reset email' do 20 | user = create_user 21 | visit_new_password_path 22 | 23 | request_forgot_password do 24 | fill_in 'user_email', with: user.email 25 | end 26 | 27 | expect(current_path).to eq new_user_session_path 28 | expect(page).to have_selector('div', text: 'You will receive an email with instructions on how to reset your password in a few minutes.') 29 | end 30 | 31 | context 'when not confirmed' do 32 | it 'shows the error message' do 33 | user = create_user(confirm: false) 34 | visit_new_password_path 35 | 36 | request_forgot_password do 37 | fill_in 'user_email', with: user.email 38 | end 39 | 40 | expect(current_path).to eq new_user_session_path 41 | expect(page).to have_selector('div', text: 'You will receive an email with instructions on how to reset your password in a few minutes.') 42 | end 43 | end 44 | end 45 | 46 | context 'with non-primary email' do 47 | context 'when confirmed' do 48 | before do 49 | user = create_user 50 | secondary_email = create_email(user) 51 | visit_new_password_path 52 | 53 | request_forgot_password do 54 | fill_in 'user_email', with: secondary_email.email 55 | end 56 | end 57 | 58 | it 'sends the password reset email' do 59 | expect(current_path).to eq new_user_session_path 60 | expect(page).to have_selector('div', text: 'You will receive an email with instructions on how to reset your password in a few minutes.') 61 | end 62 | 63 | it 'redirects to password reset page when visiting the link' do 64 | link = ActionMailer::Base.deliveries.last.body.to_s.scan(/]*href="([^"]*)"/x)[0][0] 65 | visit link 66 | 67 | fill_in 'user_password', with: 'abcdefgh' 68 | fill_in 'user_password_confirmation', with: 'abcdefgh' 69 | click_button 'Change my password' 70 | 71 | expect(page).to have_selector('div', text: 'Your password has been changed successfully. You are now signed in.') 72 | end 73 | end 74 | 75 | context 'when not confirmed' do 76 | it 'shows the error message' do 77 | user = create_user 78 | secondary_email = create_email(user, confirm: false) 79 | visit_new_password_path 80 | 81 | request_forgot_password do 82 | fill_in 'user_email', with: secondary_email.email 83 | end 84 | 85 | expect(current_path).to eq new_user_session_path 86 | expect(page).to have_selector('div', text: 'You will receive an email with instructions on how to reset your password in a few minutes.') 87 | end 88 | end 89 | end 90 | 91 | context 'with non-existing email' do 92 | before do 93 | visit_new_password_path 94 | 95 | request_forgot_password do 96 | fill_in 'user_email', with: "#{SecureRandom.base64}@example.com" 97 | end 98 | end 99 | 100 | it 'shows email does not exist' do 101 | expect(current_path).to eq '/users/password' 102 | expect(page).to have_selector('div', text: 'Email not found') 103 | end 104 | end 105 | end 106 | -------------------------------------------------------------------------------- /examples/rails5_app/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Disable serving static files from the `/public` folder by default since 18 | # Apache or NGINX already handles this. 19 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 20 | 21 | # Compress JavaScripts and CSS. 22 | config.assets.js_compressor = :uglifier 23 | # config.assets.css_compressor = :sass 24 | 25 | # Do not fallback to assets pipeline if a precompiled asset is missed. 26 | config.assets.compile = false 27 | 28 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb 29 | 30 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 31 | # config.action_controller.asset_host = 'http://assets.example.com' 32 | 33 | # Specifies the header that your server uses for sending files. 34 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 35 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 36 | 37 | # Mount Action Cable outside main process or domain 38 | # config.action_cable.mount_path = nil 39 | # config.action_cable.url = 'wss://example.com/cable' 40 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] 41 | 42 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 43 | # config.force_ssl = true 44 | 45 | # Use the lowest log level to ensure availability of diagnostic information 46 | # when problems arise. 47 | config.log_level = :debug 48 | 49 | # Prepend all log lines with the following tags. 50 | config.log_tags = [ :request_id ] 51 | 52 | # Use a different cache store in production. 53 | # config.cache_store = :mem_cache_store 54 | 55 | # Use a real queuing backend for Active Job (and separate queues per environment) 56 | # config.active_job.queue_adapter = :resque 57 | # config.active_job.queue_name_prefix = "rails5_app_#{Rails.env}" 58 | config.action_mailer.perform_caching = false 59 | 60 | # Ignore bad email addresses and do not raise email delivery errors. 61 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 62 | # config.action_mailer.raise_delivery_errors = false 63 | 64 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 65 | # the I18n.default_locale when a translation cannot be found). 66 | config.i18n.fallbacks = true 67 | 68 | # Send deprecation notices to registered listeners. 69 | config.active_support.deprecation = :notify 70 | 71 | # Use default logging formatter so that PID and timestamp are not suppressed. 72 | config.log_formatter = ::Logger::Formatter.new 73 | 74 | # Use a different logger for distributed setups. 75 | # require 'syslog/logger' 76 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 77 | 78 | if ENV["RAILS_LOG_TO_STDOUT"].present? 79 | logger = ActiveSupport::Logger.new(STDOUT) 80 | logger.formatter = config.log_formatter 81 | config.logger = ActiveSupport::TaggedLogging.new(logger) 82 | end 83 | 84 | # Do not dump schema after migrations. 85 | config.active_record.dump_schema_after_migration = false 86 | end 87 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | require 'simplecov' 2 | SimpleCov.start do 3 | add_filter 'spec/' 4 | end 5 | 6 | if ENV['CI'] 7 | require 'coveralls' 8 | Coveralls.wear! 9 | end 10 | 11 | RSpec.configure do |config| 12 | # rspec-expectations config goes here. You can use an alternate 13 | # assertion/expectation library such as wrong or the stdlib/minitest 14 | # assertions if you prefer. 15 | config.expect_with :rspec do |expectations| 16 | # This option will default to `true` in RSpec 4. It makes the `description` 17 | # and `failure_message` of custom matchers include text for helper methods 18 | # defined using `chain`, e.g.: 19 | # be_bigger_than(2).and_smaller_than(4).description 20 | # # => "be bigger than 2 and smaller than 4" 21 | # ...rather than: 22 | # # => "be bigger than 2" 23 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 24 | end 25 | 26 | # rspec-mocks config goes here. You can use an alternate test double 27 | # library (such as bogus or mocha) by changing the `mock_with` option here. 28 | config.mock_with :rspec do |mocks| 29 | # Prevents you from mocking or stubbing a method that does not exist on 30 | # a real object. This is generally recommended, and will default to 31 | # `true` in RSpec 4. 32 | mocks.verify_partial_doubles = true 33 | end 34 | 35 | # The settings below are suggested to provide a good initial experience 36 | # with RSpec, but feel free to customize to your heart's content. 37 | # These two settings work together to allow you to limit a spec run 38 | # to individual examples or groups you care about by tagging them with 39 | # `:focus` metadata. When nothing is tagged with `:focus`, all examples 40 | # get run. 41 | config.filter_run :focus 42 | config.run_all_when_everything_filtered = true 43 | 44 | # Allows RSpec to persist some state between runs in order to support 45 | # the `--only-failures` and `--next-failure` CLI options. We recommend 46 | # you configure your source control system to ignore this file. 47 | config.example_status_persistence_file_path = 'tmp/examples.txt' 48 | 49 | # Limits the available syntax to the non-monkey patched syntax that is 50 | # recommended. For more details, see: 51 | # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ 52 | # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 53 | # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode 54 | config.disable_monkey_patching! 55 | 56 | # This setting enables warnings. It's recommended, but in some cases may 57 | # be too noisy due to issues in dependencies. 58 | # config.warnings = true 59 | 60 | # Many RSpec users commonly either run the entire suite or an individual 61 | # file, and it's useful to allow more verbose output when running an 62 | # individual spec file. 63 | if config.files_to_run.one? 64 | # Use the documentation formatter for detailed output, 65 | # unless a formatter has already been configured 66 | # (e.g. via a command-line flag). 67 | config.default_formatter = 'doc' 68 | end 69 | 70 | # Print the 10 slowest examples and example groups at the 71 | # end of the spec run, to help surface which specs are running 72 | # particularly slow. 73 | # config.profile_examples = 10 74 | 75 | # Run specs in random order to surface order dependencies. If you find an 76 | # order dependency and want to debug it, you can fix the order by providing 77 | # the seed, which is printed after each run. 78 | # --seed 1234 79 | config.order = :random 80 | 81 | # Seed global randomization in this process using the `--seed` CLI option. 82 | # Setting this allows you to use `--seed` to deterministically reproduce 83 | # test failures related to randomization by passing the same `--seed` value 84 | # as the one that triggered the failure. 85 | Kernel.srand config.seed 86 | end 87 | -------------------------------------------------------------------------------- /lib/devise/multi_email/models/validatable.rb: -------------------------------------------------------------------------------- 1 | require 'devise/multi_email/parent_model_extensions' 2 | 3 | module Devise 4 | module Models 5 | module EmailValidatable 6 | extend ActiveSupport::Concern 7 | 8 | included do 9 | validates_presence_of :email, if: :email_required? 10 | if Devise.activerecord51? 11 | validates_uniqueness_of :email, allow_blank: true, case_sensitive: true, if: :will_save_change_to_email? 12 | validates_format_of :email, with: email_regexp, allow_blank: true, if: :will_save_change_to_email? 13 | else 14 | validates_uniqueness_of :email, allow_blank: true, if: :email_changed? 15 | validates_format_of :email, with: email_regexp, allow_blank: true, if: :email_changed? 16 | end 17 | end 18 | 19 | def email_required? 20 | true 21 | end 22 | 23 | module ClassMethods 24 | Devise::Models.config(self, :email_regexp) 25 | end 26 | end 27 | 28 | module MultiEmailValidatable 29 | extend ActiveSupport::Concern 30 | 31 | included do 32 | include Devise::MultiEmail::ParentModelExtensions 33 | 34 | assert_validations_api!(self) 35 | 36 | validates_presence_of :email, if: :email_required? 37 | 38 | validates_presence_of :password, if: :password_required? 39 | validates_confirmation_of :password, if: :password_required? 40 | validates_length_of :password, within: password_length, allow_blank: true 41 | 42 | after_validation :propagate_email_errors 43 | 44 | multi_email_association.include_module(EmailValidatable) 45 | 46 | devise_modules << :validatable 47 | end 48 | 49 | def self.required_fields(klass) 50 | [] 51 | end 52 | 53 | protected 54 | 55 | # Same as Devise::Models::Validatable#password_required? 56 | def password_required? 57 | !persisted? || !password.nil? || !password_confirmation.nil? 58 | end 59 | 60 | # Same as Devise::Models::Validatable#email_required? 61 | def email_required? 62 | true 63 | end 64 | 65 | private 66 | 67 | def propagate_email_errors 68 | association_name = self.class.multi_email_association.name 69 | email_error_key = errors_attribute_names.detect do |key| 70 | [association_name.to_s, "#{association_name}.email"].include?(key.to_s) 71 | end 72 | return unless email_error_key.present? 73 | 74 | email_errors = 75 | if errors.respond_to?(:details) 76 | errors 77 | .details[email_error_key] 78 | .map { |e| e[:error] } 79 | .zip(errors.delete(email_error_key) || []) 80 | else 81 | errors.delete(email_error_key) 82 | end 83 | 84 | email_errors.each do |type, message| 85 | errors.add(:email, type, message: message) 86 | end 87 | end 88 | 89 | def errors_attribute_names 90 | errors.respond_to?(:attribute_names) ? errors.attribute_names : errors.keys 91 | end 92 | 93 | module ClassMethods 94 | 95 | # All validations used by this module. 96 | VALIDATIONS = [:validates_presence_of, :validates_uniqueness_of, :validates_format_of, 97 | :validates_confirmation_of, :validates_length_of].freeze 98 | 99 | def assert_validations_api!(base) #:nodoc: 100 | unavailable_validations = VALIDATIONS.select { |v| !base.respond_to?(v) } 101 | 102 | unless unavailable_validations.empty? 103 | raise "Could not use :validatable module since #{base} does not respond " << 104 | "to the following methods: #{unavailable_validations.to_sentence}." 105 | end 106 | end 107 | 108 | Devise::Models.config(self, :password_length) 109 | end 110 | end 111 | end 112 | end 113 | -------------------------------------------------------------------------------- /examples/rails5_app/config/locales/devise.en.yml: -------------------------------------------------------------------------------- 1 | # Additional translations at https://github.com/plataformatec/devise/wiki/I18n 2 | 3 | en: 4 | devise: 5 | confirmations: 6 | confirmed: "Your email address has been successfully confirmed." 7 | send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." 8 | 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." 9 | failure: 10 | already_authenticated: "You are already signed in." 11 | inactive: "Your account is not activated yet." 12 | invalid: "Invalid %{authentication_keys} or password." 13 | locked: "Your account is locked." 14 | last_attempt: "You have one more attempt before your account is locked." 15 | not_found_in_database: "Invalid %{authentication_keys} or password." 16 | timeout: "Your session expired. Please sign in again to continue." 17 | unauthenticated: "You need to sign in or sign up before continuing." 18 | unconfirmed: "You have to confirm your email address before continuing." 19 | mailer: 20 | confirmation_instructions: 21 | subject: "Confirmation instructions" 22 | reset_password_instructions: 23 | subject: "Reset password instructions" 24 | unlock_instructions: 25 | subject: "Unlock instructions" 26 | password_change: 27 | subject: "Password Changed" 28 | omniauth_callbacks: 29 | failure: "Could not authenticate you from %{kind} because \"%{reason}\"." 30 | success: "Successfully authenticated from %{kind} account." 31 | passwords: 32 | 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." 33 | send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." 34 | 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." 35 | updated: "Your password has been changed successfully. You are now signed in." 36 | updated_not_active: "Your password has been changed successfully." 37 | registrations: 38 | destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." 39 | signed_up: "Welcome! You have signed up successfully." 40 | signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." 41 | signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." 42 | 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." 43 | update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirm link to confirm your new email address." 44 | updated: "Your account has been updated successfully." 45 | sessions: 46 | signed_in: "Signed in successfully." 47 | signed_out: "Signed out successfully." 48 | already_signed_out: "Signed out successfully." 49 | unlocks: 50 | send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." 51 | send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." 52 | unlocked: "Your account has been unlocked successfully. Please sign in to continue." 53 | errors: 54 | messages: 55 | already_confirmed: "was already confirmed, please try signing in" 56 | confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" 57 | expired: "has expired, please request a new one" 58 | not_found: "not found" 59 | not_locked: "was not locked" 60 | not_saved: 61 | one: "1 error prohibited this %{resource} from being saved:" 62 | other: "%{count} errors prohibited this %{resource} from being saved:" 63 | -------------------------------------------------------------------------------- /examples/rails5_app/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (5.0.2) 5 | actionpack (= 5.0.2) 6 | nio4r (>= 1.2, < 3.0) 7 | websocket-driver (~> 0.6.1) 8 | actionmailer (5.0.2) 9 | actionpack (= 5.0.2) 10 | actionview (= 5.0.2) 11 | activejob (= 5.0.2) 12 | mail (~> 2.5, >= 2.5.4) 13 | rails-dom-testing (~> 2.0) 14 | actionpack (5.0.2) 15 | actionview (= 5.0.2) 16 | activesupport (= 5.0.2) 17 | rack (~> 2.0) 18 | rack-test (~> 0.6.3) 19 | rails-dom-testing (~> 2.0) 20 | rails-html-sanitizer (~> 1.0, >= 1.0.2) 21 | actionview (5.0.2) 22 | activesupport (= 5.0.2) 23 | builder (~> 3.1) 24 | erubis (~> 2.7.0) 25 | rails-dom-testing (~> 2.0) 26 | rails-html-sanitizer (~> 1.0, >= 1.0.3) 27 | activejob (5.0.2) 28 | activesupport (= 5.0.2) 29 | globalid (>= 0.3.6) 30 | activemodel (5.0.2) 31 | activesupport (= 5.0.2) 32 | activerecord (5.0.2) 33 | activemodel (= 5.0.2) 34 | activesupport (= 5.0.2) 35 | arel (~> 7.0) 36 | activesupport (5.0.2) 37 | concurrent-ruby (~> 1.0, >= 1.0.2) 38 | i18n (~> 0.7) 39 | minitest (~> 5.1) 40 | tzinfo (~> 1.1) 41 | arel (7.1.4) 42 | bcrypt (3.1.13) 43 | builder (3.2.3) 44 | byebug (9.0.6) 45 | concurrent-ruby (1.1.5) 46 | crass (1.0.5) 47 | debug_inspector (0.0.2) 48 | devise (4.7.1) 49 | bcrypt (~> 3.0) 50 | orm_adapter (~> 0.1) 51 | railties (>= 4.1.0) 52 | responders 53 | warden (~> 1.2.3) 54 | devise-encryptable (0.2.0) 55 | devise (>= 2.1.0) 56 | devise-multi_email (1.0.5) 57 | devise 58 | erubis (2.7.0) 59 | execjs (2.7.0) 60 | ffi (1.11.1) 61 | globalid (0.3.7) 62 | activesupport (>= 4.1.0) 63 | i18n (0.9.5) 64 | concurrent-ruby (~> 1.0) 65 | jbuilder (2.6.3) 66 | activesupport (>= 3.0.0, < 5.2) 67 | multi_json (~> 1.2) 68 | jquery-rails (4.2.2) 69 | rails-dom-testing (>= 1, < 3) 70 | railties (>= 4.2.0) 71 | thor (>= 0.14, < 2.0) 72 | listen (3.0.8) 73 | rb-fsevent (~> 0.9, >= 0.9.4) 74 | rb-inotify (~> 0.9, >= 0.9.7) 75 | loofah (2.3.1) 76 | crass (~> 1.0.2) 77 | nokogiri (>= 1.5.9) 78 | mail (2.6.4) 79 | mime-types (>= 1.16, < 4) 80 | method_source (0.9.2) 81 | mime-types (3.1) 82 | mime-types-data (~> 3.2015) 83 | mime-types-data (3.2016.0521) 84 | mini_portile2 (2.4.0) 85 | minitest (5.12.2) 86 | multi_json (1.12.1) 87 | nio4r (2.0.0) 88 | nokogiri (1.10.5) 89 | mini_portile2 (~> 2.4.0) 90 | orm_adapter (0.5.0) 91 | puma (3.7.1) 92 | rack (2.0.7) 93 | rack-test (0.6.3) 94 | rack (>= 1.0) 95 | rails (5.0.2) 96 | actioncable (= 5.0.2) 97 | actionmailer (= 5.0.2) 98 | actionpack (= 5.0.2) 99 | actionview (= 5.0.2) 100 | activejob (= 5.0.2) 101 | activemodel (= 5.0.2) 102 | activerecord (= 5.0.2) 103 | activesupport (= 5.0.2) 104 | bundler (>= 1.3.0, < 2.0) 105 | railties (= 5.0.2) 106 | sprockets-rails (>= 2.0.0) 107 | rails-dom-testing (2.0.3) 108 | activesupport (>= 4.2.0) 109 | nokogiri (>= 1.6) 110 | rails-html-sanitizer (1.3.0) 111 | loofah (~> 2.3) 112 | railties (5.0.2) 113 | actionpack (= 5.0.2) 114 | activesupport (= 5.0.2) 115 | method_source 116 | rake (>= 0.8.7) 117 | thor (>= 0.18.1, < 2.0) 118 | rake (13.0.0) 119 | rb-fsevent (0.9.8) 120 | rb-inotify (0.9.8) 121 | ffi (>= 0.5.0) 122 | responders (3.0.0) 123 | actionpack (>= 5.0) 124 | railties (>= 5.0) 125 | sass (3.4.23) 126 | sass-rails (5.0.6) 127 | railties (>= 4.0.0, < 6) 128 | sass (~> 3.1) 129 | sprockets (>= 2.8, < 4.0) 130 | sprockets-rails (>= 2.0, < 4.0) 131 | tilt (>= 1.1, < 3) 132 | spring (2.0.1) 133 | activesupport (>= 4.2) 134 | spring-watcher-listen (2.0.1) 135 | listen (>= 2.7, < 4.0) 136 | spring (>= 1.2, < 3.0) 137 | sprockets (3.7.2) 138 | concurrent-ruby (~> 1.0) 139 | rack (> 1, < 3) 140 | sprockets-rails (3.2.0) 141 | actionpack (>= 4.0) 142 | activesupport (>= 4.0) 143 | sprockets (>= 3.0.0) 144 | sqlite3 (1.3.13) 145 | thor (0.20.3) 146 | thread_safe (0.3.6) 147 | tilt (2.0.6) 148 | turbolinks (5.0.1) 149 | turbolinks-source (~> 5) 150 | turbolinks-source (5.0.0) 151 | tzinfo (1.2.5) 152 | thread_safe (~> 0.1) 153 | uglifier (3.1.4) 154 | execjs (>= 0.3.0, < 3) 155 | warden (1.2.8) 156 | rack (>= 2.0.6) 157 | web-console (3.4.0) 158 | actionview (>= 5.0) 159 | activemodel (>= 5.0) 160 | debug_inspector 161 | railties (>= 5.0) 162 | websocket-driver (0.6.5) 163 | websocket-extensions (>= 0.1.0) 164 | websocket-extensions (0.1.2) 165 | 166 | PLATFORMS 167 | ruby 168 | 169 | DEPENDENCIES 170 | byebug 171 | devise 172 | devise-encryptable 173 | devise-multi_email 174 | jbuilder (~> 2.5) 175 | jquery-rails 176 | listen (~> 3.0.5) 177 | puma (~> 3.0) 178 | rails (~> 5.0.2) 179 | sass-rails (~> 5.0) 180 | spring 181 | spring-watcher-listen (~> 2.0.0) 182 | sqlite3 183 | turbolinks (~> 5) 184 | tzinfo-data 185 | uglifier (>= 1.3.0) 186 | web-console (>= 3.3.0) 187 | 188 | BUNDLED WITH 189 | 1.13.6 190 | -------------------------------------------------------------------------------- /spec/features/confirmable_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe 'Confirmable', type: :feature do 4 | def visit_user_confirmation_with_token(confirmation_token) 5 | visit user_confirmation_path(confirmation_token: confirmation_token) 6 | end 7 | 8 | def resend_confirmation 9 | user = create_user(confirm: false) 10 | ActionMailer::Base.deliveries.clear 11 | 12 | visit new_user_session_path 13 | click_link "Didn't receive confirmation instructions?" 14 | 15 | fill_in 'user_email', with: user.email 16 | click_button 'Resend confirmation instructions' 17 | end 18 | 19 | it 'is able to request a new confirmation' do 20 | resend_confirmation 21 | 22 | expect(current_path).to eq '/users/sign_in' 23 | expect(page).to have_selector('div', text: 'You will receive an email with instructions for how to confirm your email address in a few minutes') 24 | expect(ActionMailer::Base.deliveries.size).to eq 1 25 | expect(ActionMailer::Base.deliveries.first.from).to eq ['please-change-me@config-initializers-devise.com'] 26 | end 27 | 28 | it 'is able to confirm the account when confirmation token is valid' do 29 | user = create_user(confirm: false, confirmation_sent_at: 2.days.ago) 30 | expect(user).not_to be_confirmed 31 | visit_user_confirmation_with_token(user.primary_email_record.confirmation_token) 32 | 33 | expect(page).to have_selector('div', text: 'Your email address has been successfully confirmed.') 34 | expect(current_path).to eq '/users/sign_in' 35 | expect(user.reload).to be_confirmed 36 | expect(user.primary_email_record).to be_confirmed 37 | end 38 | 39 | describe '#email=' do 40 | context 'when unconfirmed access is disallowed' do 41 | it 'does not change primary email' do 42 | user = create_user 43 | first_email = user.primary_email_record 44 | user.email = generate_email 45 | 46 | expect(user.primary_email_record.email).to eq(first_email.email) 47 | end 48 | 49 | it 'changes primary email if confirmed' do 50 | user = create_user 51 | new_email = create_email(user, confirm: true) 52 | user.email = new_email.email 53 | 54 | expect(user.primary_email_record.email).to eq(new_email.email) 55 | end 56 | end 57 | 58 | context 'when unconfirmed access is allowed' do 59 | before do 60 | Devise.setup do |config| 61 | config.allow_unconfirmed_access_for = 2.days 62 | end 63 | end 64 | 65 | after do 66 | Devise.setup do |config| 67 | config.allow_unconfirmed_access_for = 0.day 68 | end 69 | end 70 | 71 | it 'changes primary email to the new email' do 72 | user = create_user 73 | new_email = generate_email 74 | user.email = new_email 75 | 76 | expect(user.primary_email_record.email).to eq(new_email) 77 | end 78 | 79 | context 'an unconfirmed access is indefinite' do 80 | before do 81 | Devise.setup do |config| 82 | config.allow_unconfirmed_access_for = nil 83 | end 84 | end 85 | 86 | it 'changes primary email to the new email' do 87 | user = create_user 88 | new_email = generate_email 89 | user.email = new_email 90 | 91 | expect(user.primary_email_record.email).to eq(new_email) 92 | end 93 | end 94 | end 95 | end 96 | 97 | describe 'Unconfirmed sign in' do 98 | context 'with primary email' do 99 | it 'shows the error message' do 100 | user = create_user(confirm: false) 101 | visit new_user_session_path 102 | 103 | fill_in 'user_email', with: user.email 104 | fill_in 'user_password', with: '12345678' 105 | click_button 'Log in' 106 | 107 | expect(current_path).to eq new_user_session_path 108 | expect(page).to have_selector('div#flash_alert', text: 'You have to confirm your email address before continuing.') 109 | end 110 | end 111 | 112 | context 'with non-primary email' do 113 | it 'shows the error message' do 114 | user = create_user 115 | secondary_email = create_email(user, confirm: false) 116 | visit new_user_session_path 117 | 118 | fill_in 'user_email', with: secondary_email.email 119 | fill_in 'user_password', with: '12345678' 120 | click_button 'Log in' 121 | 122 | expect(current_path).to eq new_user_session_path 123 | expect(page).to have_selector('div#flash_alert', text: 'You have to confirm your email address before continuing.') 124 | end 125 | end 126 | 127 | context 'when unconfirmed access is allowed' do 128 | before do 129 | Devise.setup do |config| 130 | config.allow_unconfirmed_access_for = 2.days 131 | end 132 | end 133 | 134 | after do 135 | Devise.setup do |config| 136 | config.allow_unconfirmed_access_for = 0.day 137 | end 138 | end 139 | 140 | context 'with primary email' do 141 | it 'signs the user in' do 142 | user = create_user(confirm: false) 143 | visit new_user_session_path 144 | 145 | fill_in 'user_email', with: user.email 146 | fill_in 'user_password', with: '12345678' 147 | click_button 'Log in' 148 | 149 | expect(current_path).to eq root_path 150 | expect(page).to have_selector('div', text: 'Signed in successfully.') 151 | end 152 | end 153 | 154 | context 'with non-primary email' do 155 | it 'shows the error message' do 156 | user = create_user 157 | secondary_email = create_email(user, confirm: false) 158 | visit new_user_session_path 159 | 160 | fill_in 'user_email', with: secondary_email.email 161 | fill_in 'user_password', with: '12345678' 162 | click_button 'Log in' 163 | 164 | expect(current_path).to eq new_user_session_path 165 | expect(page).to have_selector('div#flash_alert', text: 'You have to confirm your email address before continuing.') 166 | end 167 | end 168 | end 169 | end 170 | end 171 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Devise::MultiEmail [![Build Status](https://travis-ci.org/allenwq/devise-multi_email.svg?branch=master)](https://travis-ci.org/allenwq/devise-multi_email) [![Coverage Status](https://coveralls.io/repos/allenwq/devise-multi_email/badge.svg?branch=master&service=github)](https://coveralls.io/github/allenwq/devise-multi_email?branch=master) 2 | 3 | Letting [Devise](https://github.com/plataformatec/devise) support multiple emails, allows you to: 4 | - Login with multiple emails 5 | - Send confirmations to multiple emails 6 | - Recover the password with any of the emails 7 | - Validations for multiple emails 8 | 9 | `:multi_email_authenticatable`, `:multi_email_confirmable` and `:multi_email_validatable` are provided by _devise-multi_email_. 10 | 11 | ## Getting Started 12 | 13 | Add this line to your application's `Gemfile`: 14 | 15 | ```ruby 16 | gem 'devise-multi_email' 17 | ``` 18 | 19 | Suppose you have already setup Devise, your `User` model might look like this: 20 | 21 | ```ruby 22 | class User < ActiveRecord::Base 23 | devise :database_authenticatable, :registerable 24 | end 25 | ``` 26 | 27 | In order to let your `User` support multiple emails, with _devise-multi_email_ what you need to do is just: 28 | 29 | ```ruby 30 | class User < ActiveRecord::Base 31 | has_many :emails 32 | 33 | # Replace :database_authenticatable, with :multi_email_authenticatable 34 | devise :multi_email_authenticatable, :registerable 35 | end 36 | 37 | class Email < ActiveRecord::Base 38 | belongs_to :user 39 | end 40 | ``` 41 | 42 | Note that the `:email` column should be moved from `users` table to the `emails` table, and a new `primary` boolean column should be added to the `emails` table (so that all the emails will be sent to the primary email, and `user.email` will give you the primary email address). Your `emails` table's migration should look like: 43 | 44 | ```ruby 45 | create_table :emails do |t| 46 | t.integer :user_id 47 | t.string :email 48 | t.boolean :primary 49 | end 50 | ``` 51 | 52 | You can choose whether or not users can login with an email address that is not the primary email address. 53 | 54 | ```ruby 55 | Devise::MultiEmail.configure do |config| 56 | # Default is `false` 57 | config.only_login_with_primary_email = true 58 | end 59 | ``` 60 | 61 | The `autosave` is automatically enabled on the `emails` association by default. This is to ensure the `primary` 62 | flag is persisted for all emails when the primary email is changed. When `autosave` is not enabled on the association, 63 | only new emails are saved when the parent (e.g. `User`) record is saved. (Updates to already-persisted email records 64 | are not saved.) 65 | 66 | If you don't want `autosave` to be enabled automatically, you can disable this feature. What this will do is 67 | enable alternative behavior, which adds an `after_save` callback to the parent record and calls `email.save` on each email 68 | record where the `primary` value has changed. 69 | 70 | ```ruby 71 | Devise::MultiEmail.configure do |config| 72 | # Default is `true` 73 | config.autosave_emails = false 74 | end 75 | ``` 76 | 77 | ### Configure custom association names 78 | 79 | You may not want to use the association `user.emails` or `email.users`. You can customize the name of the associations used. Add your custom configurations to an initializer file such as `config/initializers/devise-multi_email.rb`. 80 | 81 | _Note: model classes are inferred from the associations._ 82 | 83 | ```ruby 84 | Devise::MultiEmail.configure do |config| 85 | # Default is :user for Email model 86 | config.parent_association_name = :team 87 | # Default is :emails for parent (e.g. User) model 88 | config.emails_association_name = :email_addresses 89 | # Default is :primary_email_record 90 | config.primary_email_method_name = :primary_email 91 | end 92 | 93 | # Example use of custom association names 94 | team = Team.first 95 | emails = team.email_addresses 96 | 97 | email = EmailAddress.first 98 | team = email.team 99 | ``` 100 | 101 | ## Confirmable with multiple emails 102 | 103 | Sending separate confirmations to each email is supported. What you need to do is: 104 | 105 | Declare `devise :multi_email_confirmable` in your `User` model: 106 | 107 | ```ruby 108 | class User < ActiveRecord::Base 109 | has_many :emails 110 | 111 | # You should not declare :confirmable and :multi_email_confirmable at the same time. 112 | devise :multi_email_authenticatable, :registerable, :multi_email_confirmable 113 | end 114 | ``` 115 | 116 | Add `:confirmation_token`, `:confirmed_at` and `:confirmation_sent_at` to your `emails` table: 117 | 118 | ```ruby 119 | create_table :emails do |t| 120 | t.integer :user_id 121 | t.string :email 122 | t.boolean :primary, default: false 123 | 124 | ## Confirmable 125 | t.string :unconfirmed_email 126 | t.string :confirmation_token 127 | t.datetime :confirmed_at 128 | t.datetime :confirmation_sent_at 129 | end 130 | ``` 131 | 132 | Then all the methods in Devise confirmable are available in your `Email` model. You can do `email#send_confirmation_instructions` for each of your email. And `user#send_confirmation_instructions` will be delegated to the primary email. 133 | 134 | ## Validatable with multiple emails 135 | 136 | Declare `devise :multi_email_validatable` in the `User` model, then all the user emails will be validated: 137 | 138 | ```ruby 139 | class User < ActiveRecord::Base 140 | has_many :emails 141 | 142 | # You should not declare :validatable and :multi_email_validatable at the same time. 143 | devise :multi_email_authenticatable, :registerable, :multi_email_validatable 144 | end 145 | ``` 146 | 147 | You can find the detailed configurations in the [rails 5 example app](https://github.com/allenwq/devise-multi_email/tree/master/examples/rails5_app). 148 | 149 | ## ActiveJob Integration 150 | 151 | The [Devise README](https://github.com/plataformatec/devise#activejob-integration) describes how to use ActiveJob to deliver emails in the background. Normally you would place the following code in your `User` model, however when using _devise-multi_email_ you should place this in the `Email` model. 152 | 153 | ```ruby 154 | # models/email.rb 155 | def send_devise_notification(notification, *args) 156 | devise_mailer.send(notification, self, *args).deliver_later 157 | end 158 | ``` 159 | 160 | ## What's more 161 | 162 | The gem works with all other Devise modules as expected -- you don't need to add the "multi_email" prefix. 163 | 164 | ```ruby 165 | class User < ActiveRecord::Base 166 | devise :multi_email_authenticatable, :multi_email_confirmable, :multi_email_validatable, :lockable, 167 | :recoverable, :registerable, :rememberable, :timeoutable, :trackable 168 | end 169 | ``` 170 | 171 | ## Issues 172 | 173 | You need to implement add/delete emails for a user as well as set/unset "primary" for each email. 174 | 175 | You can do `email.send_confirmation_instructions` for each email individually, but you need to handle that logic in some place (except for the primary email, which is handled by Devise by default). e.g. After a new email was added by a user, you might want to provide some buttons in the view to allow users to resend confirmation instructions for that email. 176 | 177 | ## Wiki 178 | 179 | [Migrating existing user records](https://github.com/allenwq/devise-multi_email/wiki/Migrating-existing-user-records) 180 | 181 | ## Development 182 | 183 | After checking out the repo, run `bundle install` to install dependencies. 184 | 185 | Then, run `bundle exec rake` to run the RSpec test suite. 186 | 187 | ## Contributing 188 | 189 | Bug reports and pull requests are welcome on GitHub at https://github.com/allenwq/devise-multi_email. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct. 190 | 191 | 192 | ## License 193 | 194 | The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). 195 | -------------------------------------------------------------------------------- /spec/rails_app/config/initializers/devise.rb: -------------------------------------------------------------------------------- 1 | # Use this hook to configure devise mailer, warden hooks and so forth. The first 2 | # four configuration values can also be set straight in your models. 3 | Devise.setup do |config| 4 | config.secret_key = "d9eb5171c59a4c817f68b0de27b8c1e340c2341b52cdbc60d3083d4e8958532" \ 5 | "18dcc5f589cafde048faec956b61f864b9b5513ff9ce29bf9e5d58b0f234f8e3b" 6 | 7 | # ==> Mailer Configuration 8 | # Configure the e-mail address which will be shown in Devise::Mailer, 9 | # note that it will be overwritten if you use your own mailer class with default "from" parameter. 10 | config.mailer_sender = "please-change-me@config-initializers-devise.com" 11 | 12 | # Configure the class responsible to send e-mails. 13 | # config.mailer = "Devise::Mailer" 14 | 15 | # ==> ORM configuration 16 | # Load and configure the ORM. Supports :active_record (default) and 17 | # :mongoid (bson_ext recommended) by default. Other ORMs may be 18 | # available as additional gems. 19 | require 'devise/orm/active_record' 20 | 21 | # ==> Configuration for any authentication mechanism 22 | # Configure which keys are used when authenticating a user. By default is 23 | # just :email. You can configure it to use [:username, :subdomain], so for 24 | # authenticating a user, both parameters are required. Remember that those 25 | # parameters are used only when authenticating and not when retrieving from 26 | # session. If you need permissions, you should implement that in a before filter. 27 | # You can also supply hash where the value is a boolean expliciting if authentication 28 | # should be aborted or not if the value is not present. By default is empty. 29 | # config.authentication_keys = [:email] 30 | 31 | # Configure parameters from the request object used for authentication. Each entry 32 | # given should be a request method and it will automatically be passed to 33 | # find_for_authentication method and considered in your model lookup. For instance, 34 | # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. 35 | # The same considerations mentioned for authentication_keys also apply to request_keys. 36 | # config.request_keys = [] 37 | 38 | # Configure which authentication keys should be case-insensitive. 39 | # These keys will be downcased upon creating or modifying a user and when used 40 | # to authenticate or find a user. Default is :email. 41 | config.case_insensitive_keys = [:email] 42 | 43 | # Configure which authentication keys should have whitespace stripped. 44 | # These keys will have whitespace before and after removed upon creating or 45 | # modifying a user and when used to authenticate or find a user. Default is :email. 46 | config.strip_whitespace_keys = [:email] 47 | 48 | # Tell if authentication through request.params is enabled. True by default. 49 | # config.params_authenticatable = true 50 | 51 | # Tell if authentication through HTTP Basic Auth is enabled. False by default. 52 | config.http_authenticatable = true 53 | 54 | # If http headers should be returned for AJAX requests. True by default. 55 | # config.http_authenticatable_on_xhr = true 56 | 57 | # The realm used in Http Basic Authentication. "Application" by default. 58 | # config.http_authentication_realm = "Application" 59 | 60 | # ==> Configuration for :database_authenticatable 61 | # For bcrypt, this is the cost for hashing the password and defaults to 10. If 62 | # using other encryptors, it sets how many times you want the password re-encrypted. 63 | config.stretches = Rails.env.test? ? 1 : 10 64 | 65 | # ==> Configuration for :confirmable 66 | # The time you want to give your user to confirm their account. During this time 67 | # they will be able to access your application without confirming. Default is nil. 68 | # When allow_unconfirmed_access_for is zero, the user won't be able to sign in without confirming. 69 | # You can use this to let your user access some features of your application 70 | # without confirming the account, but blocking it after a certain period 71 | # (ie 2 days). 72 | # config.allow_unconfirmed_access_for = 2.days 73 | 74 | # Defines which key will be used when confirming an account 75 | # config.confirmation_keys = [:email] 76 | 77 | # ==> Configuration for :rememberable 78 | # The time the user will be remembered without asking for credentials again. 79 | # config.remember_for = 2.weeks 80 | 81 | # If true, extends the user's remember period when remembered via cookie. 82 | # config.extend_remember_period = false 83 | 84 | # ==> Configuration for :validatable 85 | # Range for password length. Default is 8..72. 86 | config.password_length = 7..72 87 | 88 | # Regex to use to validate the email address 89 | # config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i 90 | 91 | # ==> Configuration for :timeoutable 92 | # The time you want to timeout the user session without activity. After this 93 | # time the user will be asked for credentials again. Default is 30 minutes. 94 | # config.timeout_in = 30.minutes 95 | 96 | # ==> Configuration for :lockable 97 | # Defines which strategy will be used to lock an account. 98 | # :failed_attempts = Locks an account after a number of failed attempts to sign in. 99 | # :none = No lock strategy. You should handle locking by yourself. 100 | # config.lock_strategy = :failed_attempts 101 | 102 | # Defines which key will be used when locking and unlocking an account 103 | # config.unlock_keys = [:email] 104 | 105 | # Defines which strategy will be used to unlock an account. 106 | # :email = Sends an unlock link to the user email 107 | # :time = Re-enables login after a certain amount of time (see :unlock_in below) 108 | # :both = Enables both strategies 109 | # :none = No unlock strategy. You should handle unlocking by yourself. 110 | # config.unlock_strategy = :both 111 | 112 | # Number of authentication tries before locking an account if lock_strategy 113 | # is failed attempts. 114 | # config.maximum_attempts = 20 115 | 116 | # Time interval to unlock the account if :time is enabled as unlock_strategy. 117 | # config.unlock_in = 1.hour 118 | 119 | # ==> Configuration for :recoverable 120 | # 121 | # Defines which key will be used when recovering the password for an account 122 | # config.reset_password_keys = [:email] 123 | 124 | # Time interval you can reset your password with a reset password key. 125 | # Don't put a too small interval or your users won't have the time to 126 | # change their passwords. 127 | config.reset_password_within = 2.hours 128 | 129 | # When set to false, does not sign a user in automatically after their password is 130 | # reset. Defaults to true, so a user is signed in automatically after a reset. 131 | # config.sign_in_after_reset_password = true 132 | 133 | # Setup a pepper to generate the encrypted password. 134 | config.pepper = "d142367154e5beacca404b1a6a4f8bc52c6fdcfa3ccc3cf8eb49f3458a688ee6ac3b9fae488432a3bfca863b8a90008368a9f3a3dfbe5a962e64b6ab8f3a3a1a" 135 | 136 | # ==> Scopes configuration 137 | # Turn scoped views on. Before rendering "sessions/new", it will first check for 138 | # "users/sessions/new". It's turned off by default because it's slower if you 139 | # are using only default views. 140 | # config.scoped_views = false 141 | 142 | # Configure the default scope given to Warden. By default it's the first 143 | # devise role declared in your routes (usually :user). 144 | # config.default_scope = :user 145 | 146 | # Configure sign_out behavior. 147 | # Sign_out action can be scoped (i.e. /users/sign_out affects only :user scope). 148 | # The default is true, which means any logout action will sign out all active scopes. 149 | # config.sign_out_all_scopes = true 150 | 151 | # ==> Navigation configuration 152 | # Lists the formats that should be treated as navigational. Formats like 153 | # :html, should redirect to the sign in page when the user does not have 154 | # access, but formats like :xml or :json, should return 401. 155 | # If you have any extra navigational formats, like :iphone or :mobile, you 156 | # should add them to the navigational formats lists. Default is [:html] 157 | # config.navigational_formats = [:html, :iphone] 158 | 159 | # The default HTTP method used to sign out a resource. Default is :get. 160 | # config.sign_out_via = :get 161 | 162 | # ==> Warden configuration 163 | # If you want to use other strategies, that are not supported by Devise, or 164 | # change the failure app, you can configure them inside the config.warden block. 165 | # 166 | # config.warden do |manager| 167 | # manager.failure_app = AnotherApp 168 | # manager.default_strategies(scope: :user).unshift :some_external_strategy 169 | # end 170 | end 171 | -------------------------------------------------------------------------------- /examples/rails5_app/config/initializers/devise.rb: -------------------------------------------------------------------------------- 1 | # Use this hook to configure devise mailer, warden hooks and so forth. 2 | # Many of these configuration options can be set straight in your model. 3 | Devise.setup do |config| 4 | # The secret key used by Devise. Devise uses this key to generate 5 | # random tokens. Changing this key will render invalid all existing 6 | # confirmation, reset password and unlock tokens in the database. 7 | # Devise will use the `secret_key_base` as its `secret_key` 8 | # by default. You can change it below and use your own secret key. 9 | # config.secret_key = 'b931efaaf9a644f22aa2e4524017e95d675b1919530557e5baaa95ec7788e76bb285a7dbf1b5678422f82509dd9e21344874385fbcb1df495a508c96000f00de' 10 | 11 | # ==> Mailer Configuration 12 | # Configure the e-mail address which will be shown in Devise::Mailer, 13 | # note that it will be overwritten if you use your own mailer class 14 | # with default "from" parameter. 15 | config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' 16 | 17 | # Configure the class responsible to send e-mails. 18 | # config.mailer = 'Devise::Mailer' 19 | 20 | # Configure the parent class responsible to send e-mails. 21 | # config.parent_mailer = 'ActionMailer::Base' 22 | 23 | # ==> ORM configuration 24 | # Load and configure the ORM. Supports :active_record (default) and 25 | # :mongoid (bson_ext recommended) by default. Other ORMs may be 26 | # available as additional gems. 27 | require 'devise/orm/active_record' 28 | 29 | # ==> Configuration for any authentication mechanism 30 | # Configure which keys are used when authenticating a user. The default is 31 | # just :email. You can configure it to use [:username, :subdomain], so for 32 | # authenticating a user, both parameters are required. Remember that those 33 | # parameters are used only when authenticating and not when retrieving from 34 | # session. If you need permissions, you should implement that in a before filter. 35 | # You can also supply a hash where the value is a boolean determining whether 36 | # or not authentication should be aborted when the value is not present. 37 | # config.authentication_keys = [:email] 38 | 39 | # Configure parameters from the request object used for authentication. Each entry 40 | # given should be a request method and it will automatically be passed to the 41 | # find_for_authentication method and considered in your model lookup. For instance, 42 | # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. 43 | # The same considerations mentioned for authentication_keys also apply to request_keys. 44 | # config.request_keys = [] 45 | 46 | # Configure which authentication keys should be case-insensitive. 47 | # These keys will be downcased upon creating or modifying a user and when used 48 | # to authenticate or find a user. Default is :email. 49 | config.case_insensitive_keys = [:email] 50 | 51 | # Configure which authentication keys should have whitespace stripped. 52 | # These keys will have whitespace before and after removed upon creating or 53 | # modifying a user and when used to authenticate or find a user. Default is :email. 54 | config.strip_whitespace_keys = [:email] 55 | 56 | # Tell if authentication through request.params is enabled. True by default. 57 | # It can be set to an array that will enable params authentication only for the 58 | # given strategies, for example, `config.params_authenticatable = [:database]` will 59 | # enable it only for database (email + password) authentication. 60 | # config.params_authenticatable = true 61 | 62 | # Tell if authentication through HTTP Auth is enabled. False by default. 63 | # It can be set to an array that will enable http authentication only for the 64 | # given strategies, for example, `config.http_authenticatable = [:database]` will 65 | # enable it only for database authentication. The supported strategies are: 66 | # :database = Support basic authentication with authentication key + password 67 | # config.http_authenticatable = false 68 | 69 | # If 401 status code should be returned for AJAX requests. True by default. 70 | # config.http_authenticatable_on_xhr = true 71 | 72 | # The realm used in Http Basic Authentication. 'Application' by default. 73 | # config.http_authentication_realm = 'Application' 74 | 75 | # It will change confirmation, password recovery and other workflows 76 | # to behave the same regardless if the e-mail provided was right or wrong. 77 | # Does not affect registerable. 78 | # config.paranoid = true 79 | 80 | # By default Devise will store the user in session. You can skip storage for 81 | # particular strategies by setting this option. 82 | # Notice that if you are skipping storage for all authentication paths, you 83 | # may want to disable generating routes to Devise's sessions controller by 84 | # passing skip: :sessions to `devise_for` in your config/routes.rb 85 | config.skip_session_storage = [:http_auth] 86 | 87 | # By default, Devise cleans up the CSRF token on authentication to 88 | # avoid CSRF token fixation attacks. This means that, when using AJAX 89 | # requests for sign in and sign up, you need to get a new CSRF token 90 | # from the server. You can disable this option at your own risk. 91 | # config.clean_up_csrf_token_on_authentication = true 92 | 93 | # When false, Devise will not attempt to reload routes on eager load. 94 | # This can reduce the time taken to boot the app but if your application 95 | # requires the Devise mappings to be loaded during boot time the application 96 | # won't boot properly. 97 | # config.reload_routes = true 98 | 99 | # ==> Configuration for :database_authenticatable 100 | # For bcrypt, this is the cost for hashing the password and defaults to 11. If 101 | # using other algorithms, it sets how many times you want the password to be hashed. 102 | # 103 | # Limiting the stretches to just one in testing will increase the performance of 104 | # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use 105 | # a value less than 10 in other environments. Note that, for bcrypt (the default 106 | # algorithm), the cost increases exponentially with the number of stretches (e.g. 107 | # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). 108 | config.stretches = Rails.env.test? ? 1 : 11 109 | 110 | # Set up a pepper to generate the hashed password. 111 | # config.pepper = 'ba380e8dc51adab8df2f88650218ced6865e462ae55cdc0c796c2501a38b85cf7c30dbf0677995c65c29b9c8dc2ba7dec4640a550597aa246d5eb9ab037fd709' 112 | 113 | # Send a notification email when the user's password is changed 114 | # config.send_password_change_notification = false 115 | 116 | # ==> Configuration for :confirmable 117 | # A period that the user is allowed to access the website even without 118 | # confirming their account. For instance, if set to 2.days, the user will be 119 | # able to access the website for two days without confirming their account, 120 | # access will be blocked just in the third day. Default is 0.days, meaning 121 | # the user cannot access the website without confirming their account. 122 | # config.allow_unconfirmed_access_for = 2.days 123 | 124 | # A period that the user is allowed to confirm their account before their 125 | # token becomes invalid. For example, if set to 3.days, the user can confirm 126 | # their account within 3 days after the mail was sent, but on the fourth day 127 | # their account can't be confirmed with the token any more. 128 | # Default is nil, meaning there is no restriction on how long a user can take 129 | # before confirming their account. 130 | # config.confirm_within = 3.days 131 | 132 | # If true, requires any email changes to be confirmed (exactly the same way as 133 | # initial account confirmation) to be applied. Requires additional unconfirmed_email 134 | # db field (see migrations). Until confirmed, new email is stored in 135 | # unconfirmed_email column, and copied to email column on successful confirmation. 136 | config.reconfirmable = true 137 | 138 | # Defines which key will be used when confirming an account 139 | # config.confirmation_keys = [:email] 140 | 141 | # ==> Configuration for :rememberable 142 | # The time the user will be remembered without asking for credentials again. 143 | # config.remember_for = 2.weeks 144 | 145 | # Invalidates all the remember me tokens when the user signs out. 146 | config.expire_all_remember_me_on_sign_out = true 147 | 148 | # If true, extends the user's remember period when remembered via cookie. 149 | # config.extend_remember_period = false 150 | 151 | # Options to be passed to the created cookie. For instance, you can set 152 | # secure: true in order to force SSL only cookies. 153 | # config.rememberable_options = {} 154 | 155 | # ==> Configuration for :validatable 156 | # Range for password length. 157 | config.password_length = 6..128 158 | 159 | # Email regex used to validate email formats. It simply asserts that 160 | # one (and only one) @ exists in the given string. This is mainly 161 | # to give user feedback and not to assert the e-mail validity. 162 | config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ 163 | 164 | # ==> Configuration for :timeoutable 165 | # The time you want to timeout the user session without activity. After this 166 | # time the user will be asked for credentials again. Default is 30 minutes. 167 | # config.timeout_in = 30.minutes 168 | 169 | # ==> Configuration for :lockable 170 | # Defines which strategy will be used to lock an account. 171 | # :failed_attempts = Locks an account after a number of failed attempts to sign in. 172 | # :none = No lock strategy. You should handle locking by yourself. 173 | # config.lock_strategy = :failed_attempts 174 | 175 | # Defines which key will be used when locking and unlocking an account 176 | # config.unlock_keys = [:email] 177 | 178 | # Defines which strategy will be used to unlock an account. 179 | # :email = Sends an unlock link to the user email 180 | # :time = Re-enables login after a certain amount of time (see :unlock_in below) 181 | # :both = Enables both strategies 182 | # :none = No unlock strategy. You should handle unlocking by yourself. 183 | # config.unlock_strategy = :both 184 | 185 | # Number of authentication tries before locking an account if lock_strategy 186 | # is failed attempts. 187 | # config.maximum_attempts = 20 188 | 189 | # Time interval to unlock the account if :time is enabled as unlock_strategy. 190 | # config.unlock_in = 1.hour 191 | 192 | # Warn on the last attempt before the account is locked. 193 | # config.last_attempt_warning = true 194 | 195 | # ==> Configuration for :recoverable 196 | # 197 | # Defines which key will be used when recovering the password for an account 198 | # config.reset_password_keys = [:email] 199 | 200 | # Time interval you can reset your password with a reset password key. 201 | # Don't put a too small interval or your users won't have the time to 202 | # change their passwords. 203 | config.reset_password_within = 6.hours 204 | 205 | # When set to false, does not sign a user in automatically after their password is 206 | # reset. Defaults to true, so a user is signed in automatically after a reset. 207 | # config.sign_in_after_reset_password = true 208 | 209 | # ==> Configuration for :encryptable 210 | # Allow you to use another hashing or encryption algorithm besides bcrypt (default). 211 | # You can use :sha1, :sha512 or algorithms from others authentication tools as 212 | # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 213 | # for default behavior) and :restful_authentication_sha1 (then you should set 214 | # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). 215 | # 216 | # Require the `devise-encryptable` gem when using anything other than bcrypt 217 | # config.encryptor = :sha512 218 | 219 | # ==> Scopes configuration 220 | # Turn scoped views on. Before rendering "sessions/new", it will first check for 221 | # "users/sessions/new". It's turned off by default because it's slower if you 222 | # are using only default views. 223 | # config.scoped_views = false 224 | 225 | # Configure the default scope given to Warden. By default it's the first 226 | # devise role declared in your routes (usually :user). 227 | # config.default_scope = :user 228 | 229 | # Set this configuration to false if you want /users/sign_out to sign out 230 | # only the current scope. By default, Devise signs out all scopes. 231 | # config.sign_out_all_scopes = true 232 | 233 | # ==> Navigation configuration 234 | # Lists the formats that should be treated as navigational. Formats like 235 | # :html, should redirect to the sign in page when the user does not have 236 | # access, but formats like :xml or :json, should return 401. 237 | # 238 | # If you have any extra navigational formats, like :iphone or :mobile, you 239 | # should add them to the navigational formats lists. 240 | # 241 | # The "*/*" below is required to match Internet Explorer requests. 242 | # config.navigational_formats = ['*/*', :html] 243 | 244 | # The default HTTP method used to sign out a resource. Default is :delete. 245 | config.sign_out_via = :delete 246 | 247 | # ==> OmniAuth 248 | # Add a new OmniAuth provider. Check the wiki for more information on setting 249 | # up on your models and hooks. 250 | # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' 251 | 252 | # ==> Warden configuration 253 | # If you want to use other strategies, that are not supported by Devise, or 254 | # change the failure app, you can configure them inside the config.warden block. 255 | # 256 | # config.warden do |manager| 257 | # manager.intercept_401 = false 258 | # manager.default_strategies(scope: :user).unshift :some_external_strategy 259 | # end 260 | 261 | # ==> Mountable engine configurations 262 | # When using Devise inside an engine, let's call it `MyEngine`, and this engine 263 | # is mountable, there are some extra configurations to be taken into account. 264 | # The following options are available, assuming the engine is mounted as: 265 | # 266 | # mount MyEngine, at: '/my_engine' 267 | # 268 | # The router that invoked `devise_for`, in the example above, would be: 269 | # config.router_name = :my_engine 270 | # 271 | # When using OmniAuth, Devise cannot automatically set OmniAuth path, 272 | # so you need to do it manually. For the users scope, it would be: 273 | # config.omniauth_path_prefix = '/my_engine/users/auth' 274 | end 275 | --------------------------------------------------------------------------------