repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/orm/mongoid.rb | test/orm/mongoid.rb | # frozen_string_literal: true
require 'mongoid/version'
Mongoid.configure do |config|
config.load!('test/support/mongoid.yml')
config.use_utc = true
config.include_root_in_json = true
end
class ActiveSupport::TestCase
setup do
Mongoid::Config.purge!
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/mailers/email_changed_test.rb | test/mailers/email_changed_test.rb | # frozen_string_literal: true
require 'test_helper'
class EmailChangedTest < ActionMailer::TestCase
def setup
setup_mailer
Devise.mailer = 'Devise::Mailer'
Devise.mailer_sender = 'test@example.com'
Devise.send_email_changed_notification = true
end
def teardown
Devise.mailer = 'Devise::Mailer'
Devise.mailer_sender = 'please-change-me@config-initializers-devise.com'
Devise.send_email_changed_notification = false
end
def user
@user ||= create_user.tap { |u|
@original_user_email = u.email
u.update!(email: 'new-email@example.com')
}
end
def mail
@mail ||= begin
user
ActionMailer::Base.deliveries.last
end
end
test 'email sent after changing the user email' do
assert_not_nil mail
end
test 'content type should be set to html' do
assert_includes mail.content_type, 'text/html'
end
test 'send email changed to the original user email' do
mail
assert_equal [@original_user_email], mail.to
end
test 'set up sender from configuration' do
assert_equal ['test@example.com'], mail.from
end
test 'set up sender from custom mailer defaults' do
Devise.mailer = 'Users::Mailer'
assert_equal ['custom@example.com'], mail.from
end
test 'set up sender from custom mailer defaults with proc' do
Devise.mailer = 'Users::FromProcMailer'
assert_equal ['custom@example.com'], mail.from
end
test 'custom mailer renders parent mailer template' do
Devise.mailer = 'Users::Mailer'
assert_present mail.body.encoded
end
test 'set up reply to as copy from sender' do
assert_equal ['test@example.com'], mail.reply_to
end
test 'set up reply to as different if set in defaults' do
Devise.mailer = 'Users::ReplyToMailer'
assert_equal ['custom@example.com'], mail.from
assert_equal ['custom_reply_to@example.com'], mail.reply_to
end
test 'set up subject from I18n' do
store_translations :en, devise: { mailer: { email_changed: { subject: 'Email Has Changed' } } } do
assert_equal 'Email Has Changed', mail.subject
end
end
test 'subject namespaced by model' do
store_translations :en, devise: { mailer: { email_changed: { user_subject: 'User Email Has Changed' } } } do
assert_equal 'User Email Has Changed', mail.subject
end
end
test 'body should have user info' do
body = mail.body.encoded
assert_match "Hello #{@original_user_email}", body
assert_match "has been changed to #{user.email}", body
end
end
class EmailChangedReconfirmationTest < ActionMailer::TestCase
def setup
setup_mailer
Devise.mailer = 'Devise::Mailer'
Devise.mailer_sender = 'test@example.com'
Devise.send_email_changed_notification = true
end
def teardown
Devise.mailer = 'Devise::Mailer'
Devise.mailer_sender = 'please-change-me@config-initializers-devise.com'
Devise.send_email_changed_notification = false
end
def admin
@admin ||= create_admin.tap { |u|
@original_admin_email = u.email
u.update!(email: 'new-email@example.com')
}
end
def mail
@mail ||= begin
admin
ActionMailer::Base.deliveries[-2]
end
end
test 'send email changed to the original user email' do
mail
assert_equal [@original_admin_email], mail.to
end
test 'body should have unconfirmed user info' do
body = mail.body.encoded
assert_match admin.email, body
assert_match "is being changed to #{admin.unconfirmed_email}", body
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/mailers/confirmation_instructions_test.rb | test/mailers/confirmation_instructions_test.rb | # frozen_string_literal: true
require 'test_helper'
class ConfirmationInstructionsTest < ActionMailer::TestCase
def setup
setup_mailer
Devise.mailer = 'Devise::Mailer'
Devise.mailer_sender = 'test@example.com'
end
def teardown
Devise.mailer = 'Devise::Mailer'
Devise.mailer_sender = 'please-change-me@config-initializers-devise.com'
end
def user
@user ||= create_user
end
def mail
@mail ||= begin
user
ActionMailer::Base.deliveries.first
end
end
test 'email sent after creating the user' do
assert_not_nil mail
end
test 'content type should be set to html' do
assert_includes mail.content_type, 'text/html'
end
test 'send confirmation instructions to the user email' do
mail
assert_equal [user.email], mail.to
end
test 'set up sender from configuration' do
assert_equal ['test@example.com'], mail.from
end
test 'set up sender from custom mailer defaults' do
Devise.mailer = 'Users::Mailer'
assert_equal ['custom@example.com'], mail.from
end
test 'set up sender from custom mailer defaults with proc' do
Devise.mailer = 'Users::FromProcMailer'
assert_equal ['custom@example.com'], mail.from
end
test 'custom mailer renders parent mailer template' do
Devise.mailer = 'Users::Mailer'
assert_present mail.body.encoded
end
test 'set up reply to as copy from sender' do
assert_equal ['test@example.com'], mail.reply_to
end
test 'set up reply to as different if set in defaults' do
Devise.mailer = 'Users::ReplyToMailer'
assert_equal ['custom@example.com'], mail.from
assert_equal ['custom_reply_to@example.com'], mail.reply_to
end
test 'set up subject from I18n' do
store_translations :en, devise: { mailer: { confirmation_instructions: { subject: 'Account Confirmation' } } } do
assert_equal 'Account Confirmation', mail.subject
end
end
test 'subject namespaced by model' do
store_translations :en, devise: { mailer: { confirmation_instructions: { user_subject: 'User Account Confirmation' } } } do
assert_equal 'User Account Confirmation', mail.subject
end
end
test 'body should have user info' do
assert_match user.email, mail.body.encoded
end
test 'body should have link to confirm the account' do
host, port = ActionMailer::Base.default_url_options.values_at :host, :port
if mail.body.encoded =~ %r{<a href=\"http://#{host}:#{port}/users/confirmation\?confirmation_token=([^"]+)">}
assert_equal user.confirmation_token, $1
else
flunk "expected confirmation url regex to match"
end
end
test 'renders a scoped if scoped_views is set to true' do
swap Devise, scoped_views: true do
assert_equal user.email, mail.body.decoded
end
end
test 'renders a scoped if scoped_views is set in the mailer class' do
begin
Devise::Mailer.scoped_views = true
assert_equal user.email, mail.body.decoded
ensure
Devise::Mailer.send :remove_instance_variable, :@scoped_views
end
end
test 'mailer sender accepts a proc' do
swap Devise, mailer_sender: proc { "another@example.com" } do
assert_equal ['another@example.com'], mail.from
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/mailers/mailer_test.rb | test/mailers/mailer_test.rb | # frozen_string_literal: true
require "test_helper"
class MailerTest < ActionMailer::TestCase
test "pass given block to #mail call" do
class TestMailer < Devise::Mailer
def confirmation_instructions(record, token, opts = {})
@token = token
devise_mail(record, :confirmation_instructions, opts) do |format|
format.html(content_transfer_encoding: "7bit")
end
end
end
mail = TestMailer.confirmation_instructions(create_user, "confirmation-token")
assert mail.content_transfer_encoding, "7bit"
end
test "default values defined as proc with different arity are handled correctly" do
class TestMailerWithDefault < Devise::Mailer
default from: -> { computed_from }
default reply_to: ->(_) { computed_reply_to }
def confirmation_instructions(record, token, opts = {})
@token = token
devise_mail(record, :confirmation_instructions, opts)
end
private
def computed_from
"from@example.com"
end
def computed_reply_to
"reply_to@example.com"
end
end
mail = TestMailerWithDefault.confirmation_instructions(create_user, "confirmation-token")
assert mail.from, "from@example.com"
assert mail.reply_to, "reply_to@example.com"
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/mailers/reset_password_instructions_test.rb | test/mailers/reset_password_instructions_test.rb | # frozen_string_literal: true
require 'test_helper'
class ResetPasswordInstructionsTest < ActionMailer::TestCase
def setup
setup_mailer
Devise.mailer = 'Devise::Mailer'
Devise.mailer_sender = 'test@example.com'
end
def teardown
Devise.mailer = 'Devise::Mailer'
Devise.mailer_sender = 'please-change-me@config-initializers-devise.com'
end
def user
@user ||= begin
user = create_user
user.send_reset_password_instructions
user
end
end
def mail
@mail ||= begin
user
ActionMailer::Base.deliveries.last
end
end
test 'email sent after resetting the user password' do
assert_not_nil mail
end
test 'content type should be set to html' do
assert_includes mail.content_type, 'text/html'
end
test 'send confirmation instructions to the user email' do
assert_equal [user.email], mail.to
end
test 'set up sender from configuration' do
assert_equal ['test@example.com'], mail.from
end
test 'set up sender from custom mailer defaults' do
Devise.mailer = 'Users::Mailer'
assert_equal ['custom@example.com'], mail.from
end
test 'set up sender from custom mailer defaults with proc' do
Devise.mailer = 'Users::FromProcMailer'
assert_equal ['custom@example.com'], mail.from
end
test 'custom mailer renders parent mailer template' do
Devise.mailer = 'Users::Mailer'
assert_present mail.body.encoded
end
test 'set up reply to as copy from sender' do
assert_equal ['test@example.com'], mail.reply_to
end
test 'set up subject from I18n' do
store_translations :en, devise: { mailer: { reset_password_instructions: { subject: 'Reset instructions' } } } do
assert_equal 'Reset instructions', mail.subject
end
end
test 'subject namespaced by model' do
store_translations :en, devise: { mailer: { reset_password_instructions: { user_subject: 'User Reset Instructions' } } } do
assert_equal 'User Reset Instructions', mail.subject
end
end
test 'body should have user info' do
assert_match user.email, mail.body.encoded
end
test 'body should have link to confirm the account' do
host, port = ActionMailer::Base.default_url_options.values_at :host, :port
if mail.body.encoded =~ %r{<a href=\"http://#{host}:#{port}/users/password/edit\?reset_password_token=([^"]+)">}
assert_equal user.reset_password_token, Devise.token_generator.digest(user.class, :reset_password_token, $1)
else
flunk "expected reset password url regex to match"
end
end
test 'mailer sender accepts a proc' do
swap Devise, mailer_sender: proc { "another@example.com" } do
assert_equal ['another@example.com'], mail.from
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/mailers/unlock_instructions_test.rb | test/mailers/unlock_instructions_test.rb | # frozen_string_literal: true
require 'test_helper'
class UnlockInstructionsTest < ActionMailer::TestCase
def setup
setup_mailer
Devise.mailer = 'Devise::Mailer'
Devise.mailer_sender = 'test@example.com'
end
def teardown
Devise.mailer = 'Devise::Mailer'
Devise.mailer_sender = 'please-change-me@config-initializers-devise.com'
end
def user
@user ||= begin
user = create_user
user.lock_access!
user
end
end
def mail
@mail ||= begin
user
ActionMailer::Base.deliveries.last
end
end
test 'email sent after locking the user' do
assert_not_nil mail
end
test 'content type should be set to html' do
assert_includes mail.content_type, 'text/html'
end
test 'send unlock instructions to the user email' do
assert_equal [user.email], mail.to
end
test 'set up sender from configuration' do
assert_equal ['test@example.com'], mail.from
end
test 'set up sender from custom mailer defaults' do
Devise.mailer = 'Users::Mailer'
assert_equal ['custom@example.com'], mail.from
end
test 'set up sender from custom mailer defaults with proc' do
Devise.mailer = 'Users::FromProcMailer'
assert_equal ['custom@example.com'], mail.from
end
test 'custom mailer renders parent mailer template' do
Devise.mailer = 'Users::Mailer'
assert_present mail.body.encoded
end
test 'set up reply to as copy from sender' do
assert_equal ['test@example.com'], mail.reply_to
end
test 'set up subject from I18n' do
store_translations :en, devise: { mailer: { unlock_instructions: { subject: 'Yo unlock instructions' } } } do
assert_equal 'Yo unlock instructions', mail.subject
end
end
test 'subject namespaced by model' do
store_translations :en, devise: { mailer: { unlock_instructions: { user_subject: 'User Unlock Instructions' } } } do
assert_equal 'User Unlock Instructions', mail.subject
end
end
test 'body should have user info' do
assert_match user.email, mail.body.encoded
end
test 'body should have link to unlock the account' do
host, port = ActionMailer::Base.default_url_options.values_at :host, :port
if mail.body.encoded =~ %r{<a href=\"http://#{host}:#{port}/users/unlock\?unlock_token=([^"]+)">}
assert_equal user.unlock_token, Devise.token_generator.digest(user.class, :unlock_token, $1)
else
flunk "expected unlock url regex to match"
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/helpers/application_helper.rb | test/rails_app/app/helpers/application_helper.rb | # frozen_string_literal: true
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/mongoid/user_without_email.rb | test/rails_app/app/mongoid/user_without_email.rb | # frozen_string_literal: true
require "shared_user_without_email"
class UserWithoutEmail
include Mongoid::Document
include Shim
include SharedUserWithoutEmail
field :username, type: String
field :facebook_token, type: String
## Database authenticatable
field :email, type: String, default: ""
field :encrypted_password, type: String, default: ""
## Recoverable
field :reset_password_token, type: String
field :reset_password_sent_at, type: Time
## Rememberable
field :remember_created_at, type: Time
## Trackable
field :sign_in_count, type: Integer, default: 0
field :current_sign_in_at, type: Time
field :last_sign_in_at, type: Time
field :current_sign_in_ip, type: String
field :last_sign_in_ip, type: String
## Lockable
field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
field :unlock_token, type: String # Only if unlock strategy is :email or :both
field :locked_at, type: Time
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/mongoid/user_on_main_app.rb | test/rails_app/app/mongoid/user_on_main_app.rb | # frozen_string_literal: true
require 'shared_user_without_omniauth'
class UserOnMainApp
include Mongoid::Document
include Shim
include SharedUserWithoutOmniauth
field :username, type: String
field :facebook_token, type: String
## Database authenticatable
field :email, type: String, default: ""
field :encrypted_password, type: String, default: ""
## Recoverable
field :reset_password_token, type: String
field :reset_password_sent_at, type: Time
## Rememberable
field :remember_created_at, type: Time
## Trackable
field :sign_in_count, type: Integer, default: 0
field :current_sign_in_at, type: Time
field :last_sign_in_at, type: Time
field :current_sign_in_ip, type: String
field :last_sign_in_ip, type: String
## Confirmable
field :confirmation_token, type: String
field :confirmed_at, type: Time
field :confirmation_sent_at, type: Time
# field :unconfirmed_email, type: String # Only if using reconfirmable
## Lockable
field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
field :unlock_token, type: String # Only if unlock strategy is :email or :both
field :locked_at, type: Time
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/mongoid/shim.rb | test/rails_app/app/mongoid/shim.rb | # frozen_string_literal: true
module Shim
extend ::ActiveSupport::Concern
included do
include ::Mongoid::Timestamps
field :created_at, type: DateTime
end
module ClassMethods
def order(attribute)
asc(attribute)
end
def find_by_email(email)
find_by(email: email)
end
end
# overwrite equality (because some devise tests use this for asserting model equality)
def ==(other)
other.is_a?(self.class) && _id == other._id
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/mongoid/user_on_engine.rb | test/rails_app/app/mongoid/user_on_engine.rb | # frozen_string_literal: true
require 'shared_user_without_omniauth'
class UserOnEngine
include Mongoid::Document
include Shim
include SharedUserWithoutOmniauth
field :username, type: String
field :facebook_token, type: String
## Database authenticatable
field :email, type: String, default: ""
field :encrypted_password, type: String, default: ""
## Recoverable
field :reset_password_token, type: String
field :reset_password_sent_at, type: Time
## Rememberable
field :remember_created_at, type: Time
## Trackable
field :sign_in_count, type: Integer, default: 0
field :current_sign_in_at, type: Time
field :last_sign_in_at, type: Time
field :current_sign_in_ip, type: String
field :last_sign_in_ip, type: String
## Confirmable
field :confirmation_token, type: String
field :confirmed_at, type: Time
field :confirmation_sent_at, type: Time
# field :unconfirmed_email, type: String # Only if using reconfirmable
## Lockable
field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
field :unlock_token, type: String # Only if unlock strategy is :email or :both
field :locked_at, type: Time
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/mongoid/admin.rb | test/rails_app/app/mongoid/admin.rb | # frozen_string_literal: true
require 'shared_admin'
class Admin
include Mongoid::Document
include Shim
include SharedAdmin
## Database authenticatable
field :email, type: String
field :encrypted_password, type: String
## Recoverable
field :reset_password_token, type: String
field :reset_password_sent_at, type: Time
## Rememberable
field :remember_created_at, type: Time
## Confirmable
field :confirmation_token, type: String
field :confirmed_at, type: Time
field :confirmation_sent_at, type: Time
field :unconfirmed_email, type: String # Only if using reconfirmable
## Lockable
field :locked_at, type: Time
field :active, type: Boolean, default: false
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/mongoid/user_with_validations.rb | test/rails_app/app/mongoid/user_with_validations.rb | # frozen_string_literal: true
require "shared_user"
class UserWithValidations
include Mongoid::Document
include Shim
include SharedUser
field :username, type: String
field :facebook_token, type: String
## Database authenticatable
field :email, type: String, default: ""
field :encrypted_password, type: String, default: ""
## Recoverable
field :reset_password_token, type: String
field :reset_password_sent_at, type: Time
## Rememberable
field :remember_created_at, type: Time
## Trackable
field :sign_in_count, type: Integer, default: 0
field :current_sign_in_at, type: Time
field :last_sign_in_at, type: Time
field :current_sign_in_ip, type: String
field :last_sign_in_ip, type: String
## Lockable
field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
field :unlock_token, type: String # Only if unlock strategy is :email or :both
field :locked_at, type: Time
validates :email, presence: true
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/mongoid/user.rb | test/rails_app/app/mongoid/user.rb | # frozen_string_literal: true
require 'shared_user'
class User
include Mongoid::Document
include Shim
include SharedUser
field :username, type: String
field :facebook_token, type: String
## Database authenticatable
field :email, type: String, default: ""
field :encrypted_password, type: String, default: ""
## Recoverable
field :reset_password_token, type: String
field :reset_password_sent_at, type: Time
## Rememberable
field :remember_created_at, type: Time
## Trackable
field :sign_in_count, type: Integer, default: 0
field :current_sign_in_at, type: Time
field :last_sign_in_at, type: Time
field :current_sign_in_ip, type: String
field :last_sign_in_ip, type: String
## Confirmable
field :confirmation_token, type: String
field :confirmed_at, type: Time
field :confirmation_sent_at, type: Time
# field :unconfirmed_email, type: String # Only if using reconfirmable
## Lockable
field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
field :unlock_token, type: String # Only if unlock strategy is :email or :both
field :locked_at, type: Time
cattr_accessor :validations_performed
after_validation :after_validation_callback
def after_validation_callback
# used to check in our test if the validations were called
@@validations_performed = true
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/controllers/admins_controller.rb | test/rails_app/app/controllers/admins_controller.rb | # frozen_string_literal: true
class AdminsController < ApplicationController
before_action :authenticate_admin!
def index
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/controllers/home_controller.rb | test/rails_app/app/controllers/home_controller.rb | # frozen_string_literal: true
class HomeController < ApplicationController
def index
end
def private
end
def user_dashboard
end
def admin_dashboard
end
def join
end
def set
session["devise.foo_bar"] = "something"
head :ok
end
def unauthenticated
render body: "unauthenticated", status: :unauthorized
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/controllers/users_controller.rb | test/rails_app/app/controllers/users_controller.rb | # frozen_string_literal: true
class UsersController < ApplicationController
prepend_before_action :current_user, only: :exhibit
before_action :authenticate_user!, except: [:accept, :exhibit]
clear_respond_to
respond_to :html, :json
def index
user_session[:cart] = "Cart"
respond_with(current_user)
end
def edit_form
user_session['last_request_at'] = params.fetch(:last_request_at, 31.minutes.ago.utc)
end
def update_form
render body: 'Update'
end
def accept
@current_user = current_user
end
def exhibit
render body: current_user ? "User is authenticated" : "User is not authenticated"
end
def expire
user_session['last_request_at'] = 31.minutes.ago.utc
render body: 'User will be expired on next request'
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/controllers/streaming_controller.rb | test/rails_app/app/controllers/streaming_controller.rb | # frozen_string_literal: true
class StreamingController < ApplicationController
include ActionController::Live
before_action :authenticate_user!
def index
render body: 'Index'
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/controllers/application_with_fake_engine.rb | test/rails_app/app/controllers/application_with_fake_engine.rb | # frozen_string_literal: true
class ApplicationWithFakeEngine < ApplicationController
private
helper_method :fake_engine
def fake_engine
@fake_engine ||= FakeEngine.new
end
end
class FakeEngine
def user_on_engine_confirmation_path
'/user_on_engine/confirmation'
end
def new_user_on_engine_session_path
'/user_on_engine/confirmation/new'
end
def new_user_on_engine_registration_path
'/user_on_engine/registration/new'
end
def new_user_on_engine_password_path
'/user_on_engine/password/new'
end
def new_user_on_engine_unlock_path
'/user_on_engine/unlock/new'
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/controllers/application_controller.rb | test/rails_app/app/controllers/application_controller.rb | # frozen_string_literal: true
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
protect_from_forgery
around_action :set_locale
before_action :current_user, unless: :devise_controller?
before_action :authenticate_user!, if: :devise_controller?
respond_to(*Mime::SET.map(&:to_sym))
devise_group :commenter, contains: [:user, :admin]
private
def set_locale
I18n.with_locale(params[:locale] || I18n.default_locale) { yield }
end
def default_url_options
{locale: params[:locale]}.compact
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/controllers/custom/registrations_controller.rb | test/rails_app/app/controllers/custom/registrations_controller.rb | # frozen_string_literal: true
class Custom::RegistrationsController < Devise::RegistrationsController
def new
super do |resource|
@new_block_called = true
end
end
def create
super do |resource|
@create_block_called = true
end
end
def update
super do |resource|
@update_block_called = true
end
end
def create_block_called?
@create_block_called == true
end
def update_block_called?
@update_block_called == true
end
def new_block_called?
@new_block_called == true
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/controllers/publisher/registrations_controller.rb | test/rails_app/app/controllers/publisher/registrations_controller.rb | # frozen_string_literal: true
class Publisher::RegistrationsController < ApplicationController
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/controllers/publisher/sessions_controller.rb | test/rails_app/app/controllers/publisher/sessions_controller.rb | # frozen_string_literal: true
class Publisher::SessionsController < ApplicationController
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/controllers/admins/sessions_controller.rb | test/rails_app/app/controllers/admins/sessions_controller.rb | # frozen_string_literal: true
class Admins::SessionsController < Devise::SessionsController
def new
flash[:special] = "Welcome to #{controller_path.inspect} controller!"
super
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb | test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb | # frozen_string_literal: true
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
data = request.respond_to?(:get_header) ? request.get_header("omniauth.auth") : request.env["omniauth.auth"]
session["devise.facebook_data"] = data["extra"]["user_hash"]
render json: data
end
def sign_in_facebook
user = User.to_adapter.find_first(email: 'user@test.com')
user.remember_me = true
sign_in user
render body: ""
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/active_record/user_without_email.rb | test/rails_app/app/active_record/user_without_email.rb | # frozen_string_literal: true
require "shared_user_without_email"
class UserWithoutEmail < ActiveRecord::Base
self.table_name = 'users'
include Shim
include SharedUserWithoutEmail
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/active_record/user_on_main_app.rb | test/rails_app/app/active_record/user_on_main_app.rb | # frozen_string_literal: true
require 'shared_user_without_omniauth'
class UserOnMainApp < ActiveRecord::Base
self.table_name = 'users'
include Shim
include SharedUserWithoutOmniauth
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/active_record/shim.rb | test/rails_app/app/active_record/shim.rb | # frozen_string_literal: true
module Shim
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/active_record/user_on_engine.rb | test/rails_app/app/active_record/user_on_engine.rb | # frozen_string_literal: true
require 'shared_user_without_omniauth'
class UserOnEngine < ActiveRecord::Base
self.table_name = 'users'
include Shim
include SharedUserWithoutOmniauth
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/active_record/admin.rb | test/rails_app/app/active_record/admin.rb | # frozen_string_literal: true
require 'shared_admin'
class Admin < ActiveRecord::Base
include Shim
include SharedAdmin
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/active_record/user_with_validations.rb | test/rails_app/app/active_record/user_with_validations.rb | # frozen_string_literal: true
require 'shared_user'
class UserWithValidations < ActiveRecord::Base
self.table_name = 'users'
include Shim
include SharedUser
validates :email, presence: true
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/active_record/user.rb | test/rails_app/app/active_record/user.rb | # frozen_string_literal: true
require 'shared_user'
class User < ActiveRecord::Base
include Shim
include SharedUser
validates :sign_in_count, presence: true
cattr_accessor :validations_performed
after_validation :after_validation_callback
def after_validation_callback
# used to check in our test if the validations were called
@@validations_performed = true
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/mailers/users/mailer.rb | test/rails_app/app/mailers/users/mailer.rb | # frozen_string_literal: true
class Users::Mailer < Devise::Mailer
default from: 'custom@example.com'
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/mailers/users/reply_to_mailer.rb | test/rails_app/app/mailers/users/reply_to_mailer.rb | # frozen_string_literal: true
class Users::ReplyToMailer < Devise::Mailer
default from: 'custom@example.com'
default reply_to: 'custom_reply_to@example.com'
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/app/mailers/users/from_proc_mailer.rb | test/rails_app/app/mailers/users/from_proc_mailer.rb | # frozen_string_literal: true
class Users::FromProcMailer < Devise::Mailer
default from: proc { 'custom@example.com' }
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/db/schema.rb | test/rails_app/db/schema.rb | # encoding: UTF-8
# frozen_string_literal: true
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20100401102949) do
create_table "admins", force: true do |t|
t.string "email"
t.string "encrypted_password"
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.datetime "locked_at"
t.boolean "active", default: false
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.string "username"
t.string "facebook_token"
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.integer "failed_attempts", default: 0
t.string "unlock_token"
t.datetime "locked_at"
t.datetime "created_at"
t.datetime "updated_at"
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/db/migrate/20100401102949_create_tables.rb | test/rails_app/db/migrate/20100401102949_create_tables.rb | # frozen_string_literal: true
class CreateTables < ActiveRecord::Migration[5.0]
def self.up
create_table :users do |t|
t.string :username
t.string :facebook_token
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
t.integer :failed_attempts, default: 0 # Only if lock strategy is :failed_attempts
t.string :unlock_token # Only if unlock strategy is :email or :both
t.datetime :locked_at
t.timestamps null: false
end
create_table :admins do |t|
## Database authenticatable
t.string :email, null: true
t.string :encrypted_password, null: true
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Confirmable
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
t.datetime :locked_at
## Attribute for testing route blocks
t.boolean :active, default: false
t.timestamps null: false
end
end
def self.down
drop_table :users
drop_table :admins
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/lib/shared_user_without_omniauth.rb | test/rails_app/lib/shared_user_without_omniauth.rb | # frozen_string_literal: true
module SharedUserWithoutOmniauth
extend ActiveSupport::Concern
included do
devise :database_authenticatable, :confirmable, :lockable, :recoverable,
:registerable, :rememberable, :timeoutable,
:trackable, :validatable, reconfirmable: false
end
def raw_confirmation_token
@raw_confirmation_token
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/lib/shared_admin.rb | test/rails_app/lib/shared_admin.rb | # frozen_string_literal: true
module SharedAdmin
extend ActiveSupport::Concern
included do
devise :database_authenticatable, :registerable,
:timeoutable, :recoverable, :lockable, :confirmable,
unlock_strategy: :time, lock_strategy: :none,
allow_unconfirmed_access_for: 2.weeks, reconfirmable: true
validates_length_of :reset_password_token, minimum: 3, allow_blank: true
validates_uniqueness_of :email, allow_blank: true, if: :devise_will_save_change_to_email?
end
def raw_confirmation_token
@raw_confirmation_token
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/lib/shared_user.rb | test/rails_app/lib/shared_user.rb | # frozen_string_literal: true
module SharedUser
extend ActiveSupport::Concern
included do
devise :database_authenticatable, :confirmable, :lockable, :recoverable,
:registerable, :rememberable, :timeoutable,
:trackable, :validatable, :omniauthable, password_length: 7..72,
reconfirmable: false
attr_accessor :other_key
# They need to be included after Devise is called.
extend ExtendMethods
end
def raw_confirmation_token
@raw_confirmation_token
end
module ExtendMethods
def new_with_session(params, session)
super.tap do |user|
if data = session["devise.facebook_data"]
user.email = data["email"]
user.confirmed_at = Time.now
end
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/lib/shared_user_without_email.rb | test/rails_app/lib/shared_user_without_email.rb | # frozen_string_literal: true
module SharedUserWithoutEmail
extend ActiveSupport::Concern
included do
# NOTE: This is missing :validatable and :confirmable, as they both require
# an email field at the moment. It is also missing :omniauthable because that
# adds unnecessary complexity to the setup
devise :database_authenticatable, :lockable, :recoverable,
:registerable, :rememberable, :timeoutable,
:trackable
end
# This test stub is a bit rubbish because it's tied very closely to the
# implementation where we care about this one case. However, completely
# removing the email field breaks "recoverable" tests completely, so we are
# just taking the approach here that "email" is something that is a not an
# ActiveRecord field.
def email_changed?
raise NoMethodError
end
def respond_to?(method_name, include_all = false)
return false if method_name.to_sym == :email_changed?
super(method_name, include_all)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/lib/lazy_load_test_module.rb | test/rails_app/lib/lazy_load_test_module.rb | module LazyLoadTestModule
def lazy_loading_works?
"yes it does"
end
end | ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/config/application.rb | test/rails_app/config/application.rb | # frozen_string_literal: true
require File.expand_path('../boot', __FILE__)
require "logger"
require "action_controller/railtie"
require "action_mailer/railtie"
require "rails/test_unit/railtie"
Bundler.require :default, DEVISE_ORM
begin
require "#{DEVISE_ORM}/railtie"
rescue LoadError
end
require "devise"
module RailsApp
class Application < Rails::Application
# Add additional load paths for your own custom dirs
config.autoload_paths.reject!{ |p| p =~ /\/app\/(\w+)$/ && !%w(controllers helpers mailers views).include?($1) }
config.autoload_paths += ["#{config.root}/app/#{DEVISE_ORM}"]
# Configure generators values. Many other options are available, be sure to check the documentation.
# config.generators do |g|
# g.orm :active_record
# g.template_engine :erb
# g.test_framework :test_unit, fixture: true
# end
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters << :password
# config.assets.enabled = false
config.action_mailer.default_url_options = { host: "localhost", port: 3000 }
# This was used to break devise in some situations
config.to_prepare do
Devise::SessionsController.layout "application"
end
if DEVISE_ORM == :active_record
if Devise::Test.rails70?
config.active_record.legacy_connection_handling = false
end
end
if Devise::Test.rails70_and_up?
config.active_support.cache_format_version = 7.0
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/config/environment.rb | test/rails_app/config/environment.rb | # frozen_string_literal: true
# Load the rails application.
require File.expand_path('../application', __FILE__)
# Initialize the rails application.
RailsApp::Application.initialize!
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/config/routes.rb | test/rails_app/config/routes.rb | # frozen_string_literal: true
Rails.application.routes.draw do
# Resources for testing
resources :users, only: [:index] do
member do
get :expire
get :accept
get :edit_form
put :update_form
end
authenticate do
post :exhibit, on: :member
end
end
resources :admins, only: [:index]
resources :streaming, only: [:index]
# Users scope
devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" }
devise_for :user_on_main_apps,
class_name: 'UserOnMainApp',
router_name: :main_app,
module: :devise
devise_for :user_on_engines,
class_name: 'UserOnEngine',
router_name: :fake_engine,
module: :devise
devise_for :user_without_email,
class_name: 'UserWithoutEmail',
router_name: :main_app,
module: :devise
as :user do
get "/as/sign_in", to: "devise/sessions#new"
end
get "/sign_in", to: "devise/sessions#new"
# Routes for custom controller testing
devise_for :user, only: [:registrations], controllers: { registrations: "custom/registrations" }, as: :custom, path: :custom
# Admin scope
devise_for :admin, path: "admin_area", controllers: { sessions: :"admins/sessions" }, skip: :passwords
get "/admin_area/home", to: "admins#index", as: :admin_root
get "/anywhere", to: "foo#bar", as: :new_admin_password
authenticate(:admin) do
get "/private", to: "home#private", as: :private
end
authenticate(:admin, lambda { |admin| admin.active? }) do
get "/private/active", to: "home#private", as: :private_active
end
authenticated :admin do
get "/dashboard", to: "home#admin_dashboard"
end
authenticated :admin, lambda { |admin| admin.active? } do
get "/dashboard/active", to: "home#admin_dashboard"
end
authenticated do
get "/dashboard", to: "home#user_dashboard"
end
unauthenticated do
get "/join", to: "home#join"
end
# Routes for constraints testing
devise_for :headquarters_admin, class_name: "Admin", path: "headquarters", constraints: {host: /192\.168\.1\.\d\d\d/}
constraints(host: /192\.168\.1\.\d\d\d/) do
devise_for :homebase_admin, class_name: "Admin", path: "homebase"
end
scope(subdomain: 'sub') do
devise_for :subdomain_users, class_name: "User", only: [:sessions]
end
devise_for :skip_admin, class_name: "Admin", skip: :all
# Routes for format=false testing
devise_for :htmlonly_admin, class_name: "Admin", skip: [:confirmations, :unlocks], path: "htmlonly_admin", format: false, skip_helpers: [:confirmations, :unlocks]
devise_for :htmlonly_users, class_name: "User", only: [:confirmations, :unlocks], path: "htmlonly_users", format: false, skip_helpers: true
# Other routes for routing_test.rb
devise_for :reader, class_name: "User", only: :passwords
scope host: "sub.example.com" do
devise_for :sub_admin, class_name: "Admin"
end
namespace :publisher, path_names: { sign_in: "i_dont_care", sign_out: "get_out" } do
devise_for :accounts, class_name: "Admin", path_names: { sign_in: "get_in" }
end
scope ":locale", module: :invalid do
devise_for :accounts, singular: "manager", class_name: "Admin",
path_names: {
sign_in: "login", sign_out: "logout",
password: "secret", confirmation: "verification",
unlock: "unblock", sign_up: "register",
registration: "management",
cancel: "giveup", edit: "edit/profile"
}, failure_app: lambda { |env| [404, {"Content-Type" => "text/plain"}, ["Oops, not found"]] }, module: :devise
end
namespace :sign_out_via, module: "devise" do
devise_for :deletes, sign_out_via: :delete, class_name: "Admin"
devise_for :posts, sign_out_via: :post, class_name: "Admin"
devise_for :gets, sign_out_via: :get, class_name: "Admin"
devise_for :delete_or_posts, sign_out_via: [:delete, :post], class_name: "Admin"
end
get "/set", to: "home#set"
get "/unauthenticated", to: "home#unauthenticated"
get "/custom_strategy/new"
root to: "home#index", via: [:get, :post]
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/config/boot.rb | test/rails_app/config/boot.rb | # frozen_string_literal: true
unless defined?(DEVISE_ORM)
DEVISE_ORM = (ENV["DEVISE_ORM"] || :active_record).to_sym
end
module Devise
module Test
# Detection for minor differences between Rails versions in tests.
def self.rails71_and_up?
!rails70? && Rails::VERSION::MAJOR >= 7
end
def self.rails70_and_up?
Rails::VERSION::MAJOR >= 7
end
def self.rails70?
Rails.version.start_with? '7.0'
end
end
end
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/config/initializers/session_store.rb | test/rails_app/config/initializers/session_store.rb | # frozen_string_literal: true
RailsApp::Application.config.session_store :cookie_store, key: '_rails_app_session'
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/config/initializers/devise.rb | test/rails_app/config/initializers/devise.rb | # frozen_string_literal: true
require "omniauth-facebook"
require "omniauth-openid"
# Assuming you have not yet modified this file, each configuration option below
# is set to its default value. Note that some are commented out while others
# are not: uncommented lines are intended to protect your configuration from
# breaking changes in upgrades (i.e., in the event that future versions of
# Devise change the default values for those options).
#
# Use this hook to configure devise mailer, warden hooks and so forth. The first
# four configuration values can also be set straight in your models.
Devise.setup do |config|
config.secret_key = "d9eb5171c59a4c817f68b0de27b8c1e340c2341b52cdbc60d3083d4e8958532" \
"18dcc5f589cafde048faec956b61f864b9b5513ff9ce29bf9e5d58b0f234f8e3b"
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class with default "from" parameter.
config.mailer_sender = "please-change-me@config-initializers-devise.com"
config.parent_controller = "ApplicationWithFakeEngine"
# Configure the class responsible to send e-mails.
# config.mailer = "Devise::Mailer"
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require "devise/orm/#{DEVISE_ORM}"
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. By default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply hash where the value is a boolean expliciting if authentication
# should be aborted or not if the value is not present. By default is empty.
# config.authentication_keys = [:email]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# config.params_authenticatable = true
# Tell if authentication through HTTP Basic Auth is enabled. False by default.
config.http_authenticatable = true
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. "Application" by default.
# config.http_authentication_realm = "Application"
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
config.stretches = Rails.env.test? ? 1 : 10
# ==> Configuration for :confirmable
# The time you want to give your user to confirm their account. During this time
# they will be able to access your application without confirming. Default is nil.
# When allow_unconfirmed_access_for is zero, the user won't be able to sign in without confirming.
# You can use this to let your user access some features of your application
# without confirming the account, but blocking it after a certain period
# (ie 2 days).
# config.allow_unconfirmed_access_for = 2.days
# Defines which key will be used when confirming an account
# config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# ==> Configuration for :validatable
# Range for password length. Default is 8..72.
# config.password_length = 8..72
# Regex to use to validate the email address
# config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 2.hours
# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
# config.sign_in_after_reset_password = true
# Set up a pepper to generate the encrypted password.
config.pepper = "d142367154e5beacca404b1a6a4f8bc52c6fdcfa3ccc3cf8eb49f3458a688ee6ac3b9fae488432a3bfca863b8a90008368a9f3a3dfbe5a962e64b6ab8f3a3a1a"
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Configure sign_out behavior.
# Sign_out action can be scoped (i.e. /users/sign_out affects only :user scope).
# The default is true, which means any logout action will sign out all active scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists. Default is [:html]
# config.navigational_formats = [:html, :iphone]
# The default HTTP method used to sign out a resource. Default is :get.
# config.sign_out_via = :get
# ==> OmniAuth
config.omniauth :facebook, 'APP_ID', 'APP_SECRET', scope: 'email,offline_access'
config.omniauth :openid
config.omniauth :openid, name: 'google', identifier: 'https://www.google.com/accounts/o8/id'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |warden_config|
# warden_config.failure_app = AnotherApp
# warden_config.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Configuration for :registerable
# When set to false, does not sign a user in automatically after their password is
# changed. Defaults to true, so a user is signed in automatically after changing a password.
# config.sign_in_after_change_password = true
ActiveSupport.on_load(:devise_failure_app) do
require "lazy_load_test_module"
include LazyLoadTestModule
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/config/initializers/inflections.rb | test/rails_app/config/initializers/inflections.rb | # frozen_string_literal: true
ActiveSupport::Inflector.inflections do |inflect|
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/config/initializers/backtrace_silencers.rb | test/rails_app/config/initializers/backtrace_silencers.rb | # frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/config/initializers/secret_token.rb | test/rails_app/config/initializers/secret_token.rb | # frozen_string_literal: true
config = Rails.application.config
config.secret_key_base = 'd588e99efff13a86461fd6ab82327823ad2f8feb5dc217ce652cdd9f0dfc5eb4b5a62a92d24d2574d7d51dfb1ea8dd453ea54e00cf672159a13104a135422a10'
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/config/environments/test.rb | test/rails_app/config/environments/test.rb | # frozen_string_literal: true
RailsApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true
config.public_file_server.headers = {'Cache-Control' => 'public, max-age=3600'}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
if Devise::Test.rails71_and_up?
config.action_dispatch.show_exceptions = :none
else
config.action_dispatch.show_exceptions = false
end
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/config/environments/development.rb | test/rails_app/config/environments/development.rb | # frozen_string_literal: true
RailsApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers.
config.action_dispatch.best_standards_support = :builtin
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
config.assets.debug = true
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/test/rails_app/config/environments/production.rb | test/rails_app/config/environments/production.rb | # frozen_string_literal: true
RailsApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.public_file_server.enabled = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Whether to fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [:subdomain, :uuid]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise.rb | lib/devise.rb | # frozen_string_literal: true
require 'rails'
require 'active_support/core_ext/numeric/time'
require 'active_support/dependencies'
require 'orm_adapter'
require 'set'
require 'securerandom'
require 'responders'
module Devise
autoload :Delegator, 'devise/delegator'
autoload :Encryptor, 'devise/encryptor'
autoload :FailureApp, 'devise/failure_app'
autoload :OmniAuth, 'devise/omniauth'
autoload :Orm, 'devise/orm'
autoload :ParameterFilter, 'devise/parameter_filter'
autoload :ParameterSanitizer, 'devise/parameter_sanitizer'
autoload :TimeInflector, 'devise/time_inflector'
autoload :TokenGenerator, 'devise/token_generator'
module Controllers
autoload :Helpers, 'devise/controllers/helpers'
autoload :Rememberable, 'devise/controllers/rememberable'
autoload :Responder, 'devise/controllers/responder'
autoload :ScopedViews, 'devise/controllers/scoped_views'
autoload :SignInOut, 'devise/controllers/sign_in_out'
autoload :StoreLocation, 'devise/controllers/store_location'
autoload :UrlHelpers, 'devise/controllers/url_helpers'
end
module Hooks
autoload :Proxy, 'devise/hooks/proxy'
end
module Mailers
autoload :Helpers, 'devise/mailers/helpers'
end
module Strategies
autoload :Base, 'devise/strategies/base'
autoload :Authenticatable, 'devise/strategies/authenticatable'
end
module Test
autoload :ControllerHelpers, 'devise/test/controller_helpers'
autoload :IntegrationHelpers, 'devise/test/integration_helpers'
end
# Constants which holds devise configuration for extensions. Those should
# not be modified by the "end user" (this is why they are constants).
ALL = []
CONTROLLERS = {}
ROUTES = {}
STRATEGIES = {}
URL_HELPERS = {}
# Strategies that do not require user input.
NO_INPUT = []
# True values used to check params
TRUE_VALUES = [true, 1, '1', 'on', 'ON', 't', 'T', 'true', 'TRUE']
# Secret key used by the key generator
mattr_accessor :secret_key
@@secret_key = nil
# Custom domain or key for cookies. Not set by default
mattr_accessor :rememberable_options
@@rememberable_options = {}
# The number of times to hash the password.
mattr_accessor :stretches
@@stretches = 12
# The default key used when authenticating over http auth.
mattr_accessor :http_authentication_key
@@http_authentication_key = nil
# Keys used when authenticating a user.
mattr_accessor :authentication_keys
@@authentication_keys = [:email]
# Request keys used when authenticating a user.
mattr_accessor :request_keys
@@request_keys = []
# Keys that should be case-insensitive.
mattr_accessor :case_insensitive_keys
@@case_insensitive_keys = [:email]
# Keys that should have whitespace stripped.
mattr_accessor :strip_whitespace_keys
@@strip_whitespace_keys = [:email]
# If http authentication is enabled by default.
mattr_accessor :http_authenticatable
@@http_authenticatable = false
# If http headers should be returned for ajax requests. True by default.
mattr_accessor :http_authenticatable_on_xhr
@@http_authenticatable_on_xhr = true
# If params authenticatable is enabled by default.
mattr_accessor :params_authenticatable
@@params_authenticatable = true
# The realm used in Http Basic Authentication.
mattr_accessor :http_authentication_realm
@@http_authentication_realm = "Application"
# Email regex used to validate email formats. It asserts that there are no
# @ symbols or whitespaces in either the localpart or the domain, and that
# there is a single @ symbol separating the localpart and the domain.
mattr_accessor :email_regexp
@@email_regexp = /\A[^@\s]+@[^@\s]+\z/
# Range validation for password length
mattr_accessor :password_length
@@password_length = 6..128
# The time the user will be remembered without asking for credentials again.
mattr_accessor :remember_for
@@remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
mattr_accessor :extend_remember_period
@@extend_remember_period = false
# If true, all the remember me tokens are going to be invalidated when the user signs out.
mattr_accessor :expire_all_remember_me_on_sign_out
@@expire_all_remember_me_on_sign_out = true
# Time interval you can access your account before confirming your account.
# nil - allows unconfirmed access for unlimited time
mattr_accessor :allow_unconfirmed_access_for
@@allow_unconfirmed_access_for = 0.days
# Time interval the confirmation token is valid. nil = unlimited
mattr_accessor :confirm_within
@@confirm_within = nil
# Defines which key will be used when confirming an account.
mattr_accessor :confirmation_keys
@@confirmation_keys = [:email]
# Defines if email should be reconfirmable.
mattr_accessor :reconfirmable
@@reconfirmable = true
# Time interval to timeout the user session without activity.
mattr_accessor :timeout_in
@@timeout_in = 30.minutes
# Used to hash the password. Please generate one with rails secret.
mattr_accessor :pepper
@@pepper = nil
# Used to send notification to the original user email when their email is changed.
mattr_accessor :send_email_changed_notification
@@send_email_changed_notification = false
# Used to enable sending notification to user when their password is changed.
mattr_accessor :send_password_change_notification
@@send_password_change_notification = false
# Scoped views. Since it relies on fallbacks to render default views, it's
# turned off by default.
mattr_accessor :scoped_views
@@scoped_views = false
# Defines which strategy can be used to lock an account.
# Values: :failed_attempts, :none
mattr_accessor :lock_strategy
@@lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
mattr_accessor :unlock_keys
@@unlock_keys = [:email]
# Defines which strategy can be used to unlock an account.
# Values: :email, :time, :both
mattr_accessor :unlock_strategy
@@unlock_strategy = :both
# Number of authentication tries before locking an account
mattr_accessor :maximum_attempts
@@maximum_attempts = 20
# Time interval to unlock the account if :time is defined as unlock_strategy.
mattr_accessor :unlock_in
@@unlock_in = 1.hour
# Defines which key will be used when recovering the password for an account
mattr_accessor :reset_password_keys
@@reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key
mattr_accessor :reset_password_within
@@reset_password_within = 6.hours
# When set to false, resetting a password does not automatically sign in a user
mattr_accessor :sign_in_after_reset_password
@@sign_in_after_reset_password = true
# The default scope which is used by warden.
mattr_accessor :default_scope
@@default_scope = nil
# Address which sends Devise e-mails.
mattr_accessor :mailer_sender
@@mailer_sender = nil
# Skip session storage for the following strategies
mattr_accessor :skip_session_storage
@@skip_session_storage = [:http_auth]
# Which formats should be treated as navigational.
mattr_accessor :navigational_formats
@@navigational_formats = ["*/*", :html, :turbo_stream]
# The default responder used by Devise, used to customize status codes with:
#
# `config.responder.error_status`
# `config.responder.redirect_status`
#
# Can be replaced by a custom application responder.
mattr_accessor :responder
@@responder = Devise::Controllers::Responder
# When set to true, signing out a user signs out all other scopes.
mattr_accessor :sign_out_all_scopes
@@sign_out_all_scopes = true
# The default method used while signing out
mattr_accessor :sign_out_via
@@sign_out_via = :delete
# The parent controller all Devise controllers inherits from.
# Defaults to ApplicationController. This should be set early
# in the initialization process and should be set to a string.
mattr_accessor :parent_controller
@@parent_controller = "ApplicationController"
# The parent mailer all Devise mailers inherit from.
# Defaults to ActionMailer::Base. This should be set early
# in the initialization process and should be set to a string.
mattr_accessor :parent_mailer
@@parent_mailer = "ActionMailer::Base"
# The router Devise should use to generate routes. Defaults
# to :main_app. Should be overridden by engines in order
# to provide custom routes.
mattr_accessor :router_name
@@router_name = nil
# Set the OmniAuth path prefix so it can be overridden when
# Devise is used in a mountable engine
mattr_accessor :omniauth_path_prefix
@@omniauth_path_prefix = nil
# Set if we should clean up the CSRF Token on authentication
mattr_accessor :clean_up_csrf_token_on_authentication
@@clean_up_csrf_token_on_authentication = true
# When false, Devise will not attempt to reload routes on eager load.
# This can reduce the time taken to boot the app but if your application
# requires the Devise mappings to be loaded during boot time the application
# won't boot properly.
mattr_accessor :reload_routes
@@reload_routes = true
# PRIVATE CONFIGURATION
# Store scopes mappings.
@@mappings = {}
def self.mappings
# Starting from Rails 8.0, routes are lazy-loaded by default in test and development environments.
# However, Devise's mappings are built during the routes loading phase.
# To ensure it works correctly, we need to load the routes first before accessing @@mappings.
Rails.application.try(:reload_routes_unless_loaded)
@@mappings
end
# OmniAuth configurations.
mattr_reader :omniauth_configs
@@omniauth_configs = {}
# Define a set of modules that are called when a mapping is added.
mattr_reader :helpers
@@helpers = Set.new
@@helpers << Devise::Controllers::Helpers
# Private methods to interface with Warden.
mattr_accessor :warden_config
@@warden_config = nil
@@warden_config_blocks = []
# When true, enter in paranoid mode to avoid user enumeration.
mattr_accessor :paranoid
@@paranoid = false
# When true, warn user if they just used next-to-last attempt of authentication
mattr_accessor :last_attempt_warning
@@last_attempt_warning = true
# Stores the token generator
mattr_accessor :token_generator
@@token_generator = nil
# When set to false, changing a password does not automatically sign in a user
mattr_accessor :sign_in_after_change_password
@@sign_in_after_change_password = true
# Default way to set up Devise. Run rails generate devise_install to create
# a fresh initializer with all configuration values.
def self.setup
yield self
end
class Getter
def initialize(name)
@name = name
end
def get
# TODO: Remove AS::Dependencies usage when dropping support to Rails < 7.
if ActiveSupport::Dependencies.respond_to?(:constantize)
ActiveSupport::Dependencies.constantize(@name)
else
@name.constantize
end
end
end
def self.ref(arg)
# TODO: Remove AS::Dependencies usage when dropping support to Rails < 7.
if ActiveSupport::Dependencies.respond_to?(:reference)
ActiveSupport::Dependencies.reference(arg)
end
Getter.new(arg)
end
def self.available_router_name
router_name || :main_app
end
def self.omniauth_providers
omniauth_configs.keys
end
# Get the mailer class from the mailer reference object.
def self.mailer
@@mailer_ref.get
end
# Set the mailer reference object to access the mailer.
def self.mailer=(class_name)
@@mailer_ref = ref(class_name)
end
self.mailer = "Devise::Mailer"
# Small method that adds a mapping to Devise.
def self.add_mapping(resource, options)
mapping = Devise::Mapping.new(resource, options)
@@mappings[mapping.name] = mapping
@@default_scope ||= mapping.name
@@helpers.each { |h| h.define_helpers(mapping) }
mapping
end
# Register available devise modules. For the standard modules that Devise provides, this method is
# called from lib/devise/modules.rb. Third-party modules need to be added explicitly using this method.
#
# Note that adding a module using this method does not cause it to be used in the authentication
# process. That requires that the module be listed in the arguments passed to the 'devise' method
# in the model class definition.
#
# == Options:
#
# +model+ - String representing the load path to a custom *model* for this module (to autoload.)
# +controller+ - Symbol representing the name of an existing or custom *controller* for this module.
# +route+ - Symbol representing the named *route* helper for this module.
# +strategy+ - Symbol representing if this module got a custom *strategy*.
# +insert_at+ - Integer representing the order in which this module's model will be included
#
# All values, except :model, accept also a boolean and will have the same name as the given module
# name.
#
# == Examples:
#
# Devise.add_module(:party_module)
# Devise.add_module(:party_module, strategy: true, controller: :sessions)
# Devise.add_module(:party_module, model: 'party_module/model')
# Devise.add_module(:party_module, insert_at: 0)
#
def self.add_module(module_name, options = {})
options.assert_valid_keys(:strategy, :model, :controller, :route, :no_input, :insert_at)
ALL.insert (options[:insert_at] || -1), module_name
if strategy = options[:strategy]
strategy = (strategy == true ? module_name : strategy)
STRATEGIES[module_name] = strategy
end
if controller = options[:controller]
controller = (controller == true ? module_name : controller)
CONTROLLERS[module_name] = controller
end
NO_INPUT << strategy if options[:no_input]
if route = options[:route]
case route
when TrueClass
key, value = module_name, []
when Symbol
key, value = route, []
when Hash
key, value = route.keys.first, route.values.flatten
else
raise ArgumentError, ":route should be true, a Symbol or a Hash"
end
URL_HELPERS[key] ||= []
URL_HELPERS[key].concat(value)
URL_HELPERS[key].uniq!
ROUTES[module_name] = key
end
if options[:model]
path = (options[:model] == true ? "devise/models/#{module_name}" : options[:model])
camelized = ActiveSupport::Inflector.camelize(module_name.to_s)
Devise::Models.send(:autoload, camelized.to_sym, path)
end
Devise::Mapping.add_module module_name
end
# Sets warden configuration using a block that will be invoked on warden
# initialization.
#
# Devise.setup do |config|
# config.allow_unconfirmed_access_for = 2.days
#
# config.warden do |warden_config|
# # Configure warden to use other strategies, like oauth.
# warden_config.oauth(:twitter)
# end
# end
def self.warden(&block)
@@warden_config_blocks << block
end
# Specify an OmniAuth provider.
#
# config.omniauth :github, APP_ID, APP_SECRET
#
def self.omniauth(provider, *args)
config = Devise::OmniAuth::Config.new(provider, args)
@@omniauth_configs[config.strategy_name.to_sym] = config
end
# Include helpers in the given scope to AC and AV.
def self.include_helpers(scope)
ActiveSupport.on_load(:action_controller) do
include scope::Helpers if defined?(scope::Helpers)
include scope::UrlHelpers
end
ActiveSupport.on_load(:action_view) do
include scope::UrlHelpers
end
end
# Regenerates url helpers considering Devise.mapping
def self.regenerate_helpers!
Devise::Controllers::UrlHelpers.remove_helpers!
Devise::Controllers::UrlHelpers.generate_helpers!
end
# A method used internally to complete the setup of warden manager after routes are loaded.
# See lib/devise/rails/routes.rb - ActionDispatch::Routing::RouteSet#finalize_with_devise!
def self.configure_warden! #:nodoc:
@@warden_configured ||= begin
warden_config.failure_app = Devise::Delegator.new
warden_config.default_scope = Devise.default_scope
warden_config.intercept_401 = false
Devise.mappings.each_value do |mapping|
warden_config.scope_defaults mapping.name, strategies: mapping.strategies
warden_config.serialize_into_session(mapping.name) do |record|
mapping.to.serialize_into_session(record)
end
warden_config.serialize_from_session(mapping.name) do |args|
mapping.to.serialize_from_session(*args)
end
end
@@warden_config_blocks.map { |block| block.call Devise.warden_config }
true
end
end
# Generate a friendly string randomly to be used as token.
# By default, length is 20 characters.
def self.friendly_token(length = 20)
# To calculate real characters, we must perform this operation.
# See SecureRandom.urlsafe_base64
rlength = (length * 3) / 4
SecureRandom.urlsafe_base64(rlength).tr('lIO0', 'sxyz')
end
# constant-time comparison algorithm to prevent timing attacks
def self.secure_compare(a, b)
return false if a.nil? || b.nil?
ActiveSupport::SecurityUtils.secure_compare(a, b)
end
def self.deprecator
@deprecator ||= ActiveSupport::Deprecation.new("5.0", "Devise")
end
end
require 'warden'
require 'devise/mapping'
require 'devise/models'
require 'devise/modules'
require 'devise/rails'
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/mongoid/devise_generator.rb | lib/generators/mongoid/devise_generator.rb | # frozen_string_literal: true
require 'rails/generators/named_base'
require 'generators/devise/orm_helpers'
module Mongoid
module Generators
class DeviseGenerator < Rails::Generators::NamedBase
include Devise::Generators::OrmHelpers
def generate_model
invoke "mongoid:model", [name] unless model_exists? && behavior == :invoke
end
def inject_field_types
inject_into_file model_path, migration_data, after: "include Mongoid::Document\n" if model_exists?
end
def inject_devise_content
inject_into_file model_path, model_contents, after: "include Mongoid::Document\n" if model_exists?
end
def migration_data
<<RUBY
## Database authenticatable
field :email, type: String, default: ""
field :encrypted_password, type: String, default: ""
## Recoverable
field :reset_password_token, type: String
field :reset_password_sent_at, type: Time
## Rememberable
field :remember_created_at, type: Time
## Trackable
# field :sign_in_count, type: Integer, default: 0
# field :current_sign_in_at, type: Time
# field :last_sign_in_at, type: Time
# field :current_sign_in_ip, type: String
# field :last_sign_in_ip, type: String
## Confirmable
# field :confirmation_token, type: String
# field :confirmed_at, type: Time
# field :confirmation_sent_at, type: Time
# field :unconfirmed_email, type: String # Only if using reconfirmable
## Lockable
# field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
# field :unlock_token, type: String # Only if unlock strategy is :email or :both
# field :locked_at, type: Time
RUBY
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/devise/orm_helpers.rb | lib/generators/devise/orm_helpers.rb | # frozen_string_literal: true
module Devise
module Generators
module OrmHelpers
def model_contents
buffer = <<-CONTENT
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
CONTENT
buffer
end
private
def model_exists?
File.exist?(File.join(destination_root, model_path))
end
def migration_exists?(table_name)
Dir.glob("#{File.join(destination_root, migration_path)}/[0-9]*_*.rb").grep(/\d+_add_devise_to_#{table_name}.rb$/).first
end
def migration_path
if Rails.version >= '5.0.3'
db_migrate_path
else
@migration_path ||= File.join("db", "migrate")
end
end
def model_path
@model_path ||= File.join("app", "models", "#{file_path}.rb")
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/devise/controllers_generator.rb | lib/generators/devise/controllers_generator.rb | # frozen_string_literal: true
require 'rails/generators/base'
module Devise
module Generators
class ControllersGenerator < Rails::Generators::Base
CONTROLLERS = %w(confirmations passwords registrations sessions unlocks omniauth_callbacks).freeze
desc <<-DESC.strip_heredoc
Create inherited Devise controllers in your app/controllers folder.
Use -c to specify which controller you want to overwrite.
If you do not specify a controller, all controllers will be created.
For example:
rails generate devise:controllers users -c=sessions
This will create a controller class at app/controllers/users/sessions_controller.rb like this:
class Users::SessionsController < Devise::SessionsController
content...
end
DESC
source_root File.expand_path("../../templates/controllers", __FILE__)
argument :scope, required: true,
desc: "The scope to create controllers in, e.g. users, admins"
class_option :controllers, aliases: "-c", type: :array,
desc: "Select specific controllers to generate (#{CONTROLLERS.join(', ')})"
def create_controllers
@scope_prefix = scope.blank? ? '' : (scope.camelize + '::')
controllers = options[:controllers] || CONTROLLERS
controllers.each do |name|
template "#{name}_controller.rb",
"app/controllers/#{scope}/#{name}_controller.rb"
end
end
def show_readme
readme "README" if behavior == :invoke
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/devise/views_generator.rb | lib/generators/devise/views_generator.rb | # frozen_string_literal: true
require 'rails/generators/base'
module Devise
module Generators
# Include this module in your generator to generate Devise views.
# `copy_views` is the main method and by default copies all views
# with forms.
module ViewPathTemplates #:nodoc:
extend ActiveSupport::Concern
included do
argument :scope, required: false, default: nil,
desc: "The scope to copy views to"
# Le sigh, ensure Thor won't handle opts as args
# It should be fixed in future Rails releases
class_option :form_builder, aliases: "-b"
class_option :markerb
class_option :views, aliases: "-v", type: :array, desc: "Select specific view directories to generate (confirmations, passwords, registrations, sessions, unlocks, mailer)"
public_task :copy_views
end
def copy_views
if options[:views]
options[:views].each do |directory|
view_directory directory.to_sym
end
else
view_directory :confirmations
view_directory :passwords
view_directory :registrations
view_directory :sessions
view_directory :unlocks
end
end
protected
def view_directory(name, _target_path = nil)
directory name.to_s, _target_path || "#{target_path}/#{name}" do |content|
if scope
content.gsub("devise/shared", "#{plural_scope}/shared")
else
content
end
end
end
def target_path
@target_path ||= "app/views/#{plural_scope || :devise}"
end
def plural_scope
@plural_scope ||= scope.presence && scope.underscore.pluralize
end
end
class SharedViewsGenerator < Rails::Generators::Base #:nodoc:
include ViewPathTemplates
source_root File.expand_path("../../../../app/views/devise", __FILE__)
desc "Copies shared Devise views to your application."
hide!
# Override copy_views to just copy mailer and shared.
def copy_views
view_directory :shared
end
end
class FormForGenerator < Rails::Generators::Base #:nodoc:
include ViewPathTemplates
source_root File.expand_path("../../../../app/views/devise", __FILE__)
desc "Copies default Devise views to your application."
hide!
end
class SimpleFormForGenerator < Rails::Generators::Base #:nodoc:
include ViewPathTemplates
source_root File.expand_path("../../templates/simple_form_for", __FILE__)
desc "Copies simple form enabled views to your application."
hide!
def copy_views
if options[:views]
options[:views].delete('mailer')
end
super
end
end
class ErbGenerator < Rails::Generators::Base #:nodoc:
include ViewPathTemplates
source_root File.expand_path("../../../../app/views/devise", __FILE__)
desc "Copies Devise mail erb views to your application."
hide!
def copy_views
if !options[:views] || options[:views].include?('mailer')
view_directory :mailer
end
end
end
class MarkerbGenerator < Rails::Generators::Base #:nodoc:
include ViewPathTemplates
source_root File.expand_path("../../templates", __FILE__)
desc "Copies Devise mail markerb views to your application."
hide!
def copy_views
if !options[:views] || options[:views].include?('mailer')
view_directory :markerb, target_path
end
end
def target_path
"app/views/#{plural_scope || :devise}/mailer"
end
end
class ViewsGenerator < Rails::Generators::Base
desc "Copies Devise views to your application."
argument :scope, required: false, default: nil,
desc: "The scope to copy views to"
invoke SharedViewsGenerator
hook_for :form_builder, aliases: "-b",
desc: "Form builder to be used",
default: defined?(SimpleForm) ? "simple_form_for" : "form_for"
hook_for :markerb, desc: "Generate markerb instead of erb mail views",
default: defined?(Markerb),
type: :boolean
hook_for :erb, desc: "Generate erb mail views",
default: !defined?(Markerb),
type: :boolean
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/devise/devise_generator.rb | lib/generators/devise/devise_generator.rb | # frozen_string_literal: true
require 'rails/generators/named_base'
module Devise
module Generators
class DeviseGenerator < Rails::Generators::NamedBase
include Rails::Generators::ResourceHelpers
namespace "devise"
source_root File.expand_path("../templates", __FILE__)
desc "Generates a model with the given NAME (if one does not exist) with devise " \
"configuration plus a migration file and devise routes."
hook_for :orm, required: true
class_option :routes, desc: "Generate routes", type: :boolean, default: true
def add_devise_routes
devise_route = "devise_for :#{plural_name}".dup
devise_route << %Q(, class_name: "#{class_name}") if class_name.include?("::")
devise_route << %Q(, skip: :all) unless options.routes?
route devise_route
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/devise/install_generator.rb | lib/generators/devise/install_generator.rb | # frozen_string_literal: true
require 'rails/generators/base'
require 'securerandom'
module Devise
module Generators
MissingORMError = Class.new(Thor::Error)
class InstallGenerator < Rails::Generators::Base
source_root File.expand_path("../../templates", __FILE__)
desc "Creates a Devise initializer and copy locale files to your application."
class_option :orm, required: true
def copy_initializer
unless options[:orm]
raise MissingORMError, <<-ERROR.strip_heredoc
An ORM must be set to install Devise in your application.
Be sure to have an ORM like Active Record or Mongoid loaded in your
app or configure your own at `config/application.rb`.
config.generators do |g|
g.orm :your_orm_gem
end
ERROR
end
template "devise.rb", "config/initializers/devise.rb"
end
def copy_locale
copy_file "../../../config/locales/en.yml", "config/locales/devise.en.yml"
end
def show_readme
readme "README" if behavior == :invoke
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/templates/devise.rb | lib/generators/templates/devise.rb | # frozen_string_literal: true
# Assuming you have not yet modified this file, each configuration option below
# is set to its default value. Note that some are commented out while others
# are not: uncommented lines are intended to protect your configuration from
# breaking changes in upgrades (i.e., in the event that future versions of
# Devise change the default values for those options).
#
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# Devise will use the `secret_key_base` as its `secret_key`
# by default. You can change it below and use your own secret key.
# config.secret_key = '<%= SecureRandom.hex(64) %>'
# ==> Controller configuration
# Configure the parent class to the devise controllers.
# config.parent_controller = 'DeviseController'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# Configure the parent class responsible to send e-mails.
# config.parent_mailer = 'ActionMailer::Base'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/<%= options[:orm] %>'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [:email]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication.
# For API-only applications to support authentication "out-of-the-box", you will likely want to
# enable this with :database unless you are using a custom strategy.
# The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If 401 status code should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# When false, Devise will not attempt to reload routes on eager load.
# This can reduce the time taken to boot the app but if your application
# requires the Devise mappings to be loaded during boot time the application
# won't boot properly.
# config.reload_routes = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 12. If
# using other algorithms, it sets how many times you want the password to be hashed.
# The number of stretches used for generating the hashed password are stored
# with the hashed password. This allows you to change the stretches without
# invalidating existing passwords.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# algorithm), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 12
# Set up a pepper to generate the hashed password.
# config.pepper = '<%= SecureRandom.hex(64) %>'
# Send a notification to the original email when the user's email is changed.
# config.send_email_changed_notification = false
# Send a notification email when the user's password is changed.
# config.send_password_change_notification = false
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day.
# You can also set it to nil, which will allow the user to access the website
# without confirming their account.
# Default is 0.days, meaning the user cannot access the website without
# confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
# Also, when used in conjunction with `send_email_changed_notification`,
# the notification is sent to the original email when the change is requested,
# not when the unconfirmed email is confirmed.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
# config.sign_in_after_reset_password = true
# ==> Configuration for :encryptable
# Allow you to use another hashing or encryption algorithm besides bcrypt (default).
# You can use :sha1, :sha512 or algorithms from others authentication tools as
# :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
# for default behavior) and :restful_authentication_sha1 (then you should set
# stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html, :turbo_stream]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |warden_config|
# warden_config.intercept_401 = false
# warden_config.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
# ==> Hotwire/Turbo configuration
# When using Devise with Hotwire/Turbo, the http status for error responses
# and some redirects must match the following. The default in Devise for existing
# apps is `200 OK` and `302 Found` respectively, but new apps are generated with
# these new defaults that match Hotwire/Turbo behavior.
# Note: These might become the new default in future versions of Devise.
config.responder.error_status = <%= Rack::Utils::SYMBOL_TO_STATUS_CODE.key(422).inspect %>
config.responder.redirect_status = :see_other
# ==> Configuration for :registerable
# When set to false, does not sign a user in automatically after their password is
# changed. Defaults to true, so a user is signed in automatically after changing a password.
# config.sign_in_after_change_password = true
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/templates/controllers/omniauth_callbacks_controller.rb | lib/generators/templates/controllers/omniauth_callbacks_controller.rb | # frozen_string_literal: true
class <%= @scope_prefix %>OmniauthCallbacksController < Devise::OmniauthCallbacksController
# You should configure your model like this:
# devise :omniauthable, omniauth_providers: [:twitter]
# You should also create an action method in this controller like this:
# def twitter
# end
# More info at:
# https://github.com/heartcombo/devise#omniauth
# GET|POST /resource/auth/twitter
# def passthru
# super
# end
# GET|POST /users/auth/twitter/callback
# def failure
# super
# end
# protected
# The path used when OmniAuth fails
# def after_omniauth_failure_path_for(scope)
# super(scope)
# end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/templates/controllers/passwords_controller.rb | lib/generators/templates/controllers/passwords_controller.rb | # frozen_string_literal: true
class <%= @scope_prefix %>PasswordsController < Devise::PasswordsController
# GET /resource/password/new
# def new
# super
# end
# POST /resource/password
# def create
# super
# end
# GET /resource/password/edit?reset_password_token=abcdef
# def edit
# super
# end
# PUT /resource/password
# def update
# super
# end
# protected
# def after_resetting_password_path_for(resource)
# super(resource)
# end
# The path used after sending reset password instructions
# def after_sending_reset_password_instructions_path_for(resource_name)
# super(resource_name)
# end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/templates/controllers/unlocks_controller.rb | lib/generators/templates/controllers/unlocks_controller.rb | # frozen_string_literal: true
class <%= @scope_prefix %>UnlocksController < Devise::UnlocksController
# GET /resource/unlock/new
# def new
# super
# end
# POST /resource/unlock
# def create
# super
# end
# GET /resource/unlock?unlock_token=abcdef
# def show
# super
# end
# protected
# The path used after sending unlock password instructions
# def after_sending_unlock_instructions_path_for(resource)
# super(resource)
# end
# The path used after unlocking the resource
# def after_unlock_path_for(resource)
# super(resource)
# end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/templates/controllers/registrations_controller.rb | lib/generators/templates/controllers/registrations_controller.rb | # frozen_string_literal: true
class <%= @scope_prefix %>RegistrationsController < Devise::RegistrationsController
# before_action :configure_sign_up_params, only: [:create]
# before_action :configure_account_update_params, only: [:update]
# GET /resource/sign_up
# def new
# super
# end
# POST /resource
# def create
# super
# end
# GET /resource/edit
# def edit
# super
# end
# PUT /resource
# def update
# super
# end
# DELETE /resource
# def destroy
# super
# end
# GET /resource/cancel
# Forces the session data which is usually expired after sign
# in to be expired now. This is useful if the user wants to
# cancel oauth signing in/up in the middle of the process,
# removing all OAuth session data.
# def cancel
# super
# end
# protected
# If you have extra params to permit, append them to the sanitizer.
# def configure_sign_up_params
# devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute])
# end
# If you have extra params to permit, append them to the sanitizer.
# def configure_account_update_params
# devise_parameter_sanitizer.permit(:account_update, keys: [:attribute])
# end
# The path used after sign up.
# def after_sign_up_path_for(resource)
# super(resource)
# end
# The path used after sign up for inactive accounts.
# def after_inactive_sign_up_path_for(resource)
# super(resource)
# end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/templates/controllers/confirmations_controller.rb | lib/generators/templates/controllers/confirmations_controller.rb | # frozen_string_literal: true
class <%= @scope_prefix %>ConfirmationsController < Devise::ConfirmationsController
# GET /resource/confirmation/new
# def new
# super
# end
# POST /resource/confirmation
# def create
# super
# end
# GET /resource/confirmation?confirmation_token=abcdef
# def show
# super
# end
# protected
# The path used after resending confirmation instructions.
# def after_resending_confirmation_instructions_path_for(resource_name)
# super(resource_name)
# end
# The path used after confirmation.
# def after_confirmation_path_for(resource_name, resource)
# super(resource_name, resource)
# end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/templates/controllers/sessions_controller.rb | lib/generators/templates/controllers/sessions_controller.rb | # frozen_string_literal: true
class <%= @scope_prefix %>SessionsController < Devise::SessionsController
# before_action :configure_sign_in_params, only: [:create]
# GET /resource/sign_in
# def new
# super
# end
# POST /resource/sign_in
# def create
# super
# end
# DELETE /resource/sign_out
# def destroy
# super
# end
# protected
# If you have extra params to permit, append them to the sanitizer.
# def configure_sign_in_params
# devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
# end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/active_record/devise_generator.rb | lib/generators/active_record/devise_generator.rb | # frozen_string_literal: true
require 'rails/generators/active_record'
require 'generators/devise/orm_helpers'
module ActiveRecord
module Generators
class DeviseGenerator < Base
argument :attributes, type: :array, default: [], banner: "field:type field:type"
class_option :primary_key_type, type: :string, desc: "The type for primary key"
include Devise::Generators::OrmHelpers
source_root File.expand_path("../templates", __FILE__)
def copy_devise_migration
if (behavior == :invoke && model_exists?) || (behavior == :revoke && migration_exists?(table_name))
migration_template "migration_existing.rb", "#{migration_path}/add_devise_to_#{table_name}.rb", migration_version: migration_version
else
migration_template "migration.rb", "#{migration_path}/devise_create_#{table_name}.rb", migration_version: migration_version
end
end
def generate_model
invoke "active_record:model", [name], migration: false unless model_exists? && behavior == :invoke
end
def inject_devise_content
content = model_contents
class_path = if namespaced?
class_name.to_s.split("::")
else
[class_name]
end
indent_depth = class_path.size - 1
content = content.split("\n").map { |line| " " * indent_depth + line } .join("\n") << "\n"
inject_into_class(model_path, class_path.last, content) if model_exists?
end
def migration_data
<<RUBY
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
# t.integer :sign_in_count, default: 0, null: false
# t.datetime :current_sign_in_at
# t.datetime :last_sign_in_at
# t.#{ip_column} :current_sign_in_ip
# t.#{ip_column} :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
RUBY
end
def ip_column
# Padded with spaces so it aligns nicely with the rest of the columns.
"%-8s" % (inet? ? "inet" : "string")
end
def inet?
postgresql?
end
def rails61_and_up?
Rails::VERSION::MAJOR > 6 || (Rails::VERSION::MAJOR == 6 && Rails::VERSION::MINOR >= 1)
end
def postgresql?
ar_config && ar_config['adapter'] == 'postgresql'
end
def ar_config
if ActiveRecord::Base.configurations.respond_to?(:configs_for)
if rails61_and_up?
ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, name: "primary").configuration_hash
else
ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: "primary").config
end
else
ActiveRecord::Base.configurations[Rails.env]
end
end
def migration_version
"[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]"
end
def primary_key_type
primary_key_string
end
def primary_key_string
key_string = options[:primary_key_type]
", id: :#{key_string}" if key_string
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/active_record/templates/migration_existing.rb | lib/generators/active_record/templates/migration_existing.rb | # frozen_string_literal: true
class AddDeviseTo<%= table_name.camelize %> < ActiveRecord::Migration<%= migration_version %>
def self.up
change_table :<%= table_name %> do |t|
<%= migration_data -%>
<% attributes.each do |attribute| -%>
t.<%= attribute.type %> :<%= attribute.name %>
<% end -%>
# Uncomment below if timestamps were not included in your original model.
# t.timestamps null: false
end
add_index :<%= table_name %>, :email, unique: true
add_index :<%= table_name %>, :reset_password_token, unique: true
# add_index :<%= table_name %>, :confirmation_token, unique: true
# add_index :<%= table_name %>, :unlock_token, unique: true
end
def self.down
# By default, we don't want to make any assumption about how to roll back a migration when your
# model already existed. Please edit below which fields you would like to remove in this migration.
raise ActiveRecord::IrreversibleMigration
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/generators/active_record/templates/migration.rb | lib/generators/active_record/templates/migration.rb | # frozen_string_literal: true
class DeviseCreate<%= table_name.camelize %> < ActiveRecord::Migration<%= migration_version %>
def change
create_table :<%= table_name %><%= primary_key_type %> do |t|
<%= migration_data -%>
<% attributes.each do |attribute| -%>
t.<%= attribute.type %> :<%= attribute.name %>
<% end -%>
t.timestamps null: false
end
add_index :<%= table_name %>, :email, unique: true
add_index :<%= table_name %>, :reset_password_token, unique: true
# add_index :<%= table_name %>, :confirmation_token, unique: true
# add_index :<%= table_name %>, :unlock_token, unique: true
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/version.rb | lib/devise/version.rb | # frozen_string_literal: true
module Devise
VERSION = "5.0.0.rc".freeze
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/rails.rb | lib/devise/rails.rb | # frozen_string_literal: true
require 'devise/rails/routes'
require 'devise/rails/warden_compat'
module Devise
class Engine < ::Rails::Engine
config.devise = Devise
# Initialize Warden and copy its configurations.
config.app_middleware.use Warden::Manager do |config|
Devise.warden_config = config
end
# Force routes to be loaded if we are doing any eager load.
config.before_eager_load do |app|
app.reload_routes! if Devise.reload_routes
end
initializer "devise.deprecator" do |app|
app.deprecators[:devise] = Devise.deprecator if app.respond_to?(:deprecators)
end
initializer "devise.url_helpers" do
Devise.include_helpers(Devise::Controllers)
end
initializer "devise.omniauth", after: :load_config_initializers, before: :build_middleware_stack do |app|
Devise.omniauth_configs.each do |provider, config|
app.middleware.use config.strategy_class, *config.args do |strategy|
config.strategy = strategy
end
end
if Devise.omniauth_configs.any?
Devise.include_helpers(Devise::OmniAuth)
end
end
initializer "devise.secret_key" do |app|
Devise.secret_key ||= app.secret_key_base
Devise.token_generator ||=
if secret_key = Devise.secret_key
Devise::TokenGenerator.new(
ActiveSupport::CachingKeyGenerator.new(ActiveSupport::KeyGenerator.new(secret_key))
)
end
end
initializer "devise.configure_zeitwerk" do
if Rails.autoloaders.zeitwerk_enabled? && !defined?(ActionMailer)
Rails.autoloaders.main.ignore("#{root}/app/mailers/devise/mailer.rb")
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/orm.rb | lib/devise/orm.rb | # frozen_string_literal: true
module Devise
module Orm # :nodoc:
def self.active_record?(model)
defined?(ActiveRecord) && model < ActiveRecord::Base
end
def self.included(model)
if Devise::Orm.active_record?(model)
model.include DirtyTrackingActiveRecordMethods
else
model.include DirtyTrackingMongoidMethods
end
end
module DirtyTrackingActiveRecordMethods
def devise_email_before_last_save
email_before_last_save
end
def devise_email_in_database
email_in_database
end
def devise_saved_change_to_email?
saved_change_to_email?
end
def devise_saved_change_to_encrypted_password?
saved_change_to_encrypted_password?
end
def devise_will_save_change_to_email?
will_save_change_to_email?
end
def devise_respond_to_and_will_save_change_to_attribute?(attribute)
respond_to?("will_save_change_to_#{attribute}?") && send("will_save_change_to_#{attribute}?")
end
end
module DirtyTrackingMongoidMethods
def devise_email_before_last_save
respond_to?(:email_previously_was) ? email_previously_was : email_was
end
def devise_email_in_database
email_was
end
def devise_saved_change_to_email?
respond_to?(:email_previously_changed?) ? email_previously_changed? : email_changed?
end
def devise_saved_change_to_encrypted_password?
respond_to?(:encrypted_password_previously_changed?) ? encrypted_password_previously_changed? : encrypted_password_changed?
end
def devise_will_save_change_to_email?
email_changed?
end
def devise_respond_to_and_will_save_change_to_attribute?(attribute)
respond_to?("#{attribute}_changed?") && send("#{attribute}_changed?")
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/delegator.rb | lib/devise/delegator.rb | # frozen_string_literal: true
module Devise
# Checks the scope in the given environment and returns the associated failure app.
class Delegator
def call(env)
failure_app(env).call(env)
end
def failure_app(env)
app = env["warden.options"] &&
(scope = env["warden.options"][:scope]) &&
Devise.mappings[scope.to_sym].failure_app
app || Devise::FailureApp
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/mapping.rb | lib/devise/mapping.rb | # frozen_string_literal: true
module Devise
# Responsible for handling devise mappings and routes configuration. Each
# resource configured by devise_for in routes is actually creating a mapping
# object. You can refer to devise_for in routes for usage options.
#
# The required value in devise_for is actually not used internally, but it's
# inflected to find all other values.
#
# map.devise_for :users
# mapping = Devise.mappings[:user]
#
# mapping.name #=> :user
# # is the scope used in controllers and warden, given in the route as :singular.
#
# mapping.as #=> "users"
# # how the mapping should be search in the path, given in the route as :as.
#
# mapping.to #=> User
# # is the class to be loaded from routes, given in the route as :class_name.
#
# mapping.modules #=> [:authenticatable]
# # is the modules included in the class
#
class Mapping #:nodoc:
attr_reader :singular, :scoped_path, :path, :controllers, :path_names,
:class_name, :sign_out_via, :format, :used_routes, :used_helpers,
:failure_app, :router_name
alias :name :singular
# Receives an object and finds a scope for it. If a scope cannot be found,
# raises an error. If a symbol is given, it's considered to be the scope.
def self.find_scope!(obj)
obj = obj.devise_scope if obj.respond_to?(:devise_scope)
case obj
when String, Symbol
return obj.to_sym
when Class
Devise.mappings.each_value { |m| return m.name if obj <= m.to }
else
Devise.mappings.each_value { |m| return m.name if obj.is_a?(m.to) }
end
raise "Could not find a valid mapping for #{obj.inspect}"
end
def self.find_by_path!(path, path_type = :fullpath)
Devise.mappings.each_value { |m| return m if path.include?(m.send(path_type)) }
raise "Could not find a valid mapping for path #{path.inspect}"
end
def initialize(name, options) #:nodoc:
@scoped_path = options[:as] ? "#{options[:as]}/#{name}" : name.to_s
@singular = (options[:singular] || @scoped_path.tr('/', '_').singularize).to_sym
@class_name = (options[:class_name] || name.to_s.classify).to_s
@klass = Devise.ref(@class_name)
@path = (options[:path] || name).to_s
@path_prefix = options[:path_prefix]
@sign_out_via = options[:sign_out_via] || Devise.sign_out_via
@format = options[:format]
@router_name = options[:router_name]
default_failure_app(options)
default_controllers(options)
default_path_names(options)
default_used_route(options)
default_used_helpers(options)
end
# Return modules for the mapping.
def modules
@modules ||= to.respond_to?(:devise_modules) ? to.devise_modules : []
end
# Gives the class the mapping points to.
def to
@klass.get
end
def strategies
@strategies ||= STRATEGIES.values_at(*self.modules).compact.uniq.reverse
end
def no_input_strategies
self.strategies & Devise::NO_INPUT
end
def routes
@routes ||= ROUTES.values_at(*self.modules).compact.uniq
end
def authenticatable?
@authenticatable ||= self.modules.any? { |m| m.to_s =~ /authenticatable/ }
end
def fullpath
"/#{@path_prefix}/#{@path}".squeeze("/")
end
# Create magic predicates for verifying what module is activated by this map.
# Example:
#
# def confirmable?
# self.modules.include?(:confirmable)
# end
#
def self.add_module(m)
class_eval <<-METHOD, __FILE__, __LINE__ + 1
def #{m}?
self.modules.include?(:#{m})
end
METHOD
end
private
def default_failure_app(options)
@failure_app = options[:failure_app] || Devise::FailureApp
if @failure_app.is_a?(String)
ref = Devise.ref(@failure_app)
@failure_app = lambda { |env| ref.get.call(env) }
end
end
def default_controllers(options)
mod = options[:module] || "devise"
@controllers = Hash.new { |h,k| h[k] = "#{mod}/#{k}" }
@controllers.merge!(options[:controllers]) if options[:controllers]
@controllers.each { |k,v| @controllers[k] = v.to_s }
end
def default_path_names(options)
@path_names = Hash.new { |h,k| h[k] = k.to_s }
@path_names[:registration] = ""
@path_names.merge!(options[:path_names]) if options[:path_names]
end
def default_constraints(options)
@constraints = Hash.new
@constraints.merge!(options[:constraints]) if options[:constraints]
end
def default_defaults(options)
@defaults = Hash.new
@defaults.merge!(options[:defaults]) if options[:defaults]
end
def default_used_route(options)
singularizer = lambda { |s| s.to_s.singularize.to_sym }
if options.has_key?(:only)
@used_routes = self.routes & Array(options[:only]).map(&singularizer)
elsif options[:skip] == :all
@used_routes = []
else
@used_routes = self.routes - Array(options[:skip]).map(&singularizer)
end
end
def default_used_helpers(options)
singularizer = lambda { |s| s.to_s.singularize.to_sym }
if options[:skip_helpers] == true
@used_helpers = @used_routes
elsif skip = options[:skip_helpers]
@used_helpers = self.routes - Array(skip).map(&singularizer)
else
@used_helpers = self.routes
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/parameter_filter.rb | lib/devise/parameter_filter.rb | # frozen_string_literal: true
module Devise
class ParameterFilter
def initialize(case_insensitive_keys, strip_whitespace_keys)
@case_insensitive_keys = case_insensitive_keys || []
@strip_whitespace_keys = strip_whitespace_keys || []
end
def filter(conditions)
conditions = stringify_params(conditions.dup)
conditions.merge!(filtered_hash_by_method_for_given_keys(conditions.dup, :downcase, @case_insensitive_keys))
conditions.merge!(filtered_hash_by_method_for_given_keys(conditions.dup, :strip, @strip_whitespace_keys))
conditions
end
def filtered_hash_by_method_for_given_keys(conditions, method, condition_keys)
condition_keys.each do |k|
next unless conditions.key?(k)
value = conditions[k]
conditions[k] = value.send(method) if value.respond_to?(method)
end
conditions
end
# Force keys to be string to avoid injection on mongoid related database.
def stringify_params(conditions)
return conditions unless conditions.is_a?(Hash)
conditions.each do |k, v|
conditions[k] = v.to_s if param_requires_string_conversion?(v)
end
end
private
def param_requires_string_conversion?(value)
true
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/failure_app.rb | lib/devise/failure_app.rb | # frozen_string_literal: true
require "action_controller/metal"
module Devise
# Failure application that will be called every time :warden is thrown from
# any strategy or hook. It is responsible for redirecting the user to the sign
# in page based on current scope and mapping. If no scope is given, it
# redirects to the default_url.
class FailureApp < ActionController::Metal
include ActionController::UrlFor
include ActionController::Redirecting
include Rails.application.routes.url_helpers
include Rails.application.routes.mounted_helpers
include Devise::Controllers::StoreLocation
delegate :flash, to: :request
include AbstractController::Callbacks
around_action do |failure_app, action|
I18n.with_locale(failure_app.i18n_locale, &action)
end
def self.call(env)
@respond ||= action(:respond)
@respond.call(env)
end
# Try retrieving the URL options from the parent controller (usually
# ApplicationController). Instance methods are not supported at the moment,
# so only the class-level attribute is used.
def self.default_url_options(*args)
if defined?(Devise.parent_controller.constantize)
Devise.parent_controller.constantize.try(:default_url_options) || {}
else
{}
end
end
def respond
if http_auth?
http_auth
elsif warden_options[:recall]
recall
else
redirect
end
end
def http_auth
self.status = 401
self.headers["WWW-Authenticate"] = %(Basic realm=#{Devise.http_authentication_realm.inspect}) if http_auth_header?
self.content_type = request.format.to_s
self.response_body = http_auth_body
end
def recall
header_info = if relative_url_root?
base_path = Pathname.new(relative_url_root)
full_path = Pathname.new(attempted_path)
{ "SCRIPT_NAME" => relative_url_root,
"PATH_INFO" => '/' + full_path.relative_path_from(base_path).to_s }
else
{ "PATH_INFO" => attempted_path }
end
header_info.each do | var, value|
if request.respond_to?(:set_header)
request.set_header(var, value)
else
request.env[var] = value
end
end
flash.now[:alert] = i18n_message(:invalid) if is_flashing_format?
self.response = recall_app(warden_options[:recall]).call(request.env).tap { |response|
status = response[0].in?(300..399) ? Devise.responder.redirect_status : Devise.responder.error_status
# Avoid warnings translating status to code using Rails if available (e.g. `unprocessable_entity` => `unprocessable_content`)
response[0] = ActionDispatch::Response.try(:rack_status_code, status) || Rack::Utils.status_code(status)
}
end
def redirect
store_location!
if is_flashing_format?
if flash[:timedout] && flash[:alert]
flash.keep(:timedout)
flash.keep(:alert)
else
flash[:alert] = i18n_message
end
end
redirect_to redirect_url
end
protected
def i18n_options(options)
options
end
def i18n_message(default = nil)
message = warden_message || default || :unauthenticated
if message.is_a?(Symbol)
options = {}
options[:resource_name] = scope
options[:scope] = "devise.failure"
options[:default] = [message]
auth_keys = scope_class.authentication_keys
human_keys = (auth_keys.respond_to?(:keys) ? auth_keys.keys : auth_keys).map { |key|
scope_class.human_attribute_name(key).downcase
}
options[:authentication_keys] = human_keys.join(I18n.t(:"support.array.words_connector"))
options = i18n_options(options)
I18n.t(:"#{scope}.#{message}", **options).then { |msg|
# Ensure that auth keys at the start of the translated string are properly cased.
msg.start_with?(human_keys.first) ? msg.upcase_first : msg
}
else
message.to_s
end
end
def i18n_locale
warden_options[:locale]
end
def redirect_url
if warden_message == :timeout
flash[:timedout] = true if is_flashing_format?
path = if request.get?
attempted_path
else
request.referrer
end
path || scope_url
else
scope_url
end
end
def route(scope)
:"new_#{scope}_session_url"
end
def scope_url
opts = {}
# Initialize script_name with nil to prevent infinite loops in
# authenticated mounted engines
opts[:script_name] = nil
route = route(scope)
opts[:format] = request_format unless skip_format?
router_name = Devise.mappings[scope].router_name || Devise.available_router_name
context = send(router_name)
if relative_url_root?
opts[:script_name] = relative_url_root
end
if context.respond_to?(route)
context.send(route, opts)
elsif respond_to?(:root_url)
root_url(opts)
else
"/"
end
end
def skip_format?
%w(html */* turbo_stream).include? request_format.to_s
end
# Choose whether we should respond in an HTTP authentication fashion,
# including 401 and optional headers.
#
# This method allows the user to explicitly disable HTTP authentication
# on AJAX requests in case they want to redirect on failures instead of
# handling the errors on their own. This is useful in case your AJAX API
# is the same as your public API and uses a format like JSON (so you
# cannot mark JSON as a navigational format).
def http_auth?
if request.xhr?
Devise.http_authenticatable_on_xhr
else
!(request_format && is_navigational_format?)
end
end
# It doesn't make sense to send authenticate headers in AJAX requests
# or if the user disabled them.
def http_auth_header?
scope_class.http_authenticatable && !request.xhr?
end
def http_auth_body
return i18n_message unless request_format
method = "to_#{request_format}"
if method == "to_xml"
{ error: i18n_message }.to_xml(root: "errors")
elsif {}.respond_to?(method)
{ error: i18n_message }.send(method)
else
i18n_message
end
end
def recall_app(app)
controller, action = app.split("#")
controller_name = ActiveSupport::Inflector.camelize(controller)
controller_klass = ActiveSupport::Inflector.constantize("#{controller_name}Controller")
controller_klass.action(action)
end
def warden
request.respond_to?(:get_header) ? request.get_header("warden") : request.env["warden"]
end
def warden_options
request.respond_to?(:get_header) ? request.get_header("warden.options") : request.env["warden.options"]
end
def warden_message
@message ||= warden.message || warden_options[:message]
end
def scope
@scope ||= warden_options[:scope] || Devise.default_scope
end
def scope_class
@scope_class ||= Devise.mappings[scope].to
end
def attempted_path
warden_options[:attempted_path]
end
# Stores requested URI to redirect the user after signing in. We can't use
# the scoped session provided by warden here, since the user is not
# authenticated yet, but we still need to store the URI based on scope, so
# different scopes would never use the same URI to redirect.
def store_location!
store_location_for(scope, attempted_path) if request.get? && !http_auth?
end
def is_navigational_format?
Devise.navigational_formats.include?(request_format)
end
# Check if flash messages should be emitted. Default is to do it on
# navigational formats
def is_flashing_format?
request.respond_to?(:flash) && is_navigational_format?
end
def request_format
@request_format ||= request.format.try(:ref)
end
def relative_url_root
@relative_url_root ||= begin
config = Rails.application.config
config.try(:relative_url_root) || config.action_controller.try(:relative_url_root)
end
end
def relative_url_root?
relative_url_root.present?
end
ActiveSupport.run_load_hooks(:devise_failure_app, self)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/encryptor.rb | lib/devise/encryptor.rb | # frozen_string_literal: true
require 'bcrypt'
module Devise
module Encryptor
def self.digest(klass, password)
if klass.pepper.present?
password = "#{password}#{klass.pepper}"
end
::BCrypt::Password.create(password, cost: klass.stretches).to_s
end
def self.compare(klass, hashed_password, password)
return false if hashed_password.blank?
bcrypt = ::BCrypt::Password.new(hashed_password)
if klass.pepper.present?
password = "#{password}#{klass.pepper}"
end
password = ::BCrypt::Engine.hash_secret(password, bcrypt.salt)
Devise.secure_compare(password, hashed_password)
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/models.rb | lib/devise/models.rb | # frozen_string_literal: true
module Devise
module Models
class MissingAttribute < StandardError
def initialize(attributes)
@attributes = attributes
end
def message
"The following attribute(s) is (are) missing on your model: #{@attributes.join(", ")}"
end
end
# Creates configuration values for Devise and for the given module.
#
# Devise::Models.config(Devise::Models::DatabaseAuthenticatable, :stretches)
#
# The line above creates:
#
# 1) An accessor called Devise.stretches, which value is used by default;
#
# 2) Some class methods for your model Model.stretches and Model.stretches=
# which have higher priority than Devise.stretches;
#
# 3) And an instance method stretches.
#
# To add the class methods you need to have a module ClassMethods defined
# inside the given class.
#
def self.config(mod, *accessors) #:nodoc:
class << mod; attr_accessor :available_configs; end
mod.available_configs = accessors
accessors.each do |accessor|
mod.class_eval <<-METHOD, __FILE__, __LINE__ + 1
def #{accessor}
if defined?(@#{accessor})
@#{accessor}
elsif superclass.respond_to?(:#{accessor})
superclass.#{accessor}
else
Devise.#{accessor}
end
end
def #{accessor}=(value)
@#{accessor} = value
end
METHOD
end
end
def self.check_fields!(klass)
failed_attributes = []
instance = klass.new
klass.devise_modules.each do |mod|
constant = const_get(mod.to_s.classify)
constant.required_fields(klass).each do |field|
failed_attributes << field unless instance.respond_to?(field)
end
end
if failed_attributes.any?
fail Devise::Models::MissingAttribute.new(failed_attributes)
end
end
# Include the chosen devise modules in your model:
#
# devise :database_authenticatable, :confirmable, :recoverable
#
# You can also give any of the devise configuration values in form of a hash,
# with specific values for this model. Please check your Devise initializer
# for a complete description on those values.
#
def devise(*modules)
options = modules.extract_options!.dup
selected_modules = modules.map(&:to_sym).uniq.sort_by do |s|
Devise::ALL.index(s) || -1 # follow Devise::ALL order
end
devise_modules_hook! do
include Devise::Orm
include Devise::Models::Authenticatable
selected_modules.each do |m|
mod = Devise::Models.const_get(m.to_s.classify)
if mod.const_defined?("ClassMethods")
class_mod = mod.const_get("ClassMethods")
extend class_mod
if class_mod.respond_to?(:available_configs)
available_configs = class_mod.available_configs
available_configs.each do |config|
next unless options.key?(config)
send(:"#{config}=", options.delete(config))
end
end
end
include mod
end
self.devise_modules |= selected_modules
options.each { |key, value| send(:"#{key}=", value) }
end
end
# The hook which is called inside devise.
# So your ORM can include devise compatibility stuff.
def devise_modules_hook!
yield
end
end
end
require 'devise/models/authenticatable'
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/token_generator.rb | lib/devise/token_generator.rb | # frozen_string_literal: true
require 'openssl'
module Devise
class TokenGenerator
def initialize(key_generator, digest = "SHA256")
@key_generator = key_generator
@digest = digest
end
def digest(klass, column, value)
value.present? && OpenSSL::HMAC.hexdigest(@digest, key_for(column), value.to_s)
end
def generate(klass, column)
key = key_for(column)
loop do
raw = Devise.friendly_token
enc = OpenSSL::HMAC.hexdigest(@digest, key, raw)
break [raw, enc] unless klass.to_adapter.find_first({ column => enc })
end
end
private
def key_for(column)
@key_generator.generate_key("Devise #{column}")
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/omniauth.rb | lib/devise/omniauth.rb | # frozen_string_literal: true
begin
gem "omniauth", ">= 1.0.0"
require "omniauth"
rescue LoadError
warn "Could not load 'omniauth'. Please ensure you have the omniauth gem >= 1.0.0 installed and listed in your Gemfile."
raise
end
# Clean up the default path_prefix. It will be automatically set by Devise.
OmniAuth.config.path_prefix = nil
OmniAuth.config.on_failure = Proc.new do |env|
env['devise.mapping'] = Devise::Mapping.find_by_path!(env['PATH_INFO'], :path)
controller_name = ActiveSupport::Inflector.camelize(env['devise.mapping'].controllers[:omniauth_callbacks])
controller_klass = ActiveSupport::Inflector.constantize("#{controller_name}Controller")
controller_klass.action(:failure).call(env)
end
module Devise
module OmniAuth
autoload :Config, "devise/omniauth/config"
autoload :UrlHelpers, "devise/omniauth/url_helpers"
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/parameter_sanitizer.rb | lib/devise/parameter_sanitizer.rb | # frozen_string_literal: true
module Devise
# The +ParameterSanitizer+ deals with permitting specific parameters values
# for each +Devise+ scope in the application.
#
# The sanitizer knows about Devise default parameters (like +password+ and
# +password_confirmation+ for the `RegistrationsController`), and you can
# extend or change the permitted parameters list on your controllers.
#
# === Permitting new parameters
#
# You can add new parameters to the permitted list using the +permit+ method
# in a +before_action+ method, for instance.
#
# class ApplicationController < ActionController::Base
# before_action :configure_permitted_parameters, if: :devise_controller?
#
# protected
#
# def configure_permitted_parameters
# # Permit the `subscribe_newsletter` parameter along with the other
# # sign up parameters.
# devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter])
# end
# end
#
# Using a block yields an +ActionController::Parameters+ object so you can
# permit nested parameters and have more control over how the parameters are
# permitted in your controller.
#
# def configure_permitted_parameters
# devise_parameter_sanitizer.permit(:sign_up) do |user|
# user.permit(newsletter_preferences: [])
# end
# end
class ParameterSanitizer
DEFAULT_PERMITTED_ATTRIBUTES = {
sign_in: [:password, :remember_me],
sign_up: [:password, :password_confirmation],
account_update: [:password, :password_confirmation, :current_password]
}
def initialize(resource_class, resource_name, params)
@auth_keys = extract_auth_keys(resource_class)
@params = params
@resource_name = resource_name
@permitted = {}
DEFAULT_PERMITTED_ATTRIBUTES.each_pair do |action, keys|
permit(action, keys: keys)
end
end
# Sanitize the parameters for a specific +action+.
#
# === Arguments
#
# * +action+ - A +Symbol+ with the action that the controller is
# performing, like +sign_up+, +sign_in+, etc.
#
# === Examples
#
# # Inside the `RegistrationsController#create` action.
# resource = build_resource(devise_parameter_sanitizer.sanitize(:sign_up))
# resource.save
#
# Returns an +ActiveSupport::HashWithIndifferentAccess+ with the permitted
# attributes.
def sanitize(action)
permissions = @permitted[action]
if permissions.respond_to?(:call)
cast_to_hash permissions.call(default_params)
elsif permissions.present?
cast_to_hash permit_keys(default_params, permissions)
else
unknown_action!(action)
end
end
# Add or remove new parameters to the permitted list of an +action+.
#
# === Arguments
#
# * +action+ - A +Symbol+ with the action that the controller is
# performing, like +sign_up+, +sign_in+, etc.
# * +keys:+ - An +Array+ of keys that also should be permitted.
# * +except:+ - An +Array+ of keys that shouldn't be permitted.
# * +block+ - A block that should be used to permit the action
# parameters instead of the +Array+ based approach. The block will be
# called with an +ActionController::Parameters+ instance.
#
# === Examples
#
# # Adding new parameters to be permitted in the `sign_up` action.
# devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter])
#
# # Removing the `password` parameter from the `account_update` action.
# devise_parameter_sanitizer.permit(:account_update, except: [:password])
#
# # Using the block form to completely override how we permit the
# # parameters for the `sign_up` action.
# devise_parameter_sanitizer.permit(:sign_up) do |user|
# user.permit(:email, :password, :password_confirmation)
# end
#
#
# Returns nothing.
def permit(action, keys: nil, except: nil, &block)
if block_given?
@permitted[action] = block
end
if keys.present?
@permitted[action] ||= @auth_keys.dup
@permitted[action].concat(keys)
end
if except.present?
@permitted[action] ||= @auth_keys.dup
@permitted[action] = @permitted[action] - except
end
end
private
# Cast a sanitized +ActionController::Parameters+ to a +HashWithIndifferentAccess+
# that can be used elsewhere.
#
# Returns an +ActiveSupport::HashWithIndifferentAccess+.
def cast_to_hash(params)
params && params.to_h
end
def default_params
if hashable_resource_params?
@params.fetch(@resource_name)
else
empty_params
end
end
def hashable_resource_params?
@params[@resource_name].respond_to?(:permit)
end
def empty_params
ActionController::Parameters.new({})
end
def permit_keys(parameters, keys)
parameters.permit(*keys)
end
def extract_auth_keys(klass)
auth_keys = klass.authentication_keys
auth_keys.respond_to?(:keys) ? auth_keys.keys : auth_keys
end
def unknown_action!(action)
raise NotImplementedError, <<-MESSAGE.strip_heredoc
"Devise doesn't know how to sanitize parameters for '#{action}'".
If you want to define a new set of parameters to be sanitized use the
`permit` method first:
devise_parameter_sanitizer.permit(:#{action}, keys: [:param1, :param2, :param3])
MESSAGE
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/time_inflector.rb | lib/devise/time_inflector.rb | # frozen_string_literal: true
require "active_support/core_ext/module/delegation"
module Devise
class TimeInflector
include ActionView::Helpers::DateHelper
class << self
attr_reader :instance
delegate :time_ago_in_words, to: :instance
end
@instance = new
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/modules.rb | lib/devise/modules.rb | # frozen_string_literal: true
require 'active_support/core_ext/object/with_options'
Devise.with_options model: true do |d|
# Strategies first
d.with_options strategy: true do |s|
routes = [nil, :new, :destroy]
s.add_module :database_authenticatable, controller: :sessions, route: { session: routes }
s.add_module :rememberable, no_input: true
end
# Other authentications
d.add_module :omniauthable, controller: :omniauth_callbacks, route: :omniauth_callback
# Misc after
routes = [nil, :new, :edit]
d.add_module :recoverable, controller: :passwords, route: { password: routes }
d.add_module :registerable, controller: :registrations, route: { registration: (routes << :cancel) }
d.add_module :validatable
# The ones which can sign out after
routes = [nil, :new]
d.add_module :confirmable, controller: :confirmations, route: { confirmation: routes }
d.add_module :lockable, controller: :unlocks, route: { unlock: routes }
d.add_module :timeoutable
# Stats for last, so we make sure the user is really signed in
d.add_module :trackable
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/rails/routes.rb | lib/devise/rails/routes.rb | # frozen_string_literal: true
require "active_support/core_ext/object/try"
require "active_support/core_ext/hash/slice"
module Devise
module RouteSet
def finalize!
result = super
@devise_finalized ||= begin
if Devise.router_name.nil? && defined?(@devise_finalized) && self != Rails.application.try(:routes)
warn "[DEVISE] We have detected that you are using devise_for inside engine routes. " \
"In this case, you probably want to set Devise.router_name = MOUNT_POINT, where " \
"MOUNT_POINT is a symbol representing where this engine will be mounted at. For " \
"now Devise will default the mount point to :main_app. You can explicitly set it" \
" to :main_app as well in case you want to keep the current behavior."
end
Devise.configure_warden!
Devise.regenerate_helpers!
true
end
result
end
end
end
module ActionDispatch::Routing
class RouteSet #:nodoc:
# Ensure Devise modules are included only after loading routes, because we
# need devise_for mappings already declared to create filters and helpers.
prepend Devise::RouteSet
end
class Mapper
# Includes devise_for method for routes. This method is responsible to
# generate all needed routes for devise, based on what modules you have
# defined in your model.
#
# ==== Examples
#
# Let's say you have an User model configured to use authenticatable,
# confirmable and recoverable modules. After creating this inside your routes:
#
# devise_for :users
#
# This method is going to look inside your User model and create the
# needed routes:
#
# # Session routes for Authenticatable (default)
# new_user_session GET /users/sign_in {controller:"devise/sessions", action:"new"}
# user_session POST /users/sign_in {controller:"devise/sessions", action:"create"}
# destroy_user_session DELETE /users/sign_out {controller:"devise/sessions", action:"destroy"}
#
# # Password routes for Recoverable, if User model has :recoverable configured
# new_user_password GET /users/password/new(.:format) {controller:"devise/passwords", action:"new"}
# edit_user_password GET /users/password/edit(.:format) {controller:"devise/passwords", action:"edit"}
# user_password PUT /users/password(.:format) {controller:"devise/passwords", action:"update"}
# POST /users/password(.:format) {controller:"devise/passwords", action:"create"}
#
# # Confirmation routes for Confirmable, if User model has :confirmable configured
# new_user_confirmation GET /users/confirmation/new(.:format) {controller:"devise/confirmations", action:"new"}
# user_confirmation GET /users/confirmation(.:format) {controller:"devise/confirmations", action:"show"}
# POST /users/confirmation(.:format) {controller:"devise/confirmations", action:"create"}
#
# ==== Routes integration
#
# +devise_for+ is meant to play nicely with other routes methods. For example,
# by calling +devise_for+ inside a namespace, it automatically nests your devise
# controllers:
#
# namespace :publisher do
# devise_for :account
# end
#
# The snippet above will use publisher/sessions controller instead of devise/sessions
# controller. You can revert this change or configure it directly by passing the :module
# option described below to +devise_for+.
#
# Also note that when you use a namespace it will affect all the helpers and methods
# for controllers and views. For example, using the above setup you'll end with
# following methods: current_publisher_account, authenticate_publisher_account!,
# publisher_account_signed_in, etc.
#
# The only aspect not affect by the router configuration is the model name. The
# model name can be explicitly set via the :class_name option.
#
# ==== Options
#
# You can configure your routes with some options:
#
# * class_name: set up a different class to be looked up by devise, if it cannot be
# properly found by the route name.
#
# devise_for :users, class_name: 'Account'
#
# * path: allows you to set up path name that will be used, as rails routes does.
# The following route configuration would set up your route as /accounts instead of /users:
#
# devise_for :users, path: 'accounts'
#
# * singular: set up the singular name for the given resource. This is used as the helper methods
# names in controller ("authenticate_#{singular}!", "#{singular}_signed_in?", "current_#{singular}"
# and "#{singular}_session"), as the scope name in routes and as the scope given to warden.
#
# devise_for :admins, singular: :manager
#
# devise_scope :manager do
# ...
# end
#
# class ManagerController < ApplicationController
# before_action authenticate_manager!
#
# def show
# @manager = current_manager
# ...
# end
# end
#
# * path_names: configure different path names to overwrite defaults :sign_in, :sign_out, :sign_up,
# :password, :confirmation, :unlock.
#
# devise_for :users, path_names: {
# sign_in: 'login', sign_out: 'logout',
# password: 'secret', confirmation: 'verification',
# registration: 'register', edit: 'edit/profile'
# }
#
# * controllers: the controller which should be used. All routes by default points to Devise controllers.
# However, if you want them to point to custom controller, you should do:
#
# devise_for :users, controllers: { sessions: "users/sessions" }
#
# * failure_app: a rack app which is invoked whenever there is a failure. Strings representing a given
# are also allowed as parameter.
#
# * sign_out_via: the HTTP method(s) accepted for the :sign_out action (default: :delete),
# if you wish to restrict this to accept only :post or :delete requests you should do:
#
# devise_for :users, sign_out_via: [:get, :post]
#
# You need to make sure that your sign_out controls trigger a request with a matching HTTP method.
#
# * module: the namespace to find controllers (default: "devise", thus
# accessing devise/sessions, devise/registrations, and so on). If you want
# to namespace all at once, use module:
#
# devise_for :users, module: "users"
#
# * skip: tell which controller you want to skip routes from being created.
# It accepts :all as an option, meaning it will not generate any route at all:
#
# devise_for :users, skip: :sessions
#
# * only: the opposite of :skip, tell which controllers only to generate routes to:
#
# devise_for :users, only: :sessions
#
# * skip_helpers: skip generating Devise url helpers like new_session_path(@user).
# This is useful to avoid conflicts with previous routes and is false by default.
# It accepts true as option, meaning it will skip all the helpers for the controllers
# given in :skip but it also accepts specific helpers to be skipped:
#
# devise_for :users, skip: [:registrations, :confirmations], skip_helpers: true
# devise_for :users, skip_helpers: [:registrations, :confirmations]
#
# * format: include "(.:format)" in the generated routes? true by default, set to false to disable:
#
# devise_for :users, format: false
#
# * constraints: works the same as Rails' constraints
#
# * defaults: works the same as Rails' defaults
#
# * router_name: allows application level router name to be overwritten for the current scope
#
# ==== Scoping
#
# Following Rails 3 routes DSL, you can nest devise_for calls inside a scope:
#
# scope "/my" do
# devise_for :users
# end
#
# However, since Devise uses the request path to retrieve the current user,
# this has one caveat: If you are using a dynamic segment, like so ...
#
# scope ":locale" do
# devise_for :users
# end
#
# you are required to configure default_url_options in your
# ApplicationController class, so Devise can pick it:
#
# class ApplicationController < ActionController::Base
# def self.default_url_options
# { locale: I18n.locale }
# end
# end
#
# ==== Adding custom actions to override controllers
#
# You can pass a block to devise_for that will add any routes defined in the block to Devise's
# list of known actions. This is important if you add a custom action to a controller that
# overrides an out of the box Devise controller.
# For example:
#
# class RegistrationsController < Devise::RegistrationsController
# def update
# # do something different here
# end
#
# def deactivate
# # not a standard action
# # deactivate code here
# end
# end
#
# In order to get Devise to recognize the deactivate action, your devise_scope entry should look like this:
#
# devise_scope :owner do
# post "deactivate", to: "registrations#deactivate", as: "deactivate_registration"
# end
#
def devise_for(*resources)
@devise_finalized = false
raise_no_secret_key unless Devise.secret_key
options = resources.extract_options!
options[:as] ||= @scope[:as] if @scope[:as].present?
options[:module] ||= @scope[:module] if @scope[:module].present?
options[:path_prefix] ||= @scope[:path] if @scope[:path].present?
options[:path_names] = (@scope[:path_names] || {}).merge(options[:path_names] || {})
options[:constraints] = (@scope[:constraints] || {}).merge(options[:constraints] || {})
options[:defaults] = (@scope[:defaults] || {}).merge(options[:defaults] || {})
options[:options] = @scope[:options] || {}
resources.map!(&:to_sym)
resources.each do |resource|
mapping = Devise.add_mapping(resource, options)
begin
raise_no_devise_method_error!(mapping.class_name) unless mapping.to.respond_to?(:devise)
rescue NameError => e
raise unless mapping.class_name == resource.to_s.classify
warn "[WARNING] You provided devise_for #{resource.inspect} but there is " \
"no model #{mapping.class_name} defined in your application"
next
rescue NoMethodError => e
raise unless e.message.include?("undefined method `devise'")
raise_no_devise_method_error!(mapping.class_name)
end
if options[:controllers] && options[:controllers][:omniauth_callbacks]
unless mapping.omniauthable?
raise ArgumentError, "Mapping omniauth_callbacks on a resource that is not omniauthable\n" \
"Please add `devise :omniauthable` to the `#{mapping.class_name}` model"
end
end
routes = mapping.used_routes
devise_scope mapping.name do
with_devise_exclusive_scope mapping.fullpath, mapping.name, options do
routes.each { |mod| send("devise_#{mod}", mapping, mapping.controllers) }
end
end
end
end
# Allow you to add authentication request from the router.
# Takes an optional scope and block to provide constraints
# on the model instance itself.
#
# authenticate do
# resources :post
# end
#
# authenticate(:admin) do
# resources :users
# end
#
# authenticate :user, lambda {|u| u.role == "admin"} do
# root to: "admin/dashboard#show", as: :user_root
# end
#
def authenticate(scope = nil, block = nil)
constraints_for(:authenticate!, scope, block) do
yield
end
end
# Allow you to route based on whether a scope is authenticated. You
# can optionally specify which scope and a block. The block accepts
# a model and allows extra constraints to be done on the instance.
#
# authenticated :admin do
# root to: 'admin/dashboard#show', as: :admin_root
# end
#
# authenticated do
# root to: 'dashboard#show', as: :authenticated_root
# end
#
# authenticated :user, lambda {|u| u.role == "admin"} do
# root to: "admin/dashboard#show", as: :user_root
# end
#
# root to: 'landing#show'
#
def authenticated(scope = nil, block = nil)
constraints_for(:authenticate?, scope, block) do
yield
end
end
# Allow you to route based on whether a scope is *not* authenticated.
# You can optionally specify which scope.
#
# unauthenticated do
# as :user do
# root to: 'devise/registrations#new'
# end
# end
#
# root to: 'dashboard#show'
#
def unauthenticated(scope = nil)
constraint = lambda do |request|
not request.env["warden"].authenticate? scope: scope
end
constraints(constraint) do
yield
end
end
# Sets the devise scope to be used in the controller. If you have custom routes,
# you are required to call this method (also aliased as :as) in order to specify
# to which controller it is targeted.
#
# as :user do
# get "sign_in", to: "devise/sessions#new"
# end
#
# Notice you cannot have two scopes mapping to the same URL. And remember, if
# you try to access a devise controller without specifying a scope, it will
# raise ActionNotFound error.
#
# Also be aware of that 'devise_scope' and 'as' use the singular form of the
# noun where other devise route commands expect the plural form. This would be a
# good and working example.
#
# devise_scope :user do
# get "/some/route" => "some_devise_controller"
# end
# devise_for :users
#
# Notice and be aware of the differences above between :user and :users
def devise_scope(scope)
constraint = lambda do |request|
request.env["devise.mapping"] = Devise.mappings[scope]
true
end
constraints(constraint) do
yield
end
end
alias :as :devise_scope
protected
def devise_session(mapping, controllers) #:nodoc:
resource :session, only: [], controller: controllers[:sessions], path: "" do
get :new, path: mapping.path_names[:sign_in], as: "new"
post :create, path: mapping.path_names[:sign_in]
match :destroy, path: mapping.path_names[:sign_out], as: "destroy", via: mapping.sign_out_via
end
end
def devise_password(mapping, controllers) #:nodoc:
resource :password, only: [:new, :create, :edit, :update],
path: mapping.path_names[:password], controller: controllers[:passwords]
end
def devise_confirmation(mapping, controllers) #:nodoc:
resource :confirmation, only: [:new, :create, :show],
path: mapping.path_names[:confirmation], controller: controllers[:confirmations]
end
def devise_unlock(mapping, controllers) #:nodoc:
if mapping.to.unlock_strategy_enabled?(:email)
resource :unlock, only: [:new, :create, :show],
path: mapping.path_names[:unlock], controller: controllers[:unlocks]
end
end
def devise_registration(mapping, controllers) #:nodoc:
path_names = {
new: mapping.path_names[:sign_up],
edit: mapping.path_names[:edit],
cancel: mapping.path_names[:cancel]
}
options = {
only: [:new, :create, :edit, :update, :destroy],
path: mapping.path_names[:registration],
path_names: path_names,
controller: controllers[:registrations]
}
resource :registration, **options do
get :cancel
end
end
def devise_omniauth_callback(mapping, controllers) #:nodoc:
if mapping.fullpath =~ /:[a-zA-Z_]/
raise <<-ERROR
Devise does not support scoping OmniAuth callbacks under a dynamic segment
and you have set #{mapping.fullpath.inspect}. You can work around by passing
`skip: :omniauth_callbacks` to the `devise_for` call and extract omniauth
options to another `devise_for` call outside the scope. Here is an example:
devise_for :users, only: :omniauth_callbacks, controllers: {omniauth_callbacks: 'users/omniauth_callbacks'}
scope '/(:locale)', locale: /ru|en/ do
devise_for :users, skip: :omniauth_callbacks
end
ERROR
end
current_scope = @scope.dup
if @scope.respond_to? :new
@scope = @scope.new path: nil
else
@scope[:path] = nil
end
path_prefix = Devise.omniauth_path_prefix || "/#{mapping.fullpath}/auth".squeeze("/")
set_omniauth_path_prefix!(path_prefix)
mapping.to.omniauth_providers.each do |provider|
match "#{path_prefix}/#{provider}",
to: "#{controllers[:omniauth_callbacks]}#passthru",
as: "#{provider}_omniauth_authorize",
via: OmniAuth.config.allowed_request_methods
match "#{path_prefix}/#{provider}/callback",
to: "#{controllers[:omniauth_callbacks]}##{provider}",
as: "#{provider}_omniauth_callback",
via: [:get, :post]
end
ensure
@scope = current_scope
end
def with_devise_exclusive_scope(new_path, new_as, options) #:nodoc:
current_scope = @scope.dup
exclusive = { as: new_as, path: new_path, module: nil }
exclusive.merge!(options.slice(:constraints, :format, :defaults, :options))
if @scope.respond_to? :new
@scope = @scope.new exclusive
else
exclusive.each_pair { |key, value| @scope[key] = value }
end
yield
ensure
@scope = current_scope
end
def constraints_for(method_to_apply, scope = nil, block = nil)
constraint = lambda do |request|
request.env['warden'].send(method_to_apply, scope: scope) &&
(block.nil? || block.call(request.env["warden"].user(scope)))
end
constraints(constraint) do
yield
end
end
def set_omniauth_path_prefix!(path_prefix) #:nodoc:
if ::OmniAuth.config.path_prefix && ::OmniAuth.config.path_prefix != path_prefix
raise "Wrong OmniAuth configuration. If you are getting this exception, it means that either:\n\n" \
"1) You are manually setting OmniAuth.config.path_prefix and it doesn't match the Devise one\n" \
"2) You are setting :omniauthable in more than one model\n" \
"3) You changed your Devise routes/OmniAuth setting and haven't restarted your server"
else
::OmniAuth.config.path_prefix = path_prefix
end
end
def raise_no_secret_key #:nodoc:
raise <<-ERROR
Devise.secret_key was not set. Please add the following to your Devise initializer:
config.secret_key = '#{SecureRandom.hex(64)}'
Please ensure you restarted your application after installing Devise or setting the key.
ERROR
end
def raise_no_devise_method_error!(klass) #:nodoc:
raise "#{klass} does not respond to 'devise' method. This usually means you haven't " \
"loaded your ORM file or it's being loaded too late. To fix it, be sure to require 'devise/orm/YOUR_ORM' " \
"inside 'config/initializers/devise.rb' or before your application definition in 'config/application.rb'"
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/rails/warden_compat.rb | lib/devise/rails/warden_compat.rb | # frozen_string_literal: true
module Warden::Mixins::Common
def request
@request ||= ActionDispatch::Request.new(env)
end
def reset_session!
request.reset_session
end
def cookies
request.cookie_jar
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/controllers/store_location.rb | lib/devise/controllers/store_location.rb | # frozen_string_literal: true
require "uri"
module Devise
module Controllers
# Provide the ability to store a location.
# Used to redirect back to a desired path after sign in.
# Included by default in all controllers.
module StoreLocation
# Returns and delete (if it's navigational format) the url stored in the session for
# the given scope. Useful for giving redirect backs after sign up:
#
# Example:
#
# redirect_to stored_location_for(:user) || root_path
#
def stored_location_for(resource_or_scope)
session_key = stored_location_key_for(resource_or_scope)
if is_navigational_format?
session.delete(session_key)
else
session[session_key]
end
end
# Stores the provided location to redirect the user after signing in.
# Useful in combination with the `stored_location_for` helper.
#
# Example:
#
# store_location_for(:user, dashboard_path)
# redirect_to user_facebook_omniauth_authorize_path
#
def store_location_for(resource_or_scope, location)
session_key = stored_location_key_for(resource_or_scope)
path = extract_path_from_location(location)
session[session_key] = path if path
end
private
def parse_uri(location)
location && URI.parse(location)
rescue URI::InvalidURIError
nil
end
def stored_location_key_for(resource_or_scope)
scope = Devise::Mapping.find_scope!(resource_or_scope)
"#{scope}_return_to"
end
def extract_path_from_location(location)
uri = parse_uri(location)
if uri
path = remove_domain_from_uri(uri)
path = add_fragment_back_to_path(uri, path)
path
end
end
def remove_domain_from_uri(uri)
[uri.path.sub(/\A\/+/, '/'), uri.query].compact.join('?')
end
def add_fragment_back_to_path(uri, path)
[path, uri.fragment].compact.join('#')
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/controllers/rememberable.rb | lib/devise/controllers/rememberable.rb | # frozen_string_literal: true
module Devise
module Controllers
# A module that may be optionally included in a controller in order
# to provide remember me behavior. Useful when signing in is done
# through a callback, like in OmniAuth.
module Rememberable
# Return default cookie values retrieved from session options.
def self.cookie_values
Rails.configuration.session_options.slice(:path, :domain, :secure)
end
def remember_me_is_active?(resource)
return false unless resource.respond_to?(:remember_me)
scope = Devise::Mapping.find_scope!(resource)
_, token, generated_at = cookies.signed[remember_key(resource, scope)]
resource.remember_me?(token, generated_at)
end
# Remembers the given resource by setting up a cookie
def remember_me(resource)
return if request.env["devise.skip_storage"]
scope = Devise::Mapping.find_scope!(resource)
resource.remember_me!
cookies.signed[remember_key(resource, scope)] = remember_cookie_values(resource)
end
# Forgets the given resource by deleting a cookie
def forget_me(resource)
scope = Devise::Mapping.find_scope!(resource)
resource.forget_me!
cookies.delete(remember_key(resource, scope), forget_cookie_values(resource))
end
protected
def forget_cookie_values(resource)
Devise::Controllers::Rememberable.cookie_values.merge!(resource.rememberable_options)
end
def remember_cookie_values(resource)
options = { httponly: true }
options.merge!(forget_cookie_values(resource))
options.merge!(
value: resource.class.serialize_into_cookie(resource),
expires: resource.remember_expires_at
)
end
def remember_key(resource, scope)
resource.rememberable_options.fetch(:key, "remember_#{scope}_token")
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/controllers/responder.rb | lib/devise/controllers/responder.rb | # frozen_string_literal: true
module Devise
module Controllers
# Custom Responder to configure default statuses that only apply to Devise,
# and allow to integrate more easily with Hotwire/Turbo.
class Responder < ActionController::Responder
if respond_to?(:error_status=) && respond_to?(:redirect_status=)
self.error_status = :ok
self.redirect_status = :found
else
# TODO: remove this support for older Rails versions, which aren't supported by Turbo
# and/or responders. It won't allow configuring a custom response, but it allows Devise
# to use these methods and defaults across the implementation more easily.
def self.error_status
:ok
end
def self.redirect_status
:found
end
def self.error_status=(*)
warn "[DEVISE] Setting the error status on the Devise responder has no effect with this " \
"version of `responders`, please make sure you're using a newer version. Check the changelog for more info."
end
def self.redirect_status=(*)
warn "[DEVISE] Setting the redirect status on the Devise responder has no effect with this " \
"version of `responders`, please make sure you're using a newer version. Check the changelog for more info."
end
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/controllers/sign_in_out.rb | lib/devise/controllers/sign_in_out.rb | # frozen_string_literal: true
module Devise
module Controllers
# Provide sign in and sign out functionality.
# Included by default in all controllers.
module SignInOut
# Return true if the given scope is signed in session. If no scope given, return
# true if any scope is signed in. This will run authentication hooks, which may
# cause exceptions to be thrown from this method; if you simply want to check
# if a scope has already previously been authenticated without running
# authentication hooks, you can directly call `warden.authenticated?(scope: scope)`
def signed_in?(scope = nil)
[scope || Devise.mappings.keys].flatten.any? do |_scope|
warden.authenticate?(scope: _scope)
end
end
# Sign in a user that already was authenticated. This helper is useful for logging
# users in after sign up. All options given to sign_in is passed forward
# to the set_user method in warden.
# If you are using a custom warden strategy and the timeoutable module, you have to
# set `env["devise.skip_timeout"] = true` in the request to use this method, like we do
# in the sessions controller: https://github.com/heartcombo/devise/blob/main/app/controllers/devise/sessions_controller.rb#L7
#
# Examples:
#
# sign_in :user, @user # sign_in(scope, resource)
# sign_in @user # sign_in(resource)
# sign_in @user, event: :authentication # sign_in(resource, options)
# sign_in @user, store: false # sign_in(resource, options)
#
def sign_in(resource_or_scope, *args)
options = args.extract_options!
scope = Devise::Mapping.find_scope!(resource_or_scope)
resource = args.last || resource_or_scope
expire_data_after_sign_in!
if warden.user(scope) == resource && !options.delete(:force)
# Do nothing. User already signed in and we are not forcing it.
true
else
warden.set_user(resource, options.merge!(scope: scope))
end
end
# Sign in a user bypassing the warden callbacks and stores the user
# straight in session. This option is useful in cases the user is already
# signed in, but we want to refresh the credentials in session.
#
# Examples:
#
# bypass_sign_in @user, scope: :user
# bypass_sign_in @user
def bypass_sign_in(resource, scope: nil)
scope ||= Devise::Mapping.find_scope!(resource)
expire_data_after_sign_in!
warden.session_serializer.store(resource, scope)
end
# Sign out a given user or scope. This helper is useful for signing out a user
# after deleting accounts. Returns true if there was a logout and false if there
# is no user logged in on the referred scope
#
# Examples:
#
# sign_out :user # sign_out(scope)
# sign_out @user # sign_out(resource)
#
def sign_out(resource_or_scope = nil)
return sign_out_all_scopes unless resource_or_scope
scope = Devise::Mapping.find_scope!(resource_or_scope)
user = warden.user(scope: scope, run_callbacks: false) # If there is no user
warden.logout(scope)
warden.clear_strategies_cache!(scope: scope)
instance_variable_set(:"@current_#{scope}", nil)
!!user
end
# Sign out all active users or scopes. This helper is useful for signing out all roles
# in one click. This signs out ALL scopes in warden. Returns true if there was at least one logout
# and false if there was no user logged in on all scopes.
def sign_out_all_scopes(lock = true)
users = Devise.mappings.keys.map { |s| warden.user(scope: s, run_callbacks: false) }
warden.logout
expire_data_after_sign_out!
warden.clear_strategies_cache!
warden.lock! if lock
users.any?
end
private
def expire_data_after_sign_in!
session.keys.grep(/^devise\./).each { |k| session.delete(k) }
end
alias :expire_data_after_sign_out! :expire_data_after_sign_in!
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/controllers/scoped_views.rb | lib/devise/controllers/scoped_views.rb | # frozen_string_literal: true
module Devise
module Controllers
module ScopedViews
extend ActiveSupport::Concern
module ClassMethods
def scoped_views?
defined?(@scoped_views) ? @scoped_views : Devise.scoped_views
end
def scoped_views=(value)
@scoped_views = value
end
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/controllers/helpers.rb | lib/devise/controllers/helpers.rb | # frozen_string_literal: true
module Devise
module Controllers
# Those helpers are convenience methods added to ApplicationController.
module Helpers
extend ActiveSupport::Concern
include Devise::Controllers::SignInOut
include Devise::Controllers::StoreLocation
included do
if respond_to?(:helper_method)
helper_method :warden, :signed_in?, :devise_controller?
end
end
module ClassMethods
# Define authentication filters and accessor helpers for a group of mappings.
# These methods are useful when you are working with multiple mappings that
# share some functionality. They are pretty much the same as the ones
# defined for normal mappings.
#
# Example:
#
# inside BlogsController (or any other controller, it doesn't matter which):
# devise_group :blogger, contains: [:user, :admin]
#
# Generated methods:
# authenticate_blogger! # Redirects unless user or admin are signed in
# blogger_signed_in? # Checks whether there is either a user or an admin signed in
# current_blogger # Currently signed in user or admin
# current_bloggers # Currently signed in user and admin
#
# Use:
# before_action :authenticate_blogger! # Redirects unless either a user or an admin are authenticated
# before_action ->{ authenticate_blogger! :admin } # Redirects to the admin login page
# current_blogger :user # Preferably returns a User if one is signed in
#
def devise_group(group_name, opts = {})
mappings = "[#{ opts[:contains].map { |m| ":#{m}" }.join(',') }]"
class_eval <<-METHODS, __FILE__, __LINE__ + 1
def authenticate_#{group_name}!(favorite = nil, opts = {})
unless #{group_name}_signed_in?
mappings = #{mappings}
mappings.unshift mappings.delete(favorite.to_sym) if favorite
mappings.each do |mapping|
opts[:scope] = mapping
opts[:locale] = I18n.locale
warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
end
end
end
def #{group_name}_signed_in?
#{mappings}.any? do |mapping|
warden.authenticate?(scope: mapping)
end
end
def current_#{group_name}(favorite = nil)
mappings = #{mappings}
mappings.unshift mappings.delete(favorite.to_sym) if favorite
mappings.each do |mapping|
current = warden.authenticate(scope: mapping)
return current if current
end
nil
end
def current_#{group_name.to_s.pluralize}
#{mappings}.map do |mapping|
warden.authenticate(scope: mapping)
end.compact
end
if respond_to?(:helper_method)
helper_method "current_#{group_name}", "current_#{group_name.to_s.pluralize}", "#{group_name}_signed_in?"
end
METHODS
end
def log_process_action(payload)
payload[:status] ||= 401 unless payload[:exception]
super
end
end
# Define authentication filters and accessor helpers based on mappings.
# These filters should be used inside the controllers as before_actions,
# so you can control the scope of the user who should be signed in to
# access that specific controller/action.
# Example:
#
# Roles:
# User
# Admin
#
# Generated methods:
# authenticate_user! # Signs user in or redirect
# authenticate_admin! # Signs admin in or redirect
# user_signed_in? # Checks whether there is a user signed in or not
# admin_signed_in? # Checks whether there is an admin signed in or not
# current_user # Current signed in user
# current_admin # Current signed in admin
# user_session # Session data available only to the user scope
# admin_session # Session data available only to the admin scope
#
# Use:
# before_action :authenticate_user! # Tell devise to use :user map
# before_action :authenticate_admin! # Tell devise to use :admin map
#
def self.define_helpers(mapping) #:nodoc:
mapping = mapping.name
class_eval <<-METHODS, __FILE__, __LINE__ + 1
def authenticate_#{mapping}!(opts = {})
opts[:scope] = :#{mapping}
opts[:locale] = I18n.locale
warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
end
def #{mapping}_signed_in?
!!current_#{mapping}
end
def current_#{mapping}
@current_#{mapping} ||= warden.authenticate(scope: :#{mapping})
end
def #{mapping}_session
current_#{mapping} && warden.session(:#{mapping})
end
METHODS
ActiveSupport.on_load(:action_controller) do
if respond_to?(:helper_method)
helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session"
end
end
end
# The main accessor for the warden proxy instance
def warden
request.env['warden'] or raise MissingWarden
end
# Return true if it's a devise_controller. false to all controllers unless
# the controllers defined inside devise. Useful if you want to apply a before
# filter to all controllers, except the ones in devise:
#
# before_action :my_filter, unless: :devise_controller?
def devise_controller?
is_a?(::DeviseController)
end
# Set up a param sanitizer to filter parameters using strong_parameters. See
# lib/devise/parameter_sanitizer.rb for more info. Override this
# method in your application controller to use your own parameter sanitizer.
def devise_parameter_sanitizer
@devise_parameter_sanitizer ||= Devise::ParameterSanitizer.new(resource_class, resource_name, params)
end
# Tell warden that params authentication is allowed for that specific page.
def allow_params_authentication!
request.env["devise.allow_params_authentication"] = true
end
# The scope root url to be used when they're signed in. By default, it first
# tries to find a resource_root_path, otherwise it uses the root_path.
def signed_in_root_path(resource_or_scope)
scope = Devise::Mapping.find_scope!(resource_or_scope)
router_name = Devise.mappings[scope].router_name
home_path = "#{scope}_root_path"
context = router_name ? send(router_name) : self
if context.respond_to?(home_path, true)
context.send(home_path)
elsif context.respond_to?(:root_path)
context.root_path
elsif respond_to?(:root_path)
root_path
else
"/"
end
end
# The default url to be used after signing in. This is used by all Devise
# controllers and you can overwrite it in your ApplicationController to
# provide a custom hook for a custom resource.
#
# By default, it first tries to find a valid resource_return_to key in the
# session, then it fallbacks to resource_root_path, otherwise it uses the
# root path. For a user scope, you can define the default url in
# the following way:
#
# get '/users' => 'users#index', as: :user_root # creates user_root_path
#
# namespace :user do
# root 'users#index' # creates user_root_path
# end
#
# If the resource root path is not defined, root_path is used. However,
# if this default is not enough, you can customize it, for example:
#
# def after_sign_in_path_for(resource)
# stored_location_for(resource) ||
# if resource.is_a?(User) && resource.can_publish?
# publisher_url
# else
# super
# end
# end
#
def after_sign_in_path_for(resource_or_scope)
stored_location_for(resource_or_scope) || signed_in_root_path(resource_or_scope)
end
# Method used by sessions controller to sign out a user. You can overwrite
# it in your ApplicationController to provide a custom hook for a custom
# scope. Notice that differently from +after_sign_in_path_for+ this method
# receives a symbol with the scope, and not the resource.
#
# By default it is the root_path.
def after_sign_out_path_for(resource_or_scope)
scope = Devise::Mapping.find_scope!(resource_or_scope)
router_name = Devise.mappings[scope].router_name
context = router_name ? send(router_name) : self
context.respond_to?(:root_path) ? context.root_path : "/"
end
# Sign in a user and tries to redirect first to the stored location and
# then to the url specified by after_sign_in_path_for. It accepts the same
# parameters as the sign_in method.
def sign_in_and_redirect(resource_or_scope, *args)
options = args.extract_options!
scope = Devise::Mapping.find_scope!(resource_or_scope)
resource = args.last || resource_or_scope
sign_in(scope, resource, options)
redirect_to after_sign_in_path_for(resource)
end
# Sign out a user and tries to redirect to the url specified by
# after_sign_out_path_for.
def sign_out_and_redirect(resource_or_scope)
scope = Devise::Mapping.find_scope!(resource_or_scope)
redirect_path = after_sign_out_path_for(scope)
Devise.sign_out_all_scopes ? sign_out : sign_out(scope)
redirect_to redirect_path
end
# Overwrite Rails' handle unverified request to sign out all scopes,
# clear run strategies and remove cached variables.
def handle_unverified_request
super # call the default behavior which resets/nullifies/raises
request.env["devise.skip_storage"] = true
sign_out_all_scopes(false)
end
def request_format
@request_format ||= request.format.try(:ref)
end
def is_navigational_format?
Devise.navigational_formats.include?(request_format)
end
# Check if flash messages should be emitted. Default is to do it on
# navigational formats
def is_flashing_format?
request.respond_to?(:flash) && is_navigational_format?
end
private
def expire_data_after_sign_out!
Devise.mappings.each { |_,m| instance_variable_set("@current_#{m.name}", nil) }
super
end
end
end
class MissingWarden < StandardError
def initialize
super "Devise could not find the `Warden::Proxy` instance on your request environment.\n" + \
"Make sure that your application is loading Devise and Warden as expected and that " + \
"the `Warden::Manager` middleware is present in your middleware stack.\n" + \
"If you are seeing this on one of your tests, ensure that your tests are either " + \
"executing the Rails middleware stack or that your tests are using the `Devise::Test::ControllerHelpers` " + \
"module to inject the `request.env['warden']` object for you."
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/controllers/url_helpers.rb | lib/devise/controllers/url_helpers.rb | # frozen_string_literal: true
module Devise
module Controllers
# Create url helpers to be used with resource/scope configuration. Acts as
# proxies to the generated routes created by devise.
# Resource param can be a string or symbol, a class, or an instance object.
# Example using a :user resource:
#
# new_session_path(:user) => new_user_session_path
# session_path(:user) => user_session_path
# destroy_session_path(:user) => destroy_user_session_path
#
# new_password_path(:user) => new_user_password_path
# password_path(:user) => user_password_path
# edit_password_path(:user) => edit_user_password_path
#
# new_confirmation_path(:user) => new_user_confirmation_path
# confirmation_path(:user) => user_confirmation_path
#
# Those helpers are included by default to ActionController::Base.
#
# In case you want to add such helpers to another class, you can do
# that as long as this new class includes both url_helpers and
# mounted_helpers. Example:
#
# include Rails.application.routes.url_helpers
# include Rails.application.routes.mounted_helpers
#
module UrlHelpers
def self.remove_helpers!
self.instance_methods.map(&:to_s).grep(/_(url|path)$/).each do |method|
remove_method method
end
end
def self.generate_helpers!(routes = nil)
routes ||= begin
mappings = Devise.mappings.values.map(&:used_helpers).flatten.uniq
Devise::URL_HELPERS.slice(*mappings)
end
routes.each do |module_name, actions|
[:path, :url].each do |path_or_url|
actions.each do |action|
action = action ? "#{action}_" : ""
method = :"#{action}#{module_name}_#{path_or_url}"
define_method method do |resource_or_scope, *args|
scope = Devise::Mapping.find_scope!(resource_or_scope)
router_name = Devise.mappings[scope].router_name
context = router_name ? send(router_name) : _devise_route_context
context.send("#{action}#{scope}_#{module_name}_#{path_or_url}", *args)
end
end
end
end
end
generate_helpers!(Devise::URL_HELPERS)
private
def _devise_route_context
@_devise_route_context ||= send(Devise.available_router_name)
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/hooks/csrf_cleaner.rb | lib/devise/hooks/csrf_cleaner.rb | # frozen_string_literal: true
Warden::Manager.after_authentication do |record, warden, options|
clean_up_for_winning_strategy = !warden.winning_strategy.respond_to?(:clean_up_csrf?) ||
warden.winning_strategy.clean_up_csrf?
if Devise.clean_up_csrf_token_on_authentication && clean_up_for_winning_strategy
if warden.request.respond_to?(:reset_csrf_token)
# Rails 7.1+
warden.request.reset_csrf_token
else
warden.request.session.try(:delete, :_csrf_token)
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/hooks/lockable.rb | lib/devise/hooks/lockable.rb | # frozen_string_literal: true
# After each sign in, if resource responds to failed_attempts, sets it to 0
# This is only triggered when the user is explicitly set (with set_user)
Warden::Manager.after_set_user except: :fetch do |record, warden, options|
if record.respond_to?(:reset_failed_attempts!) && warden.authenticated?(options[:scope])
record.reset_failed_attempts!
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/hooks/rememberable.rb | lib/devise/hooks/rememberable.rb | # frozen_string_literal: true
Warden::Manager.after_set_user except: :fetch do |record, warden, options|
scope = options[:scope]
if record.respond_to?(:remember_me) && options[:store] != false &&
record.remember_me && warden.authenticated?(scope)
Devise::Hooks::Proxy.new(warden).remember_me(record)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/hooks/activatable.rb | lib/devise/hooks/activatable.rb | # frozen_string_literal: true
# Deny user access whenever their account is not active yet.
# We need this as hook to validate the user activity on each request
# and in case the user is using other strategies beside Devise ones.
Warden::Manager.after_set_user do |record, warden, options|
if record && record.respond_to?(:active_for_authentication?) && !record.active_for_authentication?
scope = options[:scope]
warden.logout(scope)
throw :warden, scope: scope, message: record.inactive_message, locale: options.fetch(:locale, I18n.locale)
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/hooks/proxy.rb | lib/devise/hooks/proxy.rb | # frozen_string_literal: true
module Devise
module Hooks
# A small warden proxy so we can remember, forget and
# sign out users from hooks.
class Proxy #:nodoc:
include Devise::Controllers::Rememberable
include Devise::Controllers::SignInOut
attr_reader :warden
delegate :cookies, :request, to: :warden
def initialize(warden)
@warden = warden
end
def session
warden.request.session
end
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
heartcombo/devise | https://github.com/heartcombo/devise/blob/00a97782cb91104a72ea68d8f62ca8aa0e6eb101/lib/devise/hooks/timeoutable.rb | lib/devise/hooks/timeoutable.rb | # frozen_string_literal: true
# Each time a record is set we check whether its session has already timed out
# or not, based on last request time. If so, the record is logged out and
# redirected to the sign in page. Also, each time the request comes and the
# record is set, we set the last request time inside its scoped session to
# verify timeout in the following request.
Warden::Manager.after_set_user do |record, warden, options|
scope = options[:scope]
env = warden.request.env
if record && record.respond_to?(:timedout?) && warden.authenticated?(scope) &&
options[:store] != false && !env['devise.skip_timeoutable']
last_request_at = warden.session(scope)['last_request_at']
if last_request_at.is_a? Integer
last_request_at = Time.at(last_request_at).utc
elsif last_request_at.is_a? String
last_request_at = Time.parse(last_request_at)
end
proxy = Devise::Hooks::Proxy.new(warden)
if !env['devise.skip_timeout'] &&
record.timedout?(last_request_at) &&
!proxy.remember_me_is_active?(record)
Devise.sign_out_all_scopes ? proxy.sign_out : proxy.sign_out(scope)
throw :warden, scope: scope, message: :timeout, locale: options.fetch(:locale, I18n.locale)
end
unless env['devise.skip_trackable']
warden.session(scope)['last_request_at'] = Time.now.utc.to_i
end
end
end
| ruby | MIT | 00a97782cb91104a72ea68d8f62ca8aa0e6eb101 | 2026-01-04T15:37:27.393664Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.