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
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/acts_as_authentic_test/magic_columns_test.rb
test/acts_as_authentic_test/magic_columns_test.rb
# frozen_string_literal: true require "test_helper" module ActsAsAuthenticTest class MagicColumnsTest < ActiveSupport::TestCase def test_validates_numericality_of_login_count u = User.new u.login_count = -1 refute u.valid? refute u.errors[:login_count].empty? u.login_count = 0 refute u.valid? assert u.errors[:login_count].empty? end def test_validates_numericality_of_failed_login_count u = User.new u.failed_login_count = -1 refute u.valid? refute u.errors[:failed_login_count].empty? u.failed_login_count = 0 refute u.valid? assert u.errors[:failed_login_count].empty? end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/acts_as_authentic_test/persistence_token_test.rb
test/acts_as_authentic_test/persistence_token_test.rb
# frozen_string_literal: true require "test_helper" module ActsAsAuthenticTest class PersistenceTokenTest < ActiveSupport::TestCase def test_after_password_set_reset_persistence_token ben = users(:ben) old_persistence_token = ben.persistence_token ben.password = "newpass" assert_not_equal old_persistence_token, ben.persistence_token end def test_after_password_verification_reset_persistence_token aaron = users(:aaron) old_persistence_token = aaron.persistence_token assert aaron.valid_password?(password_for(aaron)) assert_equal old_persistence_token, aaron.reload.persistence_token # only update it if it is nil assert aaron.update_attribute(:persistence_token, nil) assert aaron.valid_password?(password_for(aaron)) assert_not_equal old_persistence_token, aaron.persistence_token end def test_before_validate_reset_persistence_token u = User.new refute u.valid? assert_not_nil u.persistence_token end def test_forget_all UserSession.allow_http_basic_auth = true http_basic_auth_for(users(:ben)) { UserSession.find } http_basic_auth_for(users(:zack)) { UserSession.find(:ziggity_zack) } assert UserSession.find assert UserSession.find(:ziggity_zack) User.forget_all refute UserSession.find refute UserSession.find(:ziggity_zack) end def test_forget UserSession.allow_http_basic_auth = true ben = users(:ben) zack = users(:zack) http_basic_auth_for(ben) { UserSession.find } http_basic_auth_for(zack) { UserSession.find(:ziggity_zack) } assert ben.reload.logged_in? assert zack.reload.logged_in? ben.forget! refute UserSession.find assert UserSession.find(:ziggity_zack) end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/acts_as_authentic_test/logged_in_status_test.rb
test/acts_as_authentic_test/logged_in_status_test.rb
# frozen_string_literal: true require "test_helper" module ActsAsAuthenticTest class LoggedInStatusTest < ActiveSupport::TestCase ERROR_MSG = "Multiple calls to %s should result in different relations" def test_logged_in_timeout_config assert_equal 10.minutes.to_i, User.logged_in_timeout assert_equal 10.minutes.to_i, Employee.logged_in_timeout User.logged_in_timeout = 1.hour assert_equal 1.hour.to_i, User.logged_in_timeout User.logged_in_timeout 10.minutes assert_equal 10.minutes.to_i, User.logged_in_timeout end def test_named_scope_logged_in # Testing that the scope returned differs, because the time it was called should be # slightly different. This is an attempt to make sure the scope is lambda wrapped # so that it is re-evaluated every time its called. My biggest concern is that the # test happens so fast that the test fails... I just don't know a better way to test it! # for rails 5 I've changed the where_values to to_sql to compare query1 = User.logged_in.to_sql sleep 0.1 query2 = User.logged_in.to_sql assert query1 != query2, ERROR_MSG % "#logged_in" assert_equal 0, User.logged_in.count user = User.first user.last_request_at = Time.now user.current_login_at = Time.now user.save! assert_equal 1, User.logged_in.count end def test_named_scope_logged_out # Testing that the scope returned differs, because the time it was called should be # slightly different. This is an attempt to make sure the scope is lambda wrapped # so that it is re-evaluated every time its called. My biggest concern is that the # test happens so fast that the test fails... I just don't know a better way to test it! # for rails 5 I've changed the where_values to to_sql to compare assert User.logged_in.to_sql != User.logged_out.to_sql, ERROR_MSG % "#logged_out" assert_equal 3, User.logged_out.count User.first.update_attribute(:last_request_at, Time.now) assert_equal 2, User.logged_out.count end def test_logged_in_logged_out u = User.first refute u.logged_in? assert u.logged_out? u.last_request_at = Time.now assert u.logged_in? refute u.logged_out? end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/acts_as_authentic_test/login_test.rb
test/acts_as_authentic_test/login_test.rb
# frozen_string_literal: true require "test_helper" module ActsAsAuthenticTest # Miscellaneous tests for configuration options related to the `login_field`. class MiscellaneousLoginTest < ActiveSupport::TestCase def test_login_field_config assert_equal :login, User.login_field assert_nil Employee.login_field User.login_field = :nope assert_equal :nope, User.login_field User.login_field :login assert_equal :login, User.login_field end def test_find_by_smart_case_login_field # `User` is configured to be case-sensitive. (It has a case-sensitive # uniqueness validation) ben = users(:ben) assert_equal ben, User.find_by_smart_case_login_field("bjohnson") assert_nil User.find_by_smart_case_login_field("BJOHNSON") assert_nil User.find_by_smart_case_login_field("Bjohnson") # Unlike `User`, `Employee` does not have a uniqueness validation. In # the absence of such, authlogic performs a case-insensitive query. drew = employees(:drew) assert_equal drew, Employee.find_by_smart_case_login_field("dgainor@binarylogic.com") assert_equal drew, Employee.find_by_smart_case_login_field("Dgainor@binarylogic.com") assert_equal drew, Employee.find_by_smart_case_login_field("DGAINOR@BINARYLOGIC.COM") end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/acts_as_authentic_test/base_test.rb
test/acts_as_authentic_test/base_test.rb
# frozen_string_literal: true require "test_helper" module ActsAsAuthenticTest class BaseTest < ActiveSupport::TestCase def test_acts_as_authentic assert_nothing_raised do User.acts_as_authentic do end end end def test_acts_as_authentic_with_old_config assert_raise(ArgumentError) do User.acts_as_authentic({}) end end def test_acts_as_authentic_with_no_table_raise_on_model_setup_error_default klass = Class.new(ActiveRecord::Base) assert_nothing_raised do klass.acts_as_authentic end end def test_acts_as_authentic_with_no_table_raise_on_model_setup_error_enabled klass = Class.new(ActiveRecord::Base) e = assert_raises Authlogic::ModelSetupError do klass.acts_as_authentic do |c| c.raise_on_model_setup_error = true end end refute e.message.empty? end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/acts_as_authentic_test/single_access_test.rb
test/acts_as_authentic_test/single_access_test.rb
# frozen_string_literal: true require "test_helper" module ActsAsAuthenticTest class SingleAccessTest < ActiveSupport::TestCase def test_change_single_access_token_with_password_config refute User.change_single_access_token_with_password refute Employee.change_single_access_token_with_password User.change_single_access_token_with_password = true assert User.change_single_access_token_with_password User.change_single_access_token_with_password false refute User.change_single_access_token_with_password end def test_validates_uniqueness_of_single_access_token u = User.new u.single_access_token = users(:ben).single_access_token refute u.valid? refute u.errors[:single_access_token].empty? end def test_before_validation_reset_single_access_token u = User.new refute u.valid? assert_not_nil u.single_access_token end def test_after_password_set_reset_single_access_token User.change_single_access_token_with_password = true ben = users(:ben) old_single_access_token = ben.single_access_token ben.password = "new_pass" assert_not_equal old_single_access_token, ben.single_access_token User.change_single_access_token_with_password = false end def test_after_password_set_is_not_called ldaper = Ldaper.new assert ldaper.save end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/acts_as_authentic_test/session_maintenance_test.rb
test/acts_as_authentic_test/session_maintenance_test.rb
# frozen_string_literal: true require "test_helper" module ActsAsAuthenticTest class SessionMaintenanceTest < ActiveSupport::TestCase def setup User.log_in_after_create = true User.log_in_after_password_change = true end def test_log_in_after_create_config assert User.log_in_after_create User.log_in_after_create = false refute User.log_in_after_create User.log_in_after_create = true assert User.log_in_after_create end def test_log_in_after_password_change_config assert User.log_in_after_password_change User.log_in_after_password_change = false refute User.log_in_after_password_change User.log_in_after_password_change = true assert User.log_in_after_password_change end def test_login_after_create User.log_in_after_create = true user = User.create( login: "awesome", password: "saweeeet", password_confirmation: "saweeeet", email: "awesome@awesome.com" ) assert user.persisted? assert UserSession.find logged_in_user = UserSession.find.user assert_equal logged_in_user, user end def test_no_login_after_create old_user = User.create( login: "awesome", password: "saweeeet", password_confirmation: "saweeeet", email: "awesome@awesome.com" ) User.log_in_after_create = false user2 = User.create( login: "awesome2", password: "saweeeet2", password_confirmation: "saweeeet2", email: "awesome2@awesome.com" ) assert user2.persisted? logged_in_user = UserSession.find.user assert_not_equal logged_in_user, user2 assert_equal logged_in_user, old_user end def test_no_login_after_logged_out_create User.log_in_after_create = false user = User.create( login: "awesome2", password: "saweeeet2", password_confirmation: "saweeeet2", email: "awesome2@awesome.com" ) assert user.persisted? assert_nil UserSession.find end def test_updating_session_with_failed_magic_state ben = users(:ben) ben.confirmed = false ben.password = "newpasswd" ben.password_confirmation = "newpasswd" assert ben.save end def test_update_session_after_password_modify User.log_in_after_password_change = true ben = users(:ben) UserSession.create(ben) old_session_key = controller.session["user_credentials"] old_cookie_key = controller.cookies["user_credentials"] ben.password = "newpasswd" ben.password_confirmation = "newpasswd" assert ben.save assert controller.session["user_credentials"] assert controller.cookies["user_credentials"] assert_not_equal controller.session["user_credentials"], old_session_key assert_not_equal controller.cookies["user_credentials"], old_cookie_key end def test_no_update_session_after_password_modify User.log_in_after_password_change = false ben = users(:ben) UserSession.create(ben) old_session_key = controller.session["user_credentials"] old_cookie_key = controller.cookies["user_credentials"] ben.password = "newpasswd" ben.password_confirmation = "newpasswd" assert ben.save assert controller.session["user_credentials"] assert controller.cookies["user_credentials"] assert_equal controller.session["user_credentials"], old_session_key assert_equal controller.cookies["user_credentials"], old_cookie_key end def test_no_session_update_after_modify ben = users(:ben) UserSession.create(ben) old_session_key = controller.session["user_credentials"] old_cookie_key = controller.cookies["user_credentials"] ben.first_name = "Ben" assert ben.save assert_equal controller.session["user_credentials"], old_session_key assert_equal controller.cookies["user_credentials"], old_cookie_key end def test_creating_other_user ben = users(:ben) UserSession.create(ben) old_session_key = controller.session["user_credentials"] old_cookie_key = controller.cookies["user_credentials"] user = User.create( login: "awesome", password: "saweet", # Password is too short, user invalid password_confirmation: "saweet", email: "awesome@saweet.com" ) refute user.persisted? assert_equal controller.session["user_credentials"], old_session_key assert_equal controller.cookies["user_credentials"], old_cookie_key end def test_updating_other_user ben = users(:ben) UserSession.create(ben) old_session_key = controller.session["user_credentials"] old_cookie_key = controller.cookies["user_credentials"] zack = users(:zack) zack.password = "newpasswd" zack.password_confirmation = "newpasswd" assert zack.save assert_equal controller.session["user_credentials"], old_session_key assert_equal controller.cookies["user_credentials"], old_cookie_key end def test_resetting_password_when_logged_out ben = users(:ben) refute UserSession.find ben.password = "newpasswd" ben.password_confirmation = "newpasswd" assert ben.save assert UserSession.find assert_equal ben, UserSession.find.record end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/acts_as_authentic_test/password_test.rb
test/acts_as_authentic_test/password_test.rb
# frozen_string_literal: true require "test_helper" module ActsAsAuthenticTest class PasswordTest < ActiveSupport::TestCase # If test_human_name is executed after test_i18n_of_human_name the test will fail. i_suck_and_my_tests_are_order_dependent! def test_crypted_password_field_config assert_equal :crypted_password, User.crypted_password_field assert_equal :crypted_password, Employee.crypted_password_field User.crypted_password_field = :nope assert_equal :nope, User.crypted_password_field User.crypted_password_field :crypted_password assert_equal :crypted_password, User.crypted_password_field end def test_password_salt_field_config assert_equal :password_salt, User.password_salt_field assert_equal :password_salt, Employee.password_salt_field User.password_salt_field = :nope assert_equal :nope, User.password_salt_field User.password_salt_field :password_salt assert_equal :password_salt, User.password_salt_field end def test_ignore_blank_passwords_config assert User.ignore_blank_passwords assert Employee.ignore_blank_passwords User.ignore_blank_passwords = false refute User.ignore_blank_passwords User.ignore_blank_passwords true assert User.ignore_blank_passwords end def test_check_passwords_against_database assert User.check_passwords_against_database User.check_passwords_against_database = false refute User.check_passwords_against_database User.check_passwords_against_database true assert User.check_passwords_against_database end def test_crypto_provider_config assert_equal Authlogic::CryptoProviders::SCrypt, User.crypto_provider silence_warnings do User.crypto_provider = Authlogic::CryptoProviders::BCrypt end assert_equal Authlogic::CryptoProviders::BCrypt, User.crypto_provider silence_warnings do User.crypto_provider = Authlogic::CryptoProviders::Sha512 end assert_equal Authlogic::CryptoProviders::Sha512, User.crypto_provider end def test_transition_from_crypto_providers_config assert_equal [Authlogic::CryptoProviders::Sha512], User.transition_from_crypto_providers assert_equal [], Employee.transition_from_crypto_providers User.transition_from_crypto_providers = [Authlogic::CryptoProviders::BCrypt] assert_equal [Authlogic::CryptoProviders::BCrypt], User.transition_from_crypto_providers User.transition_from_crypto_providers [] assert_equal [], User.transition_from_crypto_providers end def test_password u = User.new old_password_salt = u.password_salt old_crypted_password = u.crypted_password u.password = "test" assert_not_equal old_password_salt, u.password_salt assert_not_equal old_crypted_password, u.crypted_password end def test_transitioning_password ben = users(:ben) transition_password_to(Authlogic::CryptoProviders::BCrypt, ben) transition_password_to( Authlogic::CryptoProviders::Sha1, ben, [Authlogic::CryptoProviders::Sha512, Authlogic::CryptoProviders::BCrypt] ) transition_password_to( Authlogic::CryptoProviders::Sha512, ben, [Authlogic::CryptoProviders::Sha1, Authlogic::CryptoProviders::BCrypt] ) end def test_v2_crypto_provider_transition ben = users(:ben) providers = [ Authlogic::CryptoProviders::Sha512::V2, Authlogic::CryptoProviders::MD5::V2, Authlogic::CryptoProviders::Sha1::V2, Authlogic::CryptoProviders::Sha256::V2 ] transition_password_to(providers[0], ben) providers.each_cons(2) do |old_provider, new_provider| transition_password_to( new_provider, ben, old_provider ) end end def test_checks_password_against_database ben = users(:aaron) ben.password = "new pass" refute ben.valid_password?("new pass") assert ben.valid_password?("aaronrocks") end def test_checks_password_against_database_and_always_fails_on_new_records user = User.new user.password = "new pass" refute user.valid_password?("new pass") end def test_checks_password_against_object ben = users(:ben) ben.password = "new pass" assert ben.valid_password?("new pass", false) refute ben.valid_password?("benrocks", false) end def test_reset_password ben = users(:ben) old_crypted_password = ben.crypted_password old_password_salt = ben.password_salt # soft reset ben.reset_password assert_not_equal old_crypted_password, ben.crypted_password assert_not_equal old_password_salt, ben.password_salt # make sure it didn't go into the db ben.reload assert_equal old_crypted_password, ben.crypted_password assert_equal old_password_salt, ben.password_salt # hard reset assert ben.reset_password! assert_not_equal old_crypted_password, ben.crypted_password assert_not_equal old_password_salt, ben.password_salt # make sure it did go into the db ben.reload assert_not_equal old_crypted_password, ben.crypted_password assert_not_equal old_password_salt, ben.password_salt end def test_reset_password_in_after_save lumbergh = admins(:lumbergh) old_crypted_password = lumbergh.crypted_password lumbergh.role = "Stapler Supervisor" lumbergh.save! # Because his `role` changed, the `after_save` callback in admin.rb will # reset Lumbergh's password. assert_not_equal old_crypted_password, lumbergh.crypted_password # Lumbergh's perishable_token has also changed, but that's not relevant # to this test because perishable_token always changes whenever you save # anything (unless you `disable_perishable_token_maintenance`). end private def transition_password_to( crypto_provider, records, from_crypto_providers = Authlogic::CryptoProviders::Sha512 ) records = [records] unless records.is_a?(Array) User.acts_as_authentic do |c| silence_warnings do c.crypto_provider = crypto_provider end c.transition_from_crypto_providers = from_crypto_providers end records.each do |record| old_hash = record.crypted_password old_persistence_token = record.persistence_token assert record.valid_password?(password_for(record)) assert_not_equal old_hash.to_s, record.crypted_password.to_s assert_not_equal old_persistence_token.to_s, record.persistence_token.to_s old_hash = record.crypted_password old_persistence_token = record.persistence_token assert record.valid_password?(password_for(record)) assert_equal old_hash.to_s, record.crypted_password.to_s assert_equal old_persistence_token.to_s, record.persistence_token.to_s end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/libs/employee_session.rb
test/libs/employee_session.rb
# frozen_string_literal: true class EmployeeSession < Authlogic::Session::Base end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/libs/affiliate.rb
test/libs/affiliate.rb
# frozen_string_literal: true class Affiliate < ActiveRecord::Base acts_as_authentic do |c| c.crypted_password_field = :pw_hash end belongs_to :company end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/libs/project.rb
test/libs/project.rb
# frozen_string_literal: true class Project < ActiveRecord::Base has_and_belongs_to_many :users end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/libs/user_session.rb
test/libs/user_session.rb
# frozen_string_literal: true class UserSession < Authlogic::Session::Base end class BackOfficeUserSession < Authlogic::Session::Base end class WackyUserSession < Authlogic::Session::Base attr_accessor :counter authenticate_with User def initialize @counter = 0 super end def persist_by_false self.counter += 1 false end def persist_by_true self.counter += 1 true end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/libs/employee.rb
test/libs/employee.rb
# frozen_string_literal: true class Employee < ActiveRecord::Base acts_as_authentic do |config| silence_warnings do config.crypto_provider = Authlogic::CryptoProviders::Sha512 end end belongs_to :company end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/libs/ldaper.rb
test/libs/ldaper.rb
# frozen_string_literal: true class Ldaper < ActiveRecord::Base acts_as_authentic end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/libs/admin_session.rb
test/libs/admin_session.rb
# frozen_string_literal: true class AdminSession < Authlogic::Session::Base end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/libs/admin.rb
test/libs/admin.rb
# frozen_string_literal: true # This model demonstrates an `after_save` callback. class Admin < ActiveRecord::Base acts_as_authentic do |c| c.crypto_provider = Authlogic::CryptoProviders::SCrypt end validates :password, confirmation: true after_save do # In rails 5.1 `role_changed?` was deprecated in favor of `saved_change_to_role?`. # # > DEPRECATION WARNING: The behavior of `attribute_changed?` inside of # > after callbacks will be changing in the next version of Rails. # > The new return value will reflect the behavior of calling the method # > after `save` returned (e.g. the opposite of what it returns now). To # > maintain the current behavior, use `saved_change_to_attribute?` instead. # # So, in rails >= 5.2, we must use `saved_change_to_role?`. if saved_change_to_role? reset_password! end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/libs/company.rb
test/libs/company.rb
# frozen_string_literal: true class Company < ActiveRecord::Base has_many :employees, dependent: :destroy has_many :users, dependent: :destroy end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/test/libs/user.rb
test/libs/user.rb
# frozen_string_literal: true class User < ActiveRecord::Base EMAIL = / \A [A-Z0-9_.&%+\-']+ # mailbox @ (?:[A-Z0-9\-]+\.)+ # subdomains (?:[A-Z]{2,25}) # TLD \z /ix.freeze LOGIN = /\A[a-zA-Z0-9_][a-zA-Z0-9\.+\-_@ ]+\z/.freeze acts_as_authentic do |c| c.crypto_provider = Authlogic::CryptoProviders::SCrypt c.transition_from_crypto_providers Authlogic::CryptoProviders::Sha512 end belongs_to :company has_and_belongs_to_many :projects # Validations # ----------- # # In Authlogic 4.4.0, we deprecated the features of Authlogic related to # validating email, login, and password. In 5.0.0 these features were dropped. # People will instead use normal ActiveRecord validations. # # The following validations represent what Authlogic < 5 used as defaults. validates :email, format: { with: EMAIL, message: proc { ::Authlogic::I18n.t( "error_messages.email_invalid", default: "should look like an email address." ) } }, length: { maximum: 100 }, uniqueness: { case_sensitive: false, if: :will_save_change_to_email? } validates :login, format: { with: LOGIN, message: proc { ::Authlogic::I18n.t( "error_messages.login_invalid", default: "should use only letters, numbers, spaces, and .-_@+ please." ) } }, length: { within: 3..100 }, uniqueness: { # Our User model will test `case_sensitive: true`. Other models, like # Employee and Admin do not validate uniqueness, and thus, for them, # `find_by_smart_case_login_field` will be case-insensitive. See eg. # `test_find_by_smart_case_login_field` in # `test/acts_as_authentic_test/login_test.rb` case_sensitive: true, if: :will_save_change_to_login? } validates :password, confirmation: { if: :require_password? }, length: { minimum: 8, if: :require_password? } validates :password_confirmation, length: { minimum: 8, if: :require_password? } end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic.rb
lib/authlogic.rb
# frozen_string_literal: true require_relative "authlogic/errors" require_relative "authlogic/i18n" require_relative "authlogic/random" require_relative "authlogic/config" require_relative "authlogic/controller_adapters/abstract_adapter" require_relative "authlogic/cookie_credentials" require_relative "authlogic/crypto_providers" require_relative "authlogic/acts_as_authentic/email" require_relative "authlogic/acts_as_authentic/logged_in_status" require_relative "authlogic/acts_as_authentic/login" require_relative "authlogic/acts_as_authentic/magic_columns" require_relative "authlogic/acts_as_authentic/password" require_relative "authlogic/acts_as_authentic/perishable_token" require_relative "authlogic/acts_as_authentic/persistence_token" require_relative "authlogic/acts_as_authentic/session_maintenance" require_relative "authlogic/acts_as_authentic/single_access_token" require_relative "authlogic/acts_as_authentic/base" require_relative "authlogic/session/magic_column/assigns_last_request_at" require_relative "authlogic/session/base" # Authlogic uses ActiveSupport's core extensions like `strip_heredoc` and # `squish`. ActiveRecord does not `require` these exensions, so we must. # # It's possible that we could save a few milliseconds by loading only the # specific core extensions we need, but `all.rb` is simpler. We can revisit this # decision if it becomes a problem. require "active_support/all" require_relative "authlogic/controller_adapters/rails_adapter" if defined?(Rails) require_relative "authlogic/controller_adapters/sinatra_adapter" if defined?(Sinatra)
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/test_case.rb
lib/authlogic/test_case.rb
# frozen_string_literal: true require_relative "test_case/rails_request_adapter" require_relative "test_case/mock_api_controller" require_relative "test_case/mock_cookie_jar" require_relative "test_case/mock_controller" require_relative "test_case/mock_logger" require_relative "test_case/mock_request" # :nodoc: module Authlogic # This module is a collection of methods and classes that help you easily test # Authlogic. In fact, I use these same tools to test the internals of # Authlogic. # # === The quick and dirty # # require "authlogic/test_case" # include at the top of test_helper.rb # setup :activate_authlogic # run before tests are executed # UserSession.create(users(:whomever)) # logs a user in # # For a more detailed explanation, see below. # # === Setting up # # Authlogic comes with some simple testing tools. To get these, you need to # first require Authlogic's TestCase. If you are doing this in a rails app, # you would require this file at the top of your test_helper.rb file: # # require "authlogic/test_case" # # If you are using Test::Unit::TestCase, the standard testing library that # comes with ruby, then you can skip this next part. If you are not, you need # to include the Authlogic::TestCase into your testing suite as follows: # # include Authlogic::TestCase # # Now that everything is ready to go, let's move onto actually testing. Here # is the basic idea behind testing: # # Authlogic requires a "connection" to your controller to activate it. In the # same manner that ActiveRecord requires a connection to your database. It # can't do anything until it gets connected. That being said, Authlogic will # raise an Authlogic::Session::Activation::NotActivatedError any time you try # to instantiate an object without a "connection". So before you do anything # with Authlogic, you need to activate / connect Authlogic. Let's walk through # how to do this in tests: # # === Fixtures / Factories # # Creating users via fixtures / factories is easy. Here's an example of a # fixture: # # ben: # email: whatever@whatever.com # password_salt: <%= salt = Authlogic::Random.hex_token %> # crypted_password: <%= Authlogic::CryptoProviders::SCrypt.encrypt("benrocks" + salt) %> # persistence_token: <%= Authlogic::Random.hex_token %> # single_access_token: <%= Authlogic::Random.friendly_token %> # perishable_token: <%= Authlogic::Random.friendly_token %> # # Notice the crypted_password value. Just supplement that with whatever crypto # provider you are using, if you are not using the default. # # === Functional tests # # Activating Authlogic isn't a problem here, because making a request will # activate Authlogic for you. The problem is logging users in so they can # access restricted areas. Solving this is simple, just do this: # # setup :activate_authlogic # # For those of you unfamiliar with TestUnit, the setup method basically just # executes a method before any test is ran. It is essentially "setting up" # your tests. # # Once you have done this, just log users in like usual: # # UserSession.create(users(:whomever)) # # access my restricted area here # # Do this before you make your request and it will act as if that user is # logged in. # # === Integration tests # # Again, just like functional tests, you don't have to do anything. As soon as # you make a request, Authlogic will be connected. If you want to activate # Authlogic before making a request follow the same steps described in the # "functional tests" section above. It works in the same manner. # # === Unit tests # # The only time you need to do any trickiness here is if you want to test # Authlogic models. Maybe you added some custom code or methods in your # Authlogic models. Maybe you are writing a plugin or a library that extends # Authlogic. # # That being said, in this environment there is no controller. So you need to # use a "mock" controller. Something that looks like a controller, acts like a # controller, but isn't a "real" controller. You are essentially connecting # Authlogic to your "mock" controller, then you can test off of the mock # controller to make sure everything is functioning properly. # # I use a mock controller to test Authlogic myself. It's part of the Authlogic # library that you can easily use. It's as simple as functional and # integration tests. Just do the following: # # setup :activate_authlogic # # You also get a controller method that you can test off of. For example: # # ben = users(:ben) # assert_nil controller.session["user_credentials"] # assert UserSession.create(ben) # assert_equal controller.session["user_credentials"], ben.persistence_token # # See how I am checking that Authlogic is interacting with the controller # properly? That's the idea here. # # === Testing with Rails 5 # # Rails 5 has [deprecated classic controller tests](https://goo.gl/4zmt6y). # Controller tests now inherit from `ActionDispatch::IntegrationTest` making # them plain old integration tests now. You have two options for testing # AuthLogic in Rails 5: # # * Add the `rails-controller-testing` gem to bring back the original # controller testing usage # * Go full steam ahead with integration testing and actually log a user in # by submitting a form in the integration test. # # Naturally DHH recommends the second method and this is # [what he does in his own tests](https://goo.gl/Ar6p0u). This is useful # for testing not only AuthLogic itself (submitting login credentials to a # UserSessionsController, for example) but any controller action that is # behind a login wall. Add a helper method and use that before testing your # actual controller action: # # # test/test_helper.rb # def login(user) # post user_sessions_url, :params => { :email => user.email, :password => 'password' } # end # # # test/controllers/posts_controller_test.rb # test "#create requires a user to be logged in # post posts_url, :params => { :body => 'Lorem ipsum' } # # assert_redirected_to new_user_session_url # end # # test "#create lets a logged in user create a new post" do # login(users(:admin)) # # assert_difference 'Posts.count' do # post posts_url, :params => { :body => 'Lorem ipsum' } # end # # assert_redirected_to posts_url # end # # You still have access to the `session` helper in an integration test and so # you can still test to see if a user is logged in. A couple of helper methods # might look like: # # # test/test_helper.rb # def assert_logged_in # assert session[:user_credentials].present? # end # # def assert_not_logged_in # assert session[:user_credentials].blank? # end # # # test/user_sessions_controller_test.rb # test "#create logs in a user" do # login(users(:admin)) # # assert_logged_in # end module TestCase def initialize(*args) @request = nil super end # Activates authlogic so that you can use it in your tests. You should call # this method in your test's setup. Ex: # # setup :activate_authlogic def activate_authlogic if @request && !@request.respond_to?(:params) class <<@request alias_method :params, :parameters end end Authlogic::Session::Base.controller = @request && Authlogic::TestCase::RailsRequestAdapter.new(@request) || controller end # The Authlogic::TestCase::MockController object passed to Authlogic to # activate it. You can access this in your test. See the module description # for an example. def controller @controller ||= Authlogic::TestCase::MockController.new end end # TODO: Why are these lines inside the `Authlogic` module? Should be outside? ::Test::Unit::TestCase.include(TestCase) if defined?(::Test::Unit::TestCase) ::MiniTest::Unit::TestCase.include(TestCase) if defined?(::MiniTest::Unit::TestCase) ::MiniTest::Test.include(TestCase) if defined?(::MiniTest::Test) end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/version.rb
lib/authlogic/version.rb
# frozen_string_literal: true # :nodoc: module Authlogic # Returns a `::Gem::Version`, the version number of the authlogic gem. # # It is preferable for a library to provide a `gem_version` method, rather # than a `VERSION` string, because `::Gem::Version` is easier to use in a # comparison. # # We cannot return a frozen `Version`, because rubygems will try to modify it. # https://github.com/binarylogic/authlogic/pull/590 # # Added in 4.0.0 # # @api public def self.gem_version ::Gem::Version.new("6.6.0") end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/errors.rb
lib/authlogic/errors.rb
# frozen_string_literal: true module Authlogic # Parent class of all Authlogic errors. class Error < StandardError end # :nodoc: class InvalidCryptoProvider < Error end # :nodoc: class NilCryptoProvider < InvalidCryptoProvider def message <<~EOS In version 5, Authlogic used SCrypt by default. As of version 6, there is no default. We still recommend SCrypt. If you previously relied on this default, then, in your User model (or equivalent), please set the following: acts_as_authentic do |c| c.crypto_provider = ::Authlogic::CryptoProviders::SCrypt end Furthermore, the authlogic gem no longer depends on the scrypt gem. In your Gemfile, please add scrypt. gem "scrypt", "~> 3.0" We have made this change in Authlogic 6 so that users of other crypto providers no longer need to install the scrypt gem. EOS end end # :nodoc: class ModelSetupError < Error def message <<-EOS You must establish a database connection and run the migrations before using acts_as_authentic. If you need to load the User model before the database is set up correctly, please set the following: acts_as_authentic do |c| c.raise_on_model_setup_error = false end EOS end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/crypto_providers.rb
lib/authlogic/crypto_providers.rb
# frozen_string_literal: true module Authlogic # The acts_as_authentic method has a crypto_provider option. This allows you # to use any type of encryption you like. Just create a class with a class # level encrypt and matches? method. See example below. # # === Example # # class MyAwesomeEncryptionMethod # def self.encrypt(*tokens) # # The tokens passed will be an array of objects, what type of object # # is irrelevant, just do what you need to do with them and return a # # single encrypted string. For example, you will most likely join all # # of the objects into a single string and then encrypt that string. # end # # def self.matches?(crypted, *tokens) # # Return true if the crypted string matches the tokens. Depending on # # your algorithm you might decrypt the string then compare it to the # # token, or you might encrypt the tokens and make sure it matches the # # crypted string, its up to you. # end # end module CryptoProviders autoload :MD5, "authlogic/crypto_providers/md5" autoload :Sha1, "authlogic/crypto_providers/sha1" autoload :Sha256, "authlogic/crypto_providers/sha256" autoload :Sha512, "authlogic/crypto_providers/sha512" autoload :BCrypt, "authlogic/crypto_providers/bcrypt" autoload :SCrypt, "authlogic/crypto_providers/scrypt" # Guide users to choose a better crypto provider. class Guidance BUILTIN_PROVIDER_PREFIX = "Authlogic::CryptoProviders::" NONADAPTIVE_ALGORITHM = <<~EOS You have selected %s as your authlogic crypto provider. This algorithm does not have any practical known attacks against it. However, there are better choices. Authlogic has no plans yet to deprecate this crypto provider. However, we recommend transitioning to a more secure, adaptive hashing algorithm, like scrypt. Adaptive algorithms are designed to slow down brute force attacks, and over time the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even in the face of increasing computation power. Use the transition_from_crypto_providers option to make the transition painless for your users. EOS VULNERABLE_ALGORITHM = <<~EOS You have selected %s as your authlogic crypto provider. It is a poor choice because there are known attacks against this algorithm. Authlogic has no plans yet to deprecate this crypto provider. However, we recommend transitioning to a secure hashing algorithm. We recommend an adaptive algorithm, like scrypt. Use the transition_from_crypto_providers option to make the transition painless for your users. EOS def initialize(provider) @provider = provider end def impart_wisdom return unless @provider.is_a?(Class) # We can only impart wisdom about our own built-in providers. absolute_name = @provider.name return unless absolute_name.start_with?(BUILTIN_PROVIDER_PREFIX) # Inspect the string name of the provider, rather than using the # constants in our `when` clauses. If we used the constants, we'd # negate the benefits of the `autoload` above. name = absolute_name.demodulize case name when "MD5", "Sha1" warn(format(VULNERABLE_ALGORITHM, name)) when "Sha256", "Sha512" warn(format(NONADAPTIVE_ALGORITHM, name)) end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/i18n.rb
lib/authlogic/i18n.rb
# frozen_string_literal: true require_relative "i18n/translator" module Authlogic # This class allows any message in Authlogic to use internationalization. In # earlier versions of Authlogic each message was translated via configuration. # This cluttered up the configuration and cluttered up Authlogic. So all # translation has been extracted out into this class. Now all messages pass # through this class, making it much easier to implement in I18n library / # plugin you want. Use this as a layer that sits between Authlogic and # whatever I18n library you want to use. # # By default this uses the rails I18n library, if it exists. If it doesn't # exist it just returns the default English message. The Authlogic I18n class # works EXACTLY like the rails I18n class. This is because the arguments are # delegated to this class. # # Here is how all messages are translated internally with Authlogic: # # Authlogic::I18n.t('error_messages.password_invalid', :default => "is invalid") # # If you use a different I18n library just replace the build-in # I18n::Translator class with your own. For example: # # class MyAuthlogicI18nTranslator # def translate(key, options = {}) # # you will have key which will be something like: # # "error_messages.password_invalid" # # you will also have options[:default], which will be the default # # English version of the message # # do whatever you want here with the arguments passed to you. # end # end # # Authlogic::I18n.translator = MyAuthlogicI18nTranslator.new # # That it's! Here is a complete list of the keys that are passed. Just define # these however you wish: # # authlogic: # error_messages: # login_blank: can not be blank # login_not_found: is not valid # login_invalid: should use only letters, numbers, spaces, and .-_@+ please. # consecutive_failed_logins_limit_exceeded: > # Consecutive failed logins limit exceeded, account is disabled. # email_invalid: should look like an email address. # email_invalid_international: should look like an international email address. # password_blank: can not be blank # password_invalid: is not valid # not_active: Your account is not active # not_confirmed: Your account is not confirmed # not_approved: Your account is not approved # no_authentication_details: You did not provide any details for authentication. # general_credentials_error: Login/Password combination is not valid # session_invalid: Your session is invalid and has the following errors: # models: # user_session: UserSession (or whatever name you are using) # attributes: # user_session: (or whatever name you are using) # login: login # email: email # password: password # remember_me: remember me module I18n @@scope = :authlogic @@translator = nil class << self # Returns the current scope. Defaults to :authlogic def scope @@scope end # Sets the current scope. Used to set a custom scope. def scope=(scope) @@scope = scope end # Returns the current translator. Defaults to +Translator+. def translator @@translator ||= Translator.new end # Sets the current translator. Used to set a custom translator. def translator=(translator) @@translator = translator end # All message translation is passed to this method. The first argument is # the key for the message. The second is options, see the rails I18n # library for a list of options used. def translate(key, options = {}) translator.translate key, { scope: I18n.scope }.merge(options) end alias t translate end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/random.rb
lib/authlogic/random.rb
# frozen_string_literal: true require "securerandom" module Authlogic # Generates random strings using ruby's SecureRandom library. module Random def self.hex_token SecureRandom.hex(64) end # Returns a string in base64url format as defined by RFC-3548 and RFC-4648. # We call this a "friendly" token because it is short and safe for URLs. def self.friendly_token SecureRandom.urlsafe_base64(15) end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/config.rb
lib/authlogic/config.rb
# frozen_string_literal: true module Authlogic # Mixed into `Authlogic::ActsAsAuthentic::Base` and # `Authlogic::Session::Base`. module Config E_USE_NORMAL_RAILS_VALIDATION = <<~EOS This Authlogic configuration option (%s) is deprecated. Use normal ActiveRecord validation instead. Detailed instructions: https://github.com/binarylogic/authlogic/blob/master/doc/use_normal_rails_validation.md EOS def self.extended(klass) klass.class_eval do # TODO: Is this a confusing name, given this module is mixed into # both `Authlogic::ActsAsAuthentic::Base` and # `Authlogic::Session::Base`? Perhaps a more generic name, like # `authlogic_config` would be better? class_attribute :acts_as_authentic_config self.acts_as_authentic_config ||= {} end end private def deprecate_authlogic_config(method_name) ::ActiveSupport::Deprecation.new.warn( format(E_USE_NORMAL_RAILS_VALIDATION, method_name) ) end # This is a one-liner method to write a config setting, read the config # setting, and also set a default value for the setting. def rw_config(key, value, default_value = nil) if value.nil? acts_as_authentic_config.include?(key) ? acts_as_authentic_config[key] : default_value else self.acts_as_authentic_config = acts_as_authentic_config.merge(key => value) value end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/cookie_credentials.rb
lib/authlogic/cookie_credentials.rb
# frozen_string_literal: true module Authlogic # Represents the credentials *in* the cookie. The value of the cookie. # This is primarily a data object. It doesn't interact with controllers. # It doesn't know about eg. cookie expiration. # # @api private class CookieCredentials # @api private class ParseError < RuntimeError end DELIMITER = "::" attr_reader :persistence_token, :record_id, :remember_me_until # @api private # @param persistence_token [String] # @param record_id [String, Numeric] # @param remember_me_until [ActiveSupport::TimeWithZone] def initialize(persistence_token, record_id, remember_me_until) @persistence_token = persistence_token @record_id = record_id @remember_me_until = remember_me_until end class << self # @api private def parse(string) parts = string.split(DELIMITER) unless (1..3).cover?(parts.length) raise ParseError, format("Expected 1..3 parts, got %d", parts.length) end new(parts[0], parts[1], parse_time(parts[2])) end private # @api private def parse_time(string) return if string.nil? ::Time.parse(string) rescue ::ArgumentError => e raise ParseError, format("Found cookie, cannot parse remember_me_until: #{e}") end end # @api private def remember_me? !@remember_me_until.nil? end # @api private def to_s [ @persistence_token, @record_id.to_s, @remember_me_until&.iso8601 ].compact.join(DELIMITER) end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/acts_as_authentic/password.rb
lib/authlogic/acts_as_authentic/password.rb
# frozen_string_literal: true module Authlogic module ActsAsAuthentic # This module has a lot of neat functionality. It is responsible for encrypting your # password, salting it, and verifying it. It can also help you transition to a new # encryption algorithm. See the Config sub module for configuration options. module Password def self.included(klass) klass.class_eval do extend Config add_acts_as_authentic_module(Callbacks) add_acts_as_authentic_module(Methods) end end # All configuration for the password aspect of acts_as_authentic. module Config # The name of the crypted_password field in the database. # # * <tt>Default:</tt> :crypted_password, :encrypted_password, :password_hash, or :pw_hash # * <tt>Accepts:</tt> Symbol def crypted_password_field(value = nil) rw_config( :crypted_password_field, value, first_column_to_exist( nil, :crypted_password, :encrypted_password, :password_hash, :pw_hash ) ) end alias crypted_password_field= crypted_password_field # The name of the password_salt field in the database. # # * <tt>Default:</tt> :password_salt, :pw_salt, :salt, nil if none exist # * <tt>Accepts:</tt> Symbol def password_salt_field(value = nil) rw_config( :password_salt_field, value, first_column_to_exist(nil, :password_salt, :pw_salt, :salt) ) end alias password_salt_field= password_salt_field # Whether or not to require a password confirmation. If you don't want your users # to confirm their password just set this to false. # # * <tt>Default:</tt> true # * <tt>Accepts:</tt> Boolean def require_password_confirmation(value = nil) rw_config(:require_password_confirmation, value, true) end alias require_password_confirmation= require_password_confirmation # By default passwords are required when a record is new or the crypted_password # is blank, but if both of these things are met a password is not required. In # this case, blank passwords are ignored. # # Think about a profile page, where the user can edit all of their information, # including changing their password. If they do not want to change their password # they just leave the fields blank. This will try to set the password to a blank # value, in which case is incorrect behavior. As such, Authlogic ignores this. But # let's say you have a completely separate page for resetting passwords, you might # not want to ignore blank passwords. If this is the case for you, then just set # this value to false. # # * <tt>Default:</tt> true # * <tt>Accepts:</tt> Boolean def ignore_blank_passwords(value = nil) rw_config(:ignore_blank_passwords, value, true) end alias ignore_blank_passwords= ignore_blank_passwords # When calling valid_password?("some pass") do you want to check that password # against what's in that object or whats in the database. Take this example: # # u = User.first # u.password = "new pass" # u.valid_password?("old pass") # # Should the last line above return true or false? The record hasn't been saved # yet, so most would assume true. Other would assume false. So I let you decide by # giving you this option. # # * <tt>Default:</tt> true # * <tt>Accepts:</tt> Boolean def check_passwords_against_database(value = nil) rw_config(:check_passwords_against_database, value, true) end alias check_passwords_against_database= check_passwords_against_database # The class you want to use to encrypt and verify your encrypted # passwords. See the Authlogic::CryptoProviders module for more info on # the available methods and how to create your own. # # The family of adaptive hash functions (BCrypt, SCrypt, PBKDF2) is the # best choice for password storage today. We recommend SCrypt. Other # one-way functions like SHA512 are inferior, but widely used. # Reversible functions like AES256 are the worst choice, and we no # longer support them. # # You can use the `transition_from_crypto_providers` option to gradually # transition to a better crypto provider without causing your users any # pain. # # * <tt>Default:</tt> There is no longer a default value. Prior to # Authlogic 6, the default was `CryptoProviders::SCrypt`. If you try # to read this config option before setting it, it will raise a # `NilCryptoProvider` error. See that error's message for further # details, and rationale for this change. # * <tt>Accepts:</tt> Class def crypto_provider acts_as_authentic_config[:crypto_provider].tap { |provider| raise NilCryptoProvider if provider.nil? } end def crypto_provider=(value) raise NilCryptoProvider if value.nil? CryptoProviders::Guidance.new(value).impart_wisdom rw_config(:crypto_provider, value) end # Let's say you originally encrypted your passwords with Sha1. Sha1 is # starting to join the party with MD5 and you want to switch to # something stronger. No problem, just specify your new and improved # algorithm with the crypt_provider option and then let Authlogic know # you are transitioning from Sha1 using this option. Authlogic will take # care of everything, including transitioning your users to the new # algorithm. The next time a user logs in, they will be granted access # using the old algorithm and their password will be resaved with the # new algorithm. All new users will obviously use the new algorithm as # well. # # Lastly, if you want to transition again, you can pass an array of # crypto providers. So you can transition from as many algorithms as you # want. # # * <tt>Default:</tt> nil # * <tt>Accepts:</tt> Class or Array def transition_from_crypto_providers(value = nil) rw_config( :transition_from_crypto_providers, (!value.nil? && [value].flatten.compact) || value, [] ) end alias transition_from_crypto_providers= transition_from_crypto_providers end # Callbacks / hooks to allow other modules to modify the behavior of this module. module Callbacks # Does the order of this array matter? METHODS = %w[ password_set password_verification ].freeze def self.included(klass) return if klass.crypted_password_field.nil? klass.send :extend, ActiveModel::Callbacks METHODS.each do |method| klass.define_model_callbacks method, only: %i[before after] end end end # The methods related to the password field. module Methods def self.included(klass) return if klass.crypted_password_field.nil? klass.class_eval do include InstanceMethods after_save :reset_password_changed end end # :nodoc: module InstanceMethods # The password def password return nil unless defined?(@password) @password end # This is a virtual method. Once a password is passed to it, it will # create new password salt as well as encrypt the password. def password=(pass) return if ignore_blank_passwords? && pass.blank? run_callbacks :password_set do @password = pass if password_salt_field send("#{password_salt_field}=", Authlogic::Random.friendly_token) end send( "#{crypted_password_field}=", crypto_provider.encrypt(*encrypt_arguments(@password, false)) ) @password_changed = true end end # Accepts a raw password to determine if it is the correct password. # # - attempted_password [String] - password entered by user # - check_against_database [boolean] - Should we check the password # against the value in the database or the value in the object? # Default taken from config option check_passwords_against_database. # See config method for more information. def valid_password?( attempted_password, check_against_database = check_passwords_against_database? ) crypted = crypted_password_to_validate_against(check_against_database) return false if attempted_password.blank? || crypted.blank? run_callbacks :password_verification do crypto_providers.each_with_index.any? do |encryptor, index| if encryptor_matches?( crypted, encryptor, attempted_password, check_against_database ) if transition_password?(index, encryptor, check_against_database) transition_password(attempted_password) end true else false end end end end # Resets the password to a random friendly token. def reset_password friendly_token = Authlogic::Random.friendly_token self.password = friendly_token self.password_confirmation = friendly_token if self.class.require_password_confirmation end alias randomize_password reset_password # Resets the password to a random friendly token and then saves the record. def reset_password! reset_password save_without_session_maintenance(validate: false) end alias randomize_password! reset_password! private def crypted_password_to_validate_against(check_against_database) if check_against_database && send("will_save_change_to_#{crypted_password_field}?") send("#{crypted_password_field}_in_database") else send(crypted_password_field) end end def check_passwords_against_database? self.class.check_passwords_against_database == true end def crypto_providers [crypto_provider] + transition_from_crypto_providers end # Returns an array of arguments to be passed to a crypto provider, either its # `matches?` or its `encrypt` method. def encrypt_arguments(raw_password, check_against_database) salt = nil if password_salt_field salt = if check_against_database && send("will_save_change_to_#{password_salt_field}?") send("#{password_salt_field}_in_database") else send(password_salt_field) end end [raw_password, salt].compact end # Given `encryptor`, does `attempted_password` match the `crypted` password? def encryptor_matches?(crypted, encryptor, attempted_password, check_against_database) encryptor_args = encrypt_arguments(attempted_password, check_against_database) encryptor.matches?(crypted, *encryptor_args) end # Determines if we need to transition the password. # # - If the index > 0 then we are using a "transition from" crypto # provider. # - If the encryptor has a cost and the cost it outdated. # - If we aren't using database values # - If we are using database values, only if the password hasn't # changed so we don't overwrite any changes def transition_password?(index, encryptor, check_against_database) ( index > 0 || (encryptor.respond_to?(:cost_matches?) && !encryptor.cost_matches?(send(crypted_password_field))) ) && ( !check_against_database || !send("will_save_change_to_#{crypted_password_field}?") ) end def transition_password(attempted_password) self.password = attempted_password save(validate: false) end def require_password? # this is _not_ the activemodel changed? method, see below new_record? || password_changed? || send(crypted_password_field).blank? end def ignore_blank_passwords? self.class.ignore_blank_passwords == true end def password_changed? defined?(@password_changed) && @password_changed == true end def reset_password_changed @password_changed = nil end def crypted_password_field self.class.crypted_password_field end def password_salt_field self.class.password_salt_field end def crypto_provider self.class.crypto_provider end def transition_from_crypto_providers self.class.transition_from_crypto_providers end end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/acts_as_authentic/session_maintenance.rb
lib/authlogic/acts_as_authentic/session_maintenance.rb
# frozen_string_literal: true module Authlogic module ActsAsAuthentic # This is one of my favorite features that I think is pretty cool. It's # things like this that make a library great and let you know you are on the # right track. # # Just to clear up any confusion, Authlogic stores both the record id and # the persistence token in the session. Why? So stale sessions can not be # persisted. It stores the id so it can quickly find the record, and the # persistence token to ensure no sessions are stale. So if the persistence # token changes, the user must log back in. # # Well, the persistence token changes with the password. What happens if the # user changes his own password? He shouldn't have to log back in, he's the # one that made the change. # # That being said, wouldn't it be nice if their session and cookie # information was automatically updated? Instead of cluttering up your # controller with redundant session code. The same thing goes for new # registrations. # # That's what this module is all about. This will automatically maintain the # cookie and session values as records are saved. module SessionMaintenance def self.included(klass) klass.class_eval do extend Config add_acts_as_authentic_module(Methods) end end # Configuration for the session maintenance aspect of acts_as_authentic. # These methods become class methods of ::ActiveRecord::Base. module Config # In order to turn off automatic maintenance of sessions # after create, just set this to false. # # * <tt>Default:</tt> true # * <tt>Accepts:</tt> Boolean def log_in_after_create(value = nil) rw_config(:log_in_after_create, value, true) end alias log_in_after_create= log_in_after_create # In order to turn off automatic maintenance of sessions when updating # the password, just set this to false. # # * <tt>Default:</tt> true # * <tt>Accepts:</tt> Boolean def log_in_after_password_change(value = nil) rw_config(:log_in_after_password_change, value, true) end alias log_in_after_password_change= log_in_after_password_change # As you may know, authlogic sessions can be separate by id (See # Authlogic::Session::Base#id). You can specify here what session ids # you want auto maintained. By default it is the main session, which has # an id of nil. # # * <tt>Default:</tt> [nil] # * <tt>Accepts:</tt> Array def session_ids(value = nil) rw_config(:session_ids, value, [nil]) end alias session_ids= session_ids # The name of the associated session class. This is inferred by the name # of the model. # # * <tt>Default:</tt> "#{klass.name}Session".constantize # * <tt>Accepts:</tt> Class def session_class(value = nil) const = begin "#{base_class.name}Session".constantize rescue NameError nil end rw_config(:session_class, value, const) end alias session_class= session_class end # This module, as one of the `acts_as_authentic_modules`, is only included # into an ActiveRecord model if that model calls `acts_as_authentic`. module Methods def self.included(klass) klass.class_eval do before_save :get_session_information, if: :update_sessions? before_save :maintain_sessions, if: :update_sessions? end end # Save the record and skip session maintenance all together. def save_without_session_maintenance(**options) self.skip_session_maintenance = true result = save(**options) self.skip_session_maintenance = false result end private def skip_session_maintenance=(value) @skip_session_maintenance = value end def skip_session_maintenance @skip_session_maintenance ||= false end def update_sessions? !skip_session_maintenance && session_class && session_class.activated? && maintain_session? && !session_ids.blank? && will_save_change_to_persistence_token? end def maintain_session? log_in_after_create? || log_in_after_password_change? end def get_session_information # Need to determine if we are completely logged out, or logged in as # another user. @_sessions = [] session_ids.each do |session_id| session = session_class.find(session_id, self) @_sessions << session if session&.record end end def maintain_sessions if @_sessions.empty? create_session else update_sessions end end def create_session # We only want to automatically login into the first session, since # this is the main session. The other sessions are sessions that # need to be created after logging into the main session. session_id = session_ids.first session_class.create(*[self, self, session_id].compact) true end def update_sessions # We found sessions above, let's update them with the new info @_sessions.each do |stale_session| next if stale_session.record != self stale_session.unauthorized_record = self stale_session.save end true end def session_ids self.class.session_ids end def session_class self.class.session_class end def log_in_after_create? new_record? && self.class.log_in_after_create end def log_in_after_password_change? persisted? && will_save_change_to_persistence_token? && self.class.log_in_after_password_change end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/acts_as_authentic/magic_columns.rb
lib/authlogic/acts_as_authentic/magic_columns.rb
# frozen_string_literal: true module Authlogic module ActsAsAuthentic # Magic columns are like ActiveRecord's created_at and updated_at columns. # They are "magically" maintained for you. Authlogic has the same thing, but # these are maintained on the session side. Please see "Magic Columns" in # `Session::Base` for more details. This module merely adds validations for # the magic columns if they exist. module MagicColumns def self.included(klass) klass.class_eval do add_acts_as_authentic_module(Methods) end end # Methods relating to the magic columns module Methods def self.included(klass) klass.class_eval do if column_names.include?("login_count") validates_numericality_of :login_count, only_integer: true, greater_than_or_equal_to: 0, allow_nil: true end if column_names.include?("failed_login_count") validates_numericality_of :failed_login_count, only_integer: true, greater_than_or_equal_to: 0, allow_nil: true end end end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/acts_as_authentic/login.rb
lib/authlogic/acts_as_authentic/login.rb
# frozen_string_literal: true require_relative "queries/case_sensitivity" require_relative "queries/find_with_case" module Authlogic module ActsAsAuthentic # Handles everything related to the login field. module Login def self.included(klass) klass.class_eval do extend Config end end # Configuration for the login field. module Config # The name of the login field in the database. # # * <tt>Default:</tt> :login or :username, if they exist # * <tt>Accepts:</tt> Symbol def login_field(value = nil) rw_config(:login_field, value, first_column_to_exist(nil, :login, :username)) end alias login_field= login_field # This method allows you to find a record with the given login. If you # notice, with Active Record you have the UniquenessValidator class. # They give you a :case_sensitive option. I handle this in the same # manner that they handle that. If you are using the login field, set # false for the :case_sensitive option in # validates_uniqueness_of_login_field_options and the column doesn't # have a case-insensitive collation, this method will modify the query # to look something like: # # "LOWER(#{quoted_table_name}.#{login_field}) = LOWER(#{login})" # # If you don't specify this it just uses a regular case-sensitive search # (with the binary modifier if necessary): # # "BINARY #{login_field} = #{login}" # # The above also applies for using email as your login, except that you # need to set the :case_sensitive in # validates_uniqueness_of_email_field_options to false. # # @api public def find_by_smart_case_login_field(login) field = login_field || email_field sensitive = Queries::CaseSensitivity.new(self, field).sensitive? find_with_case(field, login, sensitive) end private # @api private def find_with_case(field, value, sensitive) Queries::FindWithCase.new(self, field, value, sensitive).execute end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/acts_as_authentic/email.rb
lib/authlogic/acts_as_authentic/email.rb
# frozen_string_literal: true module Authlogic module ActsAsAuthentic # Sometimes models won't have an explicit "login" or "username" field. # Instead they want to use the email field. In this case, authlogic provides # validations to make sure the email submited is actually a valid email. # Don't worry, if you do have a login or username field, Authlogic will # still validate your email field. One less thing you have to worry about. module Email def self.included(klass) klass.class_eval do extend Config end end # Configuration to modify how Authlogic handles the email field. module Config # The name of the field that stores email addresses. # # * <tt>Default:</tt> :email, if it exists # * <tt>Accepts:</tt> Symbol def email_field(value = nil) rw_config(:email_field, value, first_column_to_exist(nil, :email, :email_address)) end alias email_field= email_field end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/acts_as_authentic/single_access_token.rb
lib/authlogic/acts_as_authentic/single_access_token.rb
# frozen_string_literal: true module Authlogic module ActsAsAuthentic # This module is responsible for maintaining the single_access token. For # more information the single access token and how to use it, see "Params" # in `Session::Base`. module SingleAccessToken def self.included(klass) klass.class_eval do extend Config add_acts_as_authentic_module(Methods) end end # All configuration for the single_access token aspect of acts_as_authentic. # # These methods become class methods of ::ActiveRecord::Base. module Config # The single access token is used for authentication via URLs, such as a private # feed. That being said, if the user changes their password, that token probably # shouldn't change. If it did, the user would have to update all of their URLs. So # be default this is option is disabled, if you need it, feel free to turn it on. # # * <tt>Default:</tt> false # * <tt>Accepts:</tt> Boolean def change_single_access_token_with_password(value = nil) rw_config(:change_single_access_token_with_password, value, false) end alias change_single_access_token_with_password= change_single_access_token_with_password end # All method, for the single_access token aspect of acts_as_authentic. # # This module, as one of the `acts_as_authentic_modules`, is only included # into an ActiveRecord model if that model calls `acts_as_authentic`. module Methods def self.included(klass) return unless klass.column_names.include?("single_access_token") klass.class_eval do include InstanceMethods validates_uniqueness_of :single_access_token, case_sensitive: true, if: :will_save_change_to_single_access_token? before_validation :reset_single_access_token, if: :reset_single_access_token? if respond_to?(:after_password_set) after_password_set( :reset_single_access_token, if: :change_single_access_token_with_password? ) end end end # :nodoc: module InstanceMethods # Resets the single_access_token to a random friendly token. def reset_single_access_token self.single_access_token = Authlogic::Random.friendly_token end # same as reset_single_access_token, but then saves the record. def reset_single_access_token! reset_single_access_token save_without_session_maintenance end protected def reset_single_access_token? single_access_token.blank? end def change_single_access_token_with_password? self.class.change_single_access_token_with_password == true end end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/acts_as_authentic/base.rb
lib/authlogic/acts_as_authentic/base.rb
# frozen_string_literal: true module Authlogic module ActsAsAuthentic # Provides the base functionality for acts_as_authentic module Base def self.included(klass) klass.class_eval do class_attribute :acts_as_authentic_modules self.acts_as_authentic_modules ||= [] extend Authlogic::Config extend Config end end # The primary configuration of a model (often, `User`) for use with # authlogic. These methods become class methods of ::ActiveRecord::Base. module Config # This includes a lot of helpful methods for authenticating records # which the Authlogic::Session module relies on. To use it just do: # # class User < ApplicationRecord # acts_as_authentic # end # # Configuration is easy: # # acts_as_authentic do |c| # c.my_configuration_option = my_value # end # # See the various sub modules for the configuration they provide. def acts_as_authentic yield self if block_given? return unless db_setup? acts_as_authentic_modules.each { |mod| include mod } end # Since this part of Authlogic deals with another class, ActiveRecord, # we can't just start including things in ActiveRecord itself. A lot of # these module includes need to be triggered by the acts_as_authentic # method call. For example, you don't want to start adding in email # validations and what not into a model that has nothing to do with # Authlogic. # # That being said, this is your tool for extending Authlogic and # "hooking" into the acts_as_authentic call. def add_acts_as_authentic_module(mod, action = :append) modules = acts_as_authentic_modules.clone case action when :append modules << mod when :prepend modules = [mod] + modules end modules.uniq! self.acts_as_authentic_modules = modules end # This is the same as add_acts_as_authentic_module, except that it # removes the module from the list. def remove_acts_as_authentic_module(mod) modules = acts_as_authentic_modules.clone modules.delete(mod) self.acts_as_authentic_modules = modules end # Some Authlogic modules requires a database connection with a existing # users table by the moment when you call the `acts_as_authentic` # method. If you try to call `acts_as_authentic` without a database # connection, it will raise a `Authlogic::ModelSetupError`. # # If you rely on the User model before the database is setup correctly, # set this field to false. # * <tt>Default:</tt> false # * <tt>Accepts:</tt> Boolean def raise_on_model_setup_error(value = nil) rw_config(:raise_on_model_setup_error, value, false) end alias raise_on_model_setup_error= raise_on_model_setup_error private def db_setup? column_names true rescue StandardError raise ModelSetupError if raise_on_model_setup_error false end def first_column_to_exist(*columns_to_check) if db_setup? columns_to_check.each do |column_name| if column_names.include?(column_name.to_s) return column_name.to_sym end end end columns_to_check.first&.to_sym end end end end end ActiveSupport.on_load :active_record do ActiveRecord::Base.include Authlogic::ActsAsAuthentic::Base ActiveRecord::Base.include Authlogic::ActsAsAuthentic::Email ActiveRecord::Base.include Authlogic::ActsAsAuthentic::LoggedInStatus ActiveRecord::Base.include Authlogic::ActsAsAuthentic::Login ActiveRecord::Base.include Authlogic::ActsAsAuthentic::MagicColumns ActiveRecord::Base.include Authlogic::ActsAsAuthentic::Password ActiveRecord::Base.include Authlogic::ActsAsAuthentic::PerishableToken ActiveRecord::Base.include Authlogic::ActsAsAuthentic::PersistenceToken ActiveRecord::Base.include Authlogic::ActsAsAuthentic::SessionMaintenance ActiveRecord::Base.include Authlogic::ActsAsAuthentic::SingleAccessToken end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/acts_as_authentic/persistence_token.rb
lib/authlogic/acts_as_authentic/persistence_token.rb
# frozen_string_literal: true module Authlogic module ActsAsAuthentic # Maintains the persistence token, the token responsible for persisting sessions. This token # gets stored in the session and the cookie. module PersistenceToken def self.included(klass) klass.class_eval do add_acts_as_authentic_module(Methods) end end # Methods for the persistence token. module Methods def self.included(klass) klass.class_eval do extend ClassMethods include InstanceMethods # If the table does not have a password column, then # `after_password_set` etc. will not be defined. See # `Authlogic::ActsAsAuthentic::Password::Callbacks.included` if respond_to?(:after_password_set) && respond_to?(:after_password_verification) after_password_set :reset_persistence_token after_password_verification :reset_persistence_token!, if: :reset_persistence_token? end validates_presence_of :persistence_token validates_uniqueness_of :persistence_token, case_sensitive: true, if: :will_save_change_to_persistence_token? before_validation :reset_persistence_token, if: :reset_persistence_token? end end # :nodoc: module ClassMethods # Resets ALL persistence tokens in the database, which will require # all users to re-authenticate. def forget_all # Paginate these to save on memory find_each(batch_size: 50, &:forget!) end end # :nodoc: module InstanceMethods # Resets the persistence_token field to a random hex value. def reset_persistence_token self.persistence_token = Authlogic::Random.hex_token end # Same as reset_persistence_token, but then saves the record. def reset_persistence_token! reset_persistence_token save_without_session_maintenance(validate: false) end alias forget! reset_persistence_token! private def reset_persistence_token? persistence_token.blank? end end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/acts_as_authentic/perishable_token.rb
lib/authlogic/acts_as_authentic/perishable_token.rb
# frozen_string_literal: true module Authlogic module ActsAsAuthentic # This provides a handy token that is "perishable", meaning the token is # only good for a certain amount of time. # # This is useful for resetting password, confirming accounts, etc. Typically # during these actions you send them this token in an email. Once they use # the token and do what they need to do, that token should expire. # # Don't worry about maintaining the token, changing it, or expiring it # yourself. Authlogic does all of this for you. See the sub modules for all # of the tools Authlogic provides to you. module PerishableToken def self.included(klass) klass.class_eval do extend Config add_acts_as_authentic_module(Methods) end end # Configure the perishable token. module Config # When using the find_using_perishable_token method the token can # expire. If the token is expired, no record will be returned. Use this # option to specify how long the token is valid for. # # * <tt>Default:</tt> 10.minutes # * <tt>Accepts:</tt> Fixnum def perishable_token_valid_for(value = nil) rw_config( :perishable_token_valid_for, (!value.nil? && value.to_i) || value, 10.minutes.to_i ) end alias perishable_token_valid_for= perishable_token_valid_for # Authlogic tries to expire and change the perishable token as much as # possible, without compromising its purpose. If you want to manage it # yourself, set this to true. # # * <tt>Default:</tt> false # * <tt>Accepts:</tt> Boolean def disable_perishable_token_maintenance(value = nil) rw_config(:disable_perishable_token_maintenance, value, false) end alias disable_perishable_token_maintenance= disable_perishable_token_maintenance end # All methods relating to the perishable token. module Methods def self.included(klass) return unless klass.column_names.include?("perishable_token") klass.class_eval do extend ClassMethods include InstanceMethods validates_uniqueness_of :perishable_token, case_sensitive: true, if: :will_save_change_to_perishable_token? before_save :reset_perishable_token, unless: :disable_perishable_token_maintenance? end end # :nodoc: module ClassMethods # Use this method to find a record with a perishable token. This # method does 2 things for you: # # 1. It ignores blank tokens # 2. It enforces the perishable_token_valid_for configuration option. # # If you want to use a different timeout value, just pass it as the # second parameter: # # User.find_using_perishable_token(token, 1.hour) def find_using_perishable_token(token, age = perishable_token_valid_for) return if token.blank? age = age.to_i conditions_sql = "perishable_token = ?" conditions_subs = [token.to_s] if column_names.include?("updated_at") && age > 0 conditions_sql += " and updated_at > ?" conditions_subs << age.seconds.ago end where(conditions_sql, *conditions_subs).first end # This method will raise ActiveRecord::NotFound if no record is found. def find_using_perishable_token!(token, age = perishable_token_valid_for) find_using_perishable_token(token, age) || raise(ActiveRecord::RecordNotFound) end end # :nodoc: module InstanceMethods # Resets the perishable token to a random friendly token. def reset_perishable_token self.perishable_token = Random.friendly_token end # Same as reset_perishable_token, but then saves the record afterwards. def reset_perishable_token! reset_perishable_token save_without_session_maintenance(validate: false) end # A convenience method based on the # disable_perishable_token_maintenance configuration option. def disable_perishable_token_maintenance? self.class.disable_perishable_token_maintenance == true end end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/acts_as_authentic/logged_in_status.rb
lib/authlogic/acts_as_authentic/logged_in_status.rb
# frozen_string_literal: true module Authlogic module ActsAsAuthentic # Since web applications are stateless there is not sure fire way to tell if # a user is logged in or not, from the database perspective. The best way to # do this is to provide a "timeout" based on inactivity. So if that user is # inactive for a certain amount of time we assume they are logged out. # That's what this module is all about. module LoggedInStatus def self.included(klass) klass.class_eval do extend Config add_acts_as_authentic_module(Methods) end end # All configuration for the logged in status feature set. module Config # The timeout to determine when a user is logged in or not. # # * <tt>Default:</tt> 10.minutes # * <tt>Accepts:</tt> Fixnum def logged_in_timeout(value = nil) rw_config(:logged_in_timeout, (!value.nil? && value.to_i) || value, 10.minutes.to_i) end alias logged_in_timeout= logged_in_timeout end # All methods for the logged in status feature seat. module Methods def self.included(klass) return unless klass.column_names.include?("last_request_at") klass.class_eval do include InstanceMethods scope( :logged_in, lambda do where( "last_request_at > ? and current_login_at IS NOT NULL", logged_in_timeout.seconds.ago ) end ) scope( :logged_out, lambda do where( "last_request_at is NULL or last_request_at <= ?", logged_in_timeout.seconds.ago ) end ) end end # :nodoc: module InstanceMethods # Returns true if the last_request_at > logged_in_timeout. def logged_in? unless respond_to?(:last_request_at) raise( "Can not determine the records login state because " \ "there is no last_request_at column" ) end !last_request_at.nil? && last_request_at > logged_in_timeout.seconds.ago end # Opposite of logged_in? def logged_out? !logged_in? end private def logged_in_timeout self.class.logged_in_timeout end end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/acts_as_authentic/queries/find_with_case.rb
lib/authlogic/acts_as_authentic/queries/find_with_case.rb
# frozen_string_literal: true module Authlogic module ActsAsAuthentic module Queries # The query used by public-API method `find_by_smart_case_login_field`. # # We use the rails methods `case_insensitive_comparison` and # `case_sensitive_comparison`. These methods nicely take into account # MySQL collations. (Consider the case where a user *says* they want a # case-sensitive uniqueness validation, but then they configure their # database to have an insensitive collation. Rails will handle this for # us, by downcasing, see # `active_record/connection_adapters/abstract_mysql_adapter.rb`) So that's # great! But, these methods are not part of rails' public API, so there # are no docs. So, everything we know about how to use the methods # correctly comes from mimicing what we find in # `active_record/validations/uniqueness.rb`. # # @api private class FindWithCase # @api private def initialize(model_class, field, value, sensitive) @model_class = model_class @field = field.to_s @value = value @sensitive = sensitive end # @api private def execute @model_class.where(comparison).first end private # @api private # @return Arel::Nodes::Equality def comparison @sensitive ? sensitive_comparison : insensitive_comparison end # @api private def insensitive_comparison @model_class.connection.case_insensitive_comparison( @model_class.arel_table[@field], @value ) end # @api private def sensitive_comparison bound_value = @model_class.predicate_builder.build_bind_attribute(@field, @value) @model_class.connection.case_sensitive_comparison( @model_class.arel_table[@field], bound_value ) end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/acts_as_authentic/queries/case_sensitivity.rb
lib/authlogic/acts_as_authentic/queries/case_sensitivity.rb
# frozen_string_literal: true module Authlogic module ActsAsAuthentic module Queries # @api private class CaseSensitivity E_UNABLE_TO_DETERMINE_SENSITIVITY = <<~EOS Authlogic was unable to determine what case-sensitivity to use when searching for email/login. To specify a sensitivity, validate the uniqueness of the email/login and use the `case_sensitive` option, like this: validates :email, uniqueness: { case_sensitive: false } Authlogic will now perform a case-insensitive query. EOS # @api private def initialize(model_class, attribute) @model_class = model_class @attribute = attribute.to_sym end # @api private def sensitive? sensitive = uniqueness_validator_options[:case_sensitive] if sensitive.nil? ::Kernel.warn(E_UNABLE_TO_DETERMINE_SENSITIVITY) false else sensitive end end private # @api private def uniqueness_validator @model_class.validators.select { |v| v.is_a?(::ActiveRecord::Validations::UniquenessValidator) && v.attributes == [@attribute] }.first end # @api private def uniqueness_validator_options uniqueness_validator&.options || {} end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/test_case/mock_api_controller.rb
lib/authlogic/test_case/mock_api_controller.rb
# frozen_string_literal: true module Authlogic module TestCase # Basically acts like an API controller but doesn't do anything. # Authlogic can interact with this, do it's thing and then you can look at # the controller object to see if anything changed. class MockAPIController < ControllerAdapters::AbstractAdapter attr_writer :request_content_type def initialize end # Expected API controller has no cookies method. undef :cookies def cookie_domain nil end def logger @logger ||= MockLogger.new end def params @params ||= {} end def request @request ||= MockRequest.new(self) end def request_content_type @request_content_type ||= "text/html" end def session @session ||= {} end # If method is defined, it causes below behavior... # controller = Authlogic::ControllerAdapters::RailsAdapter.new( # Authlogic::TestCase::MockAPIController.new # ) # controller.responds_to_single_access_allowed? #=> true # controller.single_access_allowed? # #=> NoMethodError: undefined method `single_access_allowed?' for nil:NilClass # undef :single_access_allowed? end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/test_case/mock_request.rb
lib/authlogic/test_case/mock_request.rb
# frozen_string_literal: true module Authlogic module TestCase class MockRequest # :nodoc: attr_accessor :controller def initialize(controller) self.controller = controller end def env @env ||= { ControllerAdapters::AbstractAdapter::ENV_SESSION_OPTIONS => {} } end def format controller.request_content_type if controller.respond_to? :request_content_type end def ip controller&.respond_to?(:env) && controller.env.is_a?(Hash) && controller.env["REMOTE_ADDR"] || "1.1.1.1" end private def method_missing(*args, &block) end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/test_case/mock_logger.rb
lib/authlogic/test_case/mock_logger.rb
# frozen_string_literal: true module Authlogic module TestCase # Simple class to replace real loggers, so that we can raise any errors being logged. class MockLogger def error(message) raise message end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/test_case/mock_controller.rb
lib/authlogic/test_case/mock_controller.rb
# frozen_string_literal: true module Authlogic module TestCase # Basically acts like a controller but doesn't do anything. Authlogic can interact # with this, do it's thing and then you can look at the controller object to see if # anything changed. class MockController < ControllerAdapters::AbstractAdapter attr_accessor :http_user, :http_password, :realm attr_writer :request_content_type def initialize end def authenticate_with_http_basic yield http_user, http_password end def authenticate_or_request_with_http_basic(realm = "DefaultRealm") self.realm = realm @http_auth_requested = true yield http_user, http_password end def cookies @cookies ||= MockCookieJar.new end def cookie_domain nil end def logger @logger ||= MockLogger.new end def params @params ||= {} end def request @request ||= MockRequest.new(self) end def request_content_type @request_content_type ||= "text/html" end def session @session ||= {} end def http_auth_requested? @http_auth_requested ||= false end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/test_case/mock_cookie_jar.rb
lib/authlogic/test_case/mock_cookie_jar.rb
# frozen_string_literal: true module Authlogic module TestCase # A mock of `ActionDispatch::Cookies::CookieJar`. # See action_dispatch/middleware/cookies.rb class MockCookieJar < Hash # :nodoc: attr_accessor :set_cookies def [](key) hash = super hash && hash[:value] end # @param options - "the cookie's value [usually a string] or a hash of # options as documented above [in action_dispatch/middleware/cookies.rb]" def []=(key, options) opt = cookie_options_to_hash(options) (@set_cookies ||= {})[key.to_s] = opt super(key, opt) end def delete(key, _options = {}) super(key) end def signed @signed ||= MockSignedCookieJar.new(self) end def encrypted @encrypted ||= MockEncryptedCookieJar.new(self) end private # @api private def cookie_options_to_hash(options) if options.is_a?(Hash) options else { value: options } end end end # A mock of `ActionDispatch::Cookies::SignedKeyRotatingCookieJar` # # > .. a jar that'll automatically generate a signed representation of # > cookie value and verify it when reading from the cookie again. # > actionpack/lib/action_dispatch/middleware/cookies.rb class MockSignedCookieJar < MockCookieJar attr_reader :parent_jar # helper for testing def initialize(parent_jar) @parent_jar = parent_jar parent_jar.each { |k, v| self[k] = v } end def [](val) signed_message = @parent_jar[val] if signed_message payload, signature = signed_message.split("--") raise "Invalid signature" unless Digest::SHA1.hexdigest(payload) == signature payload end end def []=(key, options) opt = cookie_options_to_hash(options) opt[:value] = "#{opt[:value]}--#{Digest::SHA1.hexdigest opt[:value]}" @parent_jar[key] = opt end end # Which ActionDispatch class is this a mock of? # TODO: Document as with other mocks above. class MockEncryptedCookieJar < MockCookieJar attr_reader :parent_jar # helper for testing def initialize(parent_jar) @parent_jar = parent_jar parent_jar.each { |k, v| self[k] = v } end def [](val) encrypted_message = @parent_jar[val] if encrypted_message self.class.decrypt(encrypted_message) end end def []=(key, options) opt = cookie_options_to_hash(options) opt[:value] = self.class.encrypt(opt[:value]) @parent_jar[key] = opt end # simple caesar cipher for testing def self.encrypt(str) str.unpack("U*").map(&:succ).pack("U*") end def self.decrypt(str) str.unpack("U*").map(&:pred).pack("U*") end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/test_case/rails_request_adapter.rb
lib/authlogic/test_case/rails_request_adapter.rb
# frozen_string_literal: true module Authlogic module TestCase # Adapts authlogic to work with the @request object when testing. This way Authlogic # can set cookies and what not before a request is made, ultimately letting you log in # users in functional tests. class RailsRequestAdapter < ControllerAdapters::AbstractAdapter def authenticate_with_http_basic(&block) end def cookies new_cookies = MockCookieJar.new super.each do |key, value| new_cookies[key] = cookie_value(value) end new_cookies end def cookie_domain nil end def request @request ||= MockRequest.new(controller) end def request_content_type request.format.to_s end private def cookie_value(value) value.is_a?(Hash) ? value[:value] : value end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/controller_adapters/sinatra_adapter.rb
lib/authlogic/controller_adapters/sinatra_adapter.rb
# frozen_string_literal: true # Authlogic bridge for Sinatra module Authlogic module ControllerAdapters module SinatraAdapter # Cookie management functions class Cookies attr_reader :request, :response def initialize(request, response) @request = request @response = response end def delete(key, options = {}) @response.delete_cookie(key, options) end def []=(key, options) @response.set_cookie(key, options) end def method_missing(meth, *args, &block) @request.cookies.send(meth, *args, &block) end end # Thin wrapper around request and response. class Controller attr_reader :request, :response, :cookies def initialize(request, response) @request = request @cookies = Cookies.new(request, response) end def session env["rack.session"] end def method_missing(meth, *args, &block) @request.send meth, *args, &block end end # Sinatra controller adapter class Adapter < AbstractAdapter def cookie_domain env["SERVER_NAME"] end # Mixed into `Sinatra::Base` module Implementation def self.included(klass) klass.send :before do controller = Controller.new(request, response) Authlogic::Session::Base.controller = Adapter.new(controller) end end end end end end end Sinatra::Base.include(Authlogic::ControllerAdapters::SinatraAdapter::Adapter::Implementation)
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/controller_adapters/rack_adapter.rb
lib/authlogic/controller_adapters/rack_adapter.rb
# frozen_string_literal: true module Authlogic module ControllerAdapters # Adapter for authlogic to make it function as a Rack middleware. # First you'll have write your own Rack adapter where you have to set your cookie domain. # # class YourRackAdapter < Authlogic::ControllerAdapters::RackAdapter # def cookie_domain # 'your_cookie_domain_here.com' # end # end # # Next you need to set up a rack middleware like this: # # class AuthlogicMiddleware # def initialize(app) # @app = app # end # # def call(env) # YourRackAdapter.new(env) # @app.call(env) # end # end # # And that is all! Now just load this middleware into rack: # # use AuthlogicMiddleware # # Authlogic will expect a User and a UserSession object to be present: # # class UserSession < Authlogic::Session::Base # # Authlogic options go here # end # # class User < ApplicationRecord # acts_as_authentic # end # class RackAdapter < AbstractAdapter def initialize(env) # We use the Rack::Request object as the controller object. # For this to work, we have to add some glue. request = Rack::Request.new(env) request.instance_eval do def request self end def remote_ip ip end end super(request) Authlogic::Session::Base.controller = self end # Rack Requests stores cookies with not just the value, but also with # flags and expire information in the hash. Authlogic does not like this, # so we drop everything except the cookie value. def cookies controller .cookies .map { |key, value_hash| { key => value_hash[:value] } } .inject(:merge) || {} end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/controller_adapters/rails_adapter.rb
lib/authlogic/controller_adapters/rails_adapter.rb
# frozen_string_literal: true module Authlogic module ControllerAdapters # Adapts authlogic to work with rails. The point is to close the gap between # what authlogic expects and what the rails controller object provides. # Similar to how ActiveRecord has an adapter for MySQL, PostgreSQL, SQLite, # etc. class RailsAdapter < AbstractAdapter def authenticate_with_http_basic(&block) controller.authenticate_with_http_basic(&block) end # Returns a `ActionDispatch::Cookies::CookieJar`. See the AC guide # http://guides.rubyonrails.org/action_controller_overview.html#cookies def cookies controller.respond_to?(:cookies, true) ? controller.send(:cookies) : nil end def cookie_domain controller.request.session_options[:domain] end def request_content_type request.format.to_s end # Lets Authlogic know about the controller object via a before filter, AKA # "activates" authlogic. module RailsImplementation def self.included(klass) # :nodoc: klass.prepend_before_action :activate_authlogic end private def activate_authlogic Authlogic::Session::Base.controller = RailsAdapter.new(self) end end end end end ActiveSupport.on_load(:action_controller) do include Authlogic::ControllerAdapters::RailsAdapter::RailsImplementation end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/controller_adapters/abstract_adapter.rb
lib/authlogic/controller_adapters/abstract_adapter.rb
# frozen_string_literal: true module Authlogic module ControllerAdapters # :nodoc: # Allows you to use Authlogic in any framework you want, not just rails. See # the RailsAdapter for an example of how to adapt Authlogic to work with # your framework. class AbstractAdapter E_COOKIE_DOMAIN_ADAPTER = "The cookie_domain method has not been " \ "implemented by the controller adapter" ENV_SESSION_OPTIONS = "rack.session.options" attr_accessor :controller def initialize(controller) self.controller = controller end def authenticate_with_http_basic @auth = Rack::Auth::Basic::Request.new(controller.request.env) if @auth.provided? && @auth.basic? yield(*@auth.credentials) else false end end def cookies controller.cookies end def cookie_domain raise NotImplementedError, E_COOKIE_DOMAIN_ADAPTER end def params controller.params end def request controller.request end def request_content_type request.content_type end # Inform Rack that we would like a new session ID to be assigned. Changes # the ID, but not the contents of the session. # # The `:renew` option is read by `rack/session/abstract/id.rb`. # # This is how Devise (via warden) implements defense against Session # Fixation. Our implementation is copied directly from the warden gem # (set_user in warden/proxy.rb) def renew_session_id env = request.env options = env[ENV_SESSION_OPTIONS] if options if options.frozen? env[ENV_SESSION_OPTIONS] = options.merge(renew: true).freeze else options[:renew] = true end end end def session controller.session end def responds_to_single_access_allowed? controller.respond_to?(:single_access_allowed?, true) end def single_access_allowed? controller.send(:single_access_allowed?) end # You can disable the updating of `last_request_at` # on a per-controller basis. # # # in your controller # def last_request_update_allowed? # false # end # # For example, what if you had a javascript function that polled the # server updating how much time is left in their session before it # times out. Obviously you would want to ignore this request, because # then the user would never time out. So you can do something like # this in your controller: # # def last_request_update_allowed? # action_name != "update_session_time_left" # end # # See `authlogic/session/magic_columns.rb` to learn more about the # `last_request_at` column itself. def last_request_update_allowed? if controller.respond_to?(:last_request_update_allowed?, true) controller.send(:last_request_update_allowed?) else true end end def respond_to_missing?(*args) super(*args) || controller.respond_to?(*args) end private def method_missing(id, *args, &block) controller.send(id, *args, &block) end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/i18n/translator.rb
lib/authlogic/i18n/translator.rb
# frozen_string_literal: true module Authlogic module I18n # The default translator used by authlogic/i18n.rb class Translator # If the I18n gem is present, calls +I18n.translate+ passing all # arguments, else returns +options[:default]+. def translate(key, options = {}) if defined?(::I18n) ::I18n.translate key, **options else options[:default] end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/crypto_providers/sha512.rb
lib/authlogic/crypto_providers/sha512.rb
# frozen_string_literal: true require "digest/sha2" module Authlogic module CryptoProviders # SHA-512 does not have any practical known attacks against it. However, # there are better choices. We recommend transitioning to a more secure, # adaptive hashing algorithm, like scrypt. class Sha512 # V2 hashes the digest bytes in repeated stretches instead of hex characters. autoload :V2, File.join(__dir__, "sha512", "v2") class << self attr_accessor :join_token # The number of times to loop through the encryption. def stretches @stretches ||= 20 end attr_writer :stretches # Turns your raw password into a Sha512 hash. def encrypt(*tokens) digest = tokens.flatten.join(join_token) stretches.times { digest = Digest::SHA512.hexdigest(digest) } digest end # Does the crypted password match the tokens? Uses the same tokens that # were used to encrypt. def matches?(crypted, *tokens) encrypt(*tokens) == crypted end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/crypto_providers/scrypt.rb
lib/authlogic/crypto_providers/scrypt.rb
# frozen_string_literal: true require "scrypt" module Authlogic module CryptoProviders # SCrypt is the default provider for Authlogic. It is the only # choice in the adaptive hash family that accounts for hardware # based attacks by compensating with memory bound as well as cpu # bound computational constraints. It offers the same guarantees # as BCrypt in the way of one-way, unique and slow. # # Decided SCrypt is for you? Just install the scrypt gem: # # gem install scrypt # # Tell acts_as_authentic to use it: # # acts_as_authentic do |c| # c.crypto_provider = Authlogic::CryptoProviders::SCrypt # end class SCrypt class << self DEFAULTS = { key_len: 32, salt_size: 8, max_time: 0.2, max_mem: 1024 * 1024, max_memfrac: 0.5 }.freeze attr_writer :key_len, :salt_size, :max_time, :max_mem, :max_memfrac # Key length - length in bytes of generated key, from 16 to 512. def key_len @key_len ||= DEFAULTS[:key_len] end # Salt size - size in bytes of random salt, from 8 to 32 def salt_size @salt_size ||= DEFAULTS[:salt_size] end # Max time - maximum time spent in computation def max_time @max_time ||= DEFAULTS[:max_time] end # Max memory - maximum memory usage. The minimum is always 1MB def max_mem @max_mem ||= DEFAULTS[:max_mem] end # Max memory fraction - maximum memory out of all available. Always # greater than zero and <= 0.5. def max_memfrac @max_memfrac ||= DEFAULTS[:max_memfrac] end # Creates an SCrypt hash for the password passed. def encrypt(*tokens) ::SCrypt::Password.create( join_tokens(tokens), key_len: key_len, salt_size: salt_size, max_mem: max_mem, max_memfrac: max_memfrac, max_time: max_time ) end # Does the hash match the tokens? Uses the same tokens that were used to encrypt. def matches?(hash, *tokens) hash = new_from_hash(hash) return false if hash.blank? hash == join_tokens(tokens) end private def join_tokens(tokens) tokens.flatten.join end def new_from_hash(hash) ::SCrypt::Password.new(hash) rescue ::SCrypt::Errors::InvalidHash nil end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/crypto_providers/bcrypt.rb
lib/authlogic/crypto_providers/bcrypt.rb
# frozen_string_literal: true require "bcrypt" module Authlogic module CryptoProviders # The family of adaptive hash functions (BCrypt, SCrypt, PBKDF2) # is the best choice for password storage today. They have the # three properties of password hashing that are desirable. They # are one-way, unique, and slow. While a salted SHA or MD5 hash is # one-way and unique, preventing rainbow table attacks, they are # still lightning fast and attacks on the stored passwords are # much more effective. This benchmark demonstrates the effective # slowdown that BCrypt provides: # # require "bcrypt" # require "digest" # require "benchmark" # # Benchmark.bm(18) do |x| # x.report("BCrypt (cost = 10:") { # 100.times { BCrypt::Password.create("mypass", :cost => 10) } # } # x.report("BCrypt (cost = 4:") { # 100.times { BCrypt::Password.create("mypass", :cost => 4) } # } # x.report("Sha512:") { # 100.times { Digest::SHA512.hexdigest("mypass") } # } # x.report("Sha1:") { # 100.times { Digest::SHA1.hexdigest("mypass") } # } # end # # user system total real # BCrypt (cost = 10): 37.360000 0.020000 37.380000 ( 37.558943) # BCrypt (cost = 4): 0.680000 0.000000 0.680000 ( 0.677460) # Sha512: 0.000000 0.000000 0.000000 ( 0.000672) # Sha1: 0.000000 0.000000 0.000000 ( 0.000454) # # You can play around with the cost to get that perfect balance # between performance and security. A default cost of 10 is the # best place to start. # # Decided BCrypt is for you? Just install the bcrypt gem: # # gem install bcrypt # # Tell acts_as_authentic to use it: # # acts_as_authentic do |c| # c.crypto_provider = Authlogic::CryptoProviders::BCrypt # end # # You are good to go! class BCrypt class << self # This is the :cost option for the BCrpyt library. The higher the cost # the more secure it is and the longer is take the generate a hash. By # default this is 10. Set this to any value >= the engine's minimum # (currently 4), play around with it to get that perfect balance between # security and performance. def cost @cost ||= 10 end def cost=(val) if val < ::BCrypt::Engine::MIN_COST raise ArgumentError, "Authlogic's bcrypt cost cannot be set below the engine's " \ "min cost (#{::BCrypt::Engine::MIN_COST})" end @cost = val end # Creates a BCrypt hash for the password passed. def encrypt(*tokens) ::BCrypt::Password.create(join_tokens(tokens), cost: cost) end # Does the hash match the tokens? Uses the same tokens that were used to # encrypt. def matches?(hash, *tokens) hash = new_from_hash(hash) return false if hash.blank? hash == join_tokens(tokens) end # This method is used as a flag to tell Authlogic to "resave" the # password upon a successful login, using the new cost def cost_matches?(hash) hash = new_from_hash(hash) if hash.blank? false else hash.cost == cost end end private def join_tokens(tokens) tokens.flatten.join end def new_from_hash(hash) ::BCrypt::Password.new(hash) rescue ::BCrypt::Errors::InvalidHash nil end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/crypto_providers/md5.rb
lib/authlogic/crypto_providers/md5.rb
# frozen_string_literal: true require "digest/md5" module Authlogic module CryptoProviders # A poor choice. There are known attacks against this algorithm. class MD5 # V2 hashes the digest bytes in repeated stretches instead of hex characters. autoload :V2, File.join(__dir__, "md5", "v2") class << self attr_accessor :join_token # The number of times to loop through the encryption. def stretches @stretches ||= 1 end attr_writer :stretches # Turns your raw password into a MD5 hash. def encrypt(*tokens) digest = tokens.flatten.join(join_token) stretches.times { digest = Digest::MD5.hexdigest(digest) } digest end # Does the crypted password match the tokens? Uses the same tokens that # were used to encrypt. def matches?(crypted, *tokens) encrypt(*tokens) == crypted end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/crypto_providers/sha1.rb
lib/authlogic/crypto_providers/sha1.rb
# frozen_string_literal: true require "digest/sha1" module Authlogic module CryptoProviders # A poor choice. There are known attacks against this algorithm. class Sha1 # V2 hashes the digest bytes in repeated stretches instead of hex characters. autoload :V2, File.join(__dir__, "sha1", "v2") class << self def join_token @join_token ||= "--" end attr_writer :join_token # The number of times to loop through the encryption. def stretches @stretches ||= 10 end attr_writer :stretches # Turns your raw password into a Sha1 hash. def encrypt(*tokens) tokens = tokens.flatten digest = tokens.shift stretches.times do digest = Digest::SHA1.hexdigest([digest, *tokens].join(join_token)) end digest end # Does the crypted password match the tokens? Uses the same tokens that # were used to encrypt. def matches?(crypted, *tokens) encrypt(*tokens) == crypted end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/crypto_providers/sha256.rb
lib/authlogic/crypto_providers/sha256.rb
# frozen_string_literal: true require "digest/sha2" module Authlogic # The acts_as_authentic method has a crypto_provider option. This allows you # to use any type of encryption you like. Just create a class with a class # level encrypt and matches? method. See example below. # # === Example # # class MyAwesomeEncryptionMethod # def self.encrypt(*tokens) # # the tokens passed will be an array of objects, what type of object # # is irrelevant, just do what you need to do with them and return a # # single encrypted string. for example, you will most likely join all # # of the objects into a single string and then encrypt that string # end # # def self.matches?(crypted, *tokens) # # return true if the crypted string matches the tokens. Depending on # # your algorithm you might decrypt the string then compare it to the # # token, or you might encrypt the tokens and make sure it matches the # # crypted string, its up to you. # end # end module CryptoProviders # = Sha256 # # Uses the Sha256 hash algorithm to encrypt passwords. class Sha256 # V2 hashes the digest bytes in repeated stretches instead of hex characters. autoload :V2, File.join(__dir__, "sha256", "v2") class << self attr_accessor :join_token # The number of times to loop through the encryption. def stretches @stretches ||= 20 end attr_writer :stretches # Turns your raw password into a Sha256 hash. def encrypt(*tokens) digest = tokens.flatten.join(join_token) stretches.times { digest = Digest::SHA256.hexdigest(digest) } digest end # Does the crypted password match the tokens? Uses the same tokens that # were used to encrypt. def matches?(crypted, *tokens) encrypt(*tokens) == crypted end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/crypto_providers/sha1/v2.rb
lib/authlogic/crypto_providers/sha1/v2.rb
# frozen_string_literal: true require "digest/sha1" module Authlogic module CryptoProviders class Sha1 # A poor choice. There are known attacks against this algorithm. class V2 class << self def join_token @join_token ||= "--" end attr_writer :join_token # The number of times to loop through the encryption. def stretches @stretches ||= 10 end attr_writer :stretches # Turns your raw password into a Sha1 hash. def encrypt(*tokens) tokens = tokens.flatten digest = tokens.shift stretches.times do digest = Digest::SHA1.digest([digest, *tokens].join(join_token)) end digest.unpack1("H*") end # Does the crypted password match the tokens? Uses the same tokens that # were used to encrypt. def matches?(crypted, *tokens) encrypt(*tokens) == crypted end end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/crypto_providers/md5/v2.rb
lib/authlogic/crypto_providers/md5/v2.rb
# frozen_string_literal: true require "digest/md5" module Authlogic module CryptoProviders class MD5 # A poor choice. There are known attacks against this algorithm. class V2 class << self attr_accessor :join_token # The number of times to loop through the encryption. def stretches @stretches ||= 1 end attr_writer :stretches # Turns your raw password into a MD5 hash. def encrypt(*tokens) digest = tokens.flatten.join(join_token) stretches.times { digest = Digest::MD5.digest(digest) } digest.unpack1("H*") end # Does the crypted password match the tokens? Uses the same tokens that # were used to encrypt. def matches?(crypted, *tokens) encrypt(*tokens) == crypted end end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/crypto_providers/sha512/v2.rb
lib/authlogic/crypto_providers/sha512/v2.rb
# frozen_string_literal: true require "digest/sha2" module Authlogic module CryptoProviders class Sha512 # SHA-512 does not have any practical known attacks against it. However, # there are better choices. We recommend transitioning to a more secure, # adaptive hashing algorithm, like scrypt. class V2 class << self attr_accessor :join_token # The number of times to loop through the encryption. def stretches @stretches ||= 20 end attr_writer :stretches # Turns your raw password into a Sha512 hash. def encrypt(*tokens) digest = tokens.flatten.join(join_token) stretches.times do digest = Digest::SHA512.digest(digest) end digest.unpack1("H*") end # Does the crypted password match the tokens? Uses the same tokens that # were used to encrypt. def matches?(crypted, *tokens) encrypt(*tokens) == crypted end end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/crypto_providers/sha256/v2.rb
lib/authlogic/crypto_providers/sha256/v2.rb
# frozen_string_literal: true require "digest/sha2" module Authlogic # The acts_as_authentic method has a crypto_provider option. This allows you # to use any type of encryption you like. Just create a class with a class # level encrypt and matches? method. See example below. # # === Example # # class MyAwesomeEncryptionMethod # def self.encrypt(*tokens) # # the tokens passed will be an array of objects, what type of object # # is irrelevant, just do what you need to do with them and return a # # single encrypted string. for example, you will most likely join all # # of the objects into a single string and then encrypt that string # end # # def self.matches?(crypted, *tokens) # # return true if the crypted string matches the tokens. Depending on # # your algorithm you might decrypt the string then compare it to the # # token, or you might encrypt the tokens and make sure it matches the # # crypted string, its up to you. # end # end module CryptoProviders class Sha256 # = Sha256 # # Uses the Sha256 hash algorithm to encrypt passwords. class V2 class << self attr_accessor :join_token # The number of times to loop through the encryption. def stretches @stretches ||= 20 end attr_writer :stretches # Turns your raw password into a Sha256 hash. def encrypt(*tokens) digest = tokens.flatten.join(join_token) stretches.times { digest = Digest::SHA256.digest(digest) } digest.unpack1("H*") end # Does the crypted password match the tokens? Uses the same tokens that # were used to encrypt. def matches?(crypted, *tokens) encrypt(*tokens) == crypted end end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/session/base.rb
lib/authlogic/session/base.rb
# frozen_string_literal: true require "request_store" module Authlogic module Session module Activation # :nodoc: class NotActivatedError < ::StandardError def initialize super( "You must activate the Authlogic::Session::Base.controller with " \ "a controller object before creating objects" ) end end end module Existence # :nodoc: class SessionInvalidError < ::StandardError def initialize(session) message = I18n.t( "error_messages.session_invalid", default: "Your session is invalid and has the following errors:" ) message += " #{session.errors.full_messages.to_sentence}" super message end end end # This is the most important class in Authlogic. You will inherit this class # for your own eg. `UserSession`. # # Ongoing consolidation of modules # ================================ # # We are consolidating modules into this class (inlining mixins). When we # are done, there will only be this one file. It will be quite large, but it # will be easier to trace execution. # # Once consolidation is complete, we hope to identify and extract # collaborating objects. For example, there may be a "session adapter" that # connects this class with the existing `ControllerAdapters`. Perhaps a # data object or a state machine will reveal itself. # # Activation # ========== # # Activating Authlogic requires that you pass it an # Authlogic::ControllerAdapters::AbstractAdapter object, or a class that # extends it. This is sort of like a database connection for an ORM library, # Authlogic can't do anything until it is "connected" to a controller. If # you are using a supported framework, Authlogic takes care of this for you. # # ActiveRecord Trickery # ===================== # # Authlogic looks like ActiveRecord, sounds like ActiveRecord, but its not # ActiveRecord. That's the goal here. This is useful for the various rails # helper methods such as form_for, error_messages_for, or any method that # expects an ActiveRecord object. The point is to disguise the object as an # ActiveRecord object so we can take advantage of the many ActiveRecord # tools. # # Brute Force Protection # ====================== # # A brute force attacks is executed by hammering a login with as many password # combinations as possible, until one works. A brute force attacked is generally # combated with a slow hashing algorithm such as BCrypt. You can increase the cost, # which makes the hash generation slower, and ultimately increases the time it takes # to execute a brute force attack. Just to put this into perspective, if a hacker was # to gain access to your server and execute a brute force attack locally, meaning # there is no network lag, it would probably take decades to complete. Now throw in # network lag and it would take MUCH longer. # # But for those that are extra paranoid and can't get enough protection, why not stop # them as soon as you realize something isn't right? That's what this module is all # about. By default the consecutive_failed_logins_limit configuration option is set to # 50, if someone consecutively fails to login after 50 attempts their account will be # suspended. This is a very liberal number and at this point it should be obvious that # something is not right. If you wish to lower this number just set the configuration # to a lower number: # # class UserSession < Authlogic::Session::Base # consecutive_failed_logins_limit 10 # end # # Callbacks # ========= # # Between these callbacks and the configuration, this is the contract between me and # you to safely modify Authlogic's behavior. I will do everything I can to make sure # these do not change. # # Check out the sub modules of Authlogic::Session. They are very concise, clear, and # to the point. More importantly they use the same API that you would use to extend # Authlogic. That being said, they are great examples of how to extend Authlogic and # add / modify behavior to Authlogic. These modules could easily be pulled out into # their own plugin and become an "add on" without any change. # # Now to the point of this module. Just like in ActiveRecord you have before_save, # before_validation, etc. You have similar callbacks with Authlogic, see the METHODS # constant below. The order of execution is as follows: # # before_persisting # persist # after_persisting # [save record if record.has_changes_to_save?] # # before_validation # before_validation_on_create # before_validation_on_update # validate # after_validation_on_update # after_validation_on_create # after_validation # [save record if record.has_changes_to_save?] # # before_save # before_create # before_update # after_update # after_create # after_save # [save record if record.has_changes_to_save?] # # before_destroy # [save record if record.has_changes_to_save?] # after_destroy # # Notice the "save record if has_changes_to_save" lines above. This helps with performance. If # you need to make changes to the associated record, there is no need to save the # record, Authlogic will do it for you. This allows multiple modules to modify the # record and execute as few queries as possible. # # **WARNING**: unlike ActiveRecord, these callbacks must be set up on the class level: # # class UserSession < Authlogic::Session::Base # before_validation :my_method # validate :another_method # # ..etc # end # # You can NOT define a "before_validation" method, this is bad practice and does not # allow Authlogic to extend properly with multiple extensions. Please ONLY use the # method above. # # HTTP Basic Authentication # ========================= # # Handles all authentication that deals with basic HTTP auth. Which is # authentication built into the HTTP protocol: # # http://username:password@whatever.com # # Also, if you are not comfortable letting users pass their raw username and # password you can use a single access token, as described below. # # Magic Columns # ============= # # Just like ActiveRecord has "magic" columns, such as: created_at and updated_at. # Authlogic has its own "magic" columns too: # # * login_count - Increased every time an explicit login is made. This will *NOT* # increase if logging in by a session, cookie, or basic http auth # * failed_login_count - This increases for each consecutive failed login. See # the consecutive_failed_logins_limit option for details. # * last_request_at - Updates every time the user logs in, either by explicitly # logging in, or logging in by cookie, session, or http auth # * current_login_at - Updates with the current time when an explicit login is made. # * last_login_at - Updates with the value of current_login_at before it is reset. # * current_login_ip - Updates with the request ip when an explicit login is made. # * last_login_ip - Updates with the value of current_login_ip before it is reset. # # Multiple Simultaneous Sessions # ============================== # # See `id`. Allows you to separate sessions with an id, ultimately letting # you create multiple sessions for the same user. # # Timeout # ======= # # Think about financial websites, if you are inactive for a certain period # of time you will be asked to log back in on your next request. You can do # this with Authlogic easily, there are 2 parts to this: # # 1. Define the timeout threshold: # # acts_as_authentic do |c| # c.logged_in_timeout = 10.minutes # default is 10.minutes # end # # 2. Enable logging out on timeouts # # class UserSession < Authlogic::Session::Base # logout_on_timeout true # default is false # end # # This will require a user to log back in if they are inactive for more than # 10 minutes. In order for this feature to be used you must have a # last_request_at datetime column in your table for whatever model you are # authenticating with. # # Params # ====== # # This module is responsible for authenticating the user via params, which ultimately # allows the user to log in using a URL like the following: # # https://www.domain.com?user_credentials=4LiXF7FiGUppIPubBPey # # Notice the token in the URL, this is a single access token. A single access token is # used for single access only, it is not persisted. Meaning the user provides it, # Authlogic grants them access, and that's it. If they want access again they need to # provide the token again. Authlogic will *NEVER* try to persist the session after # authenticating through this method. # # For added security, this token is *ONLY* allowed for RSS and ATOM requests. You can # change this with the configuration. You can also define if it is allowed dynamically # by defining a single_access_allowed? method in your controller. For example: # # class UsersController < ApplicationController # private # def single_access_allowed? # action_name == "index" # end # # Also, by default, this token is permanent. Meaning if the user changes their # password, this token will remain the same. It will only change when it is explicitly # reset. # # You can modify all of this behavior with the Config sub module. # # Perishable Token # ================ # # Maintains the perishable token, which is helpful for confirming records or # authorizing records to reset their password. All that this module does is # reset it after a session have been saved, just keep it changing. The more # it changes, the tighter the security. # # See Authlogic::ActsAsAuthentic::PerishableToken for more information. # # Scopes # ====== # # Authentication can be scoped, and it's easy, you just need to define how you want to # scope everything. See `.with_scope`. # # Unauthorized Record # =================== # # Allows you to create session with an object. Ex: # # UserSession.create(my_user_object) # # Be careful with this, because Authlogic is assuming that you have already # confirmed that the user is who he says he is. # # For example, this is the method used to persist the session internally. # Authlogic finds the user with the persistence token. At this point we know # the user is who he says he is, so Authlogic just creates a session with # the record. This is particularly useful for 3rd party authentication # methods, such as OpenID. Let that method verify the identity, once it's # verified, pass the object and create a session. # # Magic States # ============ # # Authlogic tries to check the state of the record before creating the session. If # your record responds to the following methods and any of them return false, # validation will fail: # # Method name Description # active? Is the record marked as active? # approved? Has the record been approved? # confirmed? Has the record been confirmed? # # Authlogic does nothing to define these methods for you, its up to you to define what # they mean. If your object responds to these methods Authlogic will use them, # otherwise they are ignored. # # What's neat about this is that these are checked upon any type of login. When # logging in explicitly, by cookie, session, or basic http auth. So if you mark a user # inactive in the middle of their session they wont be logged back in next time they # refresh the page. Giving you complete control. # # Need Authlogic to check your own "state"? No problem, check out the hooks section # below. Add in a before_validation to do your own checking. The sky is the limit. # # Validation # ========== # # The errors in Authlogic work just like ActiveRecord. In fact, it uses # the `ActiveModel::Errors` class. Use it the same way: # # ``` # class UserSession # validate :check_if_awesome # # private # # def check_if_awesome # if login && !login.include?("awesome") # errors.add(:login, "must contain awesome") # end # unless attempted_record.awesome? # errors.add(:base, "You must be awesome to log in") # end # end # end # ``` class Base extend ActiveModel::Naming extend ActiveModel::Translation extend Authlogic::Config include ActiveSupport::Callbacks E_AC_PARAMETERS = <<~EOS Passing an ActionController::Parameters to Authlogic is not allowed. In Authlogic 3, especially during the transition of rails to Strong Parameters, it was common for Authlogic users to forget to `permit` their params. They would pass their params into Authlogic, we'd call `to_h`, and they'd be surprised when authentication failed. In 2018, people are still making this mistake. We'd like to help them and make authlogic a little simpler at the same time, so in Authlogic 3.7.0, we deprecated the use of ActionController::Parameters. Instead, pass a plain Hash. Please replace: UserSession.new(user_session_params) UserSession.create(user_session_params) with UserSession.new(user_session_params.to_h) UserSession.create(user_session_params.to_h) And don't forget to `permit`! We discussed this issue thoroughly between late 2016 and early 2018. Notable discussions include: - https://github.com/binarylogic/authlogic/issues/512 - https://github.com/binarylogic/authlogic/pull/558 - https://github.com/binarylogic/authlogic/pull/577 EOS E_DPR_FIND_BY_LOGIN_METHOD = <<~EOS.squish.freeze find_by_login_method is deprecated in favor of record_selection_method, to avoid confusion with ActiveRecord's "Dynamic Finders". (https://guides.rubyonrails.org/v6.0/active_record_querying.html#dynamic-finders) For example, rubocop-rails is confused by the deprecated method. (https://github.com/rubocop-hq/rubocop-rails/blob/master/lib/rubocop/cop/rails/dynamic_find_by.rb) EOS VALID_SAME_SITE_VALUES = [nil, "Lax", "Strict", "None"].freeze # Callbacks # ========= METHODS = %w[ before_persisting persist after_persisting before_validation before_validation_on_create before_validation_on_update validate after_validation_on_update after_validation_on_create after_validation before_save before_create before_update after_update after_create after_save before_destroy after_destroy ].freeze # Defines the "callback installation methods" used below. METHODS.each do |method| class_eval <<-EOS, __FILE__, __LINE__ + 1 def self.#{method}(*filter_list, &block) set_callback(:#{method}, *filter_list, &block) end EOS end # Defines session life cycle events that support callbacks. define_callbacks( *METHODS, terminator: ->(_target, result_lambda) { result_lambda.call == false } ) define_callbacks( "persist", terminator: ->(_target, result_lambda) { result_lambda.call == true } ) # Use the "callback installation methods" defined above # ----------------------------------------------------- before_persisting :reset_stale_state # `persist` callbacks, in order of priority persist :persist_by_params persist :persist_by_cookie persist :persist_by_session persist :persist_by_http_auth, if: :persist_by_http_auth? after_persisting :enforce_timeout after_persisting :update_session, unless: :single_access? after_persisting :set_last_request_at before_save :update_info before_save :set_last_request_at after_save :reset_perishable_token! after_save :save_cookie, if: :cookie_enabled? after_save :update_session after_create :renew_session_id after_destroy :destroy_cookie, if: :cookie_enabled? after_destroy :update_session # `validate` callbacks, in deliberate order. For example, # validate_magic_states must run *after* a record is found. validate :validate_by_password, if: :authenticating_with_password? validate( :validate_by_unauthorized_record, if: :authenticating_with_unauthorized_record? ) validate :validate_magic_states, unless: :disable_magic_states? validate :reset_failed_login_count, if: :reset_failed_login_count? validate :validate_failed_logins, if: :being_brute_force_protected? validate :increase_failed_login_count # Accessors # ========= class << self attr_accessor( :configured_password_methods ) end attr_accessor( :invalid_password, :new_session, :priority_record, :record, :single_access, :stale_record, :unauthorized_record ) attr_writer( :scope, :id ) # Public class methods # ==================== class << self # Returns true if a controller has been set and can be used properly. # This MUST be set before anything can be done. Similar to how # ActiveRecord won't allow you to do anything without establishing a DB # connection. In your framework environment this is done for you, but if # you are using Authlogic outside of your framework, you need to assign # a controller object to Authlogic via # Authlogic::Session::Base.controller = obj. See the controller= method # for more information. def activated? !controller.nil? end # Allow users to log in via HTTP basic authentication. # # * <tt>Default:</tt> false # * <tt>Accepts:</tt> Boolean def allow_http_basic_auth(value = nil) rw_config(:allow_http_basic_auth, value, false) end alias allow_http_basic_auth= allow_http_basic_auth # Lets you change which model to use for authentication. # # * <tt>Default:</tt> inferred from the class name. UserSession would # automatically try User # * <tt>Accepts:</tt> an ActiveRecord class def authenticate_with(klass) @klass_name = klass.name @klass = klass end alias authenticate_with= authenticate_with # The current controller object def controller RequestStore.store[:authlogic_controller] end # This accepts a controller object wrapped with the Authlogic controller # adapter. The controller adapters close the gap between the different # controllers in each framework. That being said, Authlogic is expecting # your object's class to extend # Authlogic::ControllerAdapters::AbstractAdapter. See # Authlogic::ControllerAdapters for more info. # # Lastly, this is thread safe. def controller=(value) RequestStore.store[:authlogic_controller] = value end # To help protect from brute force attacks you can set a limit on the # allowed number of consecutive failed logins. By default this is 50, # this is a very liberal number, and if someone fails to login after 50 # tries it should be pretty obvious that it's a machine trying to login # in and very likely a brute force attack. # # In order to enable this field your model MUST have a # failed_login_count (integer) field. # # If you don't know what a brute force attack is, it's when a machine # tries to login into a system using every combination of character # possible. Thus resulting in possibly millions of attempts to log into # an account. # # * <tt>Default:</tt> 50 # * <tt>Accepts:</tt> Integer, set to 0 to disable def consecutive_failed_logins_limit(value = nil) rw_config(:consecutive_failed_logins_limit, value, 50) end alias consecutive_failed_logins_limit= consecutive_failed_logins_limit # The name of the cookie or the key in the cookies hash. Be sure and use # a unique name. If you have multiple sessions and they use the same # cookie it will cause problems. Also, if a id is set it will be # inserted into the beginning of the string. Example: # # session = UserSession.new # session.cookie_key => "user_credentials" # # session = UserSession.new(:super_high_secret) # session.cookie_key => "super_high_secret_user_credentials" # # * <tt>Default:</tt> "#{klass_name.underscore}_credentials" # * <tt>Accepts:</tt> String def cookie_key(value = nil) rw_config(:cookie_key, value, "#{klass_name.underscore}_credentials") end alias cookie_key= cookie_key # A convenience method. The same as: # # session = UserSession.new(*args) # session.save # # Instead you can do: # # UserSession.create(*args) def create(*args, &block) session = new(*args) session.save(&block) session end # Same as create but calls create!, which raises an exception when # validation fails. def create!(*args) session = new(*args) session.save! session end # Set this to true if you want to disable the checking of active?, approved?, and # confirmed? on your record. This is more or less of a convenience feature, since # 99% of the time if those methods exist and return false you will not want the # user logging in. You could easily accomplish this same thing with a # before_validation method or other callbacks. # # * <tt>Default:</tt> false # * <tt>Accepts:</tt> Boolean def disable_magic_states(value = nil) rw_config(:disable_magic_states, value, false) end alias disable_magic_states= disable_magic_states # Once the failed logins limit has been exceed, how long do you want to # ban the user? This can be a temporary or permanent ban. # # * <tt>Default:</tt> 2.hours # * <tt>Accepts:</tt> Fixnum, set to 0 for permanent ban def failed_login_ban_for(value = nil) rw_config(:failed_login_ban_for, (!value.nil? && value) || value, 2.hours.to_i) end alias failed_login_ban_for= failed_login_ban_for # This is how you persist a session. This finds the record for the # current session using a variety of methods. It basically tries to "log # in" the user without the user having to explicitly log in. Check out # the other Authlogic::Session modules for more information. # # The best way to use this method is something like: # # helper_method :current_user_session, :current_user # # def current_user_session # return @current_user_session if defined?(@current_user_session) # @current_user_session = UserSession.find # end # # def current_user # return @current_user if defined?(@current_user) # @current_user = current_user_session && current_user_session.user # end # # Also, this method accepts a single parameter as the id, to find # session that you marked with an id: # # UserSession.find(:secure) # # See the id method for more information on ids. # # Priority Record # =============== # # This internal feature supports ActiveRecord's optimistic locking feature, # which is automatically enabled when a table has a `lock_version` column. # # ``` # # https://api.rubyonrails.org/classes/ActiveRecord/Locking/Optimistic.html # p1 = Person.find(1) # p2 = Person.find(1) # p1.first_name = "Michael" # p1.save # p2.first_name = "should fail" # p2.save # Raises an ActiveRecord::StaleObjectError # ``` # # Now, consider the following Authlogic scenario: # # ``` # User.log_in_after_password_change = true # ben = User.find(1) # UserSession.create(ben) # ben.password = "newpasswd" # ben.password_confirmation = "newpasswd" # ben.save # ``` # # We've used one of Authlogic's session maintenance features, # `log_in_after_password_change`. So, when we call `ben.save`, there is a # `before_save` callback that logs Ben in (`UserSession.find`). Well, when # we log Ben in, we update his user record, eg. `login_count`. When we're # done logging Ben in, then the normal `ben.save` happens. So, there were # two `update` queries. If those two updates came from different User # instances, we would get a `StaleObjectError`. # # Our solution is to carefully pass around a single `User` instance, using # it for all `update` queries, thus avoiding the `StaleObjectError`. def find(id = nil, priority_record = nil) session = new({ priority_record: priority_record }, id) session.priority_record = priority_record if session.persisting? session end end # @deprecated in favor of record_selection_method def find_by_login_method(value = nil) ::ActiveSupport::Deprecation.new.warn(E_DPR_FIND_BY_LOGIN_METHOD) record_selection_method(value) end alias find_by_login_method= find_by_login_method # The text used to identify credentials (username/password) combination # when a bad login attempt occurs. When you show error messages for a # bad login, it's considered good security practice to hide which field # the user has entered incorrectly (the login field or the password # field). For a full explanation, see # http://www.gnucitizen.org/blog/username-enumeration-vulnerabilities/ # # Example of use: # # class UserSession < Authlogic::Session::Base # generalize_credentials_error_messages true # end # # This would make the error message for bad logins and bad passwords # look identical: # # Login/Password combination is not valid # # Alternatively you may use a custom message: # # class UserSession < AuthLogic::Session::Base # generalize_credentials_error_messages "Your login information is invalid" # end # # This will instead show your custom error message when the UserSession is invalid. # # The downside to enabling this is that is can be too vague for a user # that has a hard time remembering their username and password # combinations. It also disables the ability to to highlight the field # with the error when you use form_for. # # If you are developing an app where security is an extreme priority # (such as a financial application), then you should enable this. # Otherwise, leaving this off is fine. # # * <tt>Default</tt> false # * <tt>Accepts:</tt> Boolean def generalize_credentials_error_messages(value = nil) rw_config(:generalize_credentials_error_messages, value, false) end alias generalize_credentials_error_messages= generalize_credentials_error_messages # HTTP authentication realm # # Sets the HTTP authentication realm. # # Note: This option has no effect unless request_http_basic_auth is true # # * <tt>Default:</tt> 'Application' # * <tt>Accepts:</tt> String def http_basic_auth_realm(value = nil) rw_config(:http_basic_auth_realm, value, "Application") end alias http_basic_auth_realm= http_basic_auth_realm # Should the cookie be set as httponly? If true, the cookie will not be # accessible from javascript # # * <tt>Default:</tt> true # * <tt>Accepts:</tt> Boolean def httponly(value = nil) rw_config(:httponly, value, true) end alias httponly= httponly # How to name the class, works JUST LIKE ActiveRecord, except it uses # the following namespace: # # authlogic.models.user_session def human_name(*) I18n.t("models.#{name.underscore}", count: 1, default: name.humanize) end def i18n_scope I18n.scope end # The name of the class that this session is authenticating with. For # example, the UserSession class will authenticate with the User class # unless you specify otherwise in your configuration. See # authenticate_with for information on how to change this value. # # @api public def klass @klass ||= klass_name ? klass_name.constantize : nil end # The model name, guessed from the session class name, e.g. "User", # from "UserSession". # # TODO: This method can return nil. We should explore this. It seems # likely to cause a NoMethodError later, so perhaps we should raise an # error instead. # # @api private def klass_name return @klass_name if instance_variable_defined?(:@klass_name) @klass_name = name.scan(/(.*)Session/)[0]&.first end # The name of the method you want Authlogic to create for storing the # login / username. Keep in mind this is just for your # Authlogic::Session, if you want it can be something completely # different than the field in your model. So if you wanted people to # login with a field called "login" and then find users by email this is # completely doable. See the `record_selection_method` configuration # option for details. # # * <tt>Default:</tt> klass.login_field || klass.email_field # * <tt>Accepts:</tt> Symbol or String def login_field(value = nil) rw_config(:login_field, value, klass.login_field || klass.email_field) end alias login_field= login_field # With acts_as_authentic you get a :logged_in_timeout configuration # option. If this is set, after this amount of time has passed the user # will be marked as logged out. Obviously, since web based apps are on a # per request basis, we have to define a time limit threshold that # determines when we consider a user to be "logged out". Meaning, if # they login and then leave the website, when do mark them as logged # out? I recommend just using this as a fun feature on your website or # reports, giving you a ballpark number of users logged in and active. # This is not meant to be a dead accurate representation of a user's # logged in state, since there is really no real way to do this with web # based apps. Think about a user that logs in and doesn't log out. There # is no action that tells you that the user isn't technically still
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
true
binarylogic/authlogic
https://github.com/binarylogic/authlogic/blob/77da613d09fe8e2be2c980d5a5d3c76109590edd/lib/authlogic/session/magic_column/assigns_last_request_at.rb
lib/authlogic/session/magic_column/assigns_last_request_at.rb
# frozen_string_literal: true module Authlogic module Session module MagicColumn # Assigns the current time to the `last_request_at` attribute. # # 1. The `last_request_at` column must exist # 2. Assignment can be disabled on a per-controller basis # 3. Assignment will not happen more often than `last_request_at_threshold` # seconds. # # - current_time - a `Time` # - record - eg. a `User` # - controller - an `Authlogic::ControllerAdapters::AbstractAdapter` # - last_request_at_threshold - integer - seconds # # @api private class AssignsLastRequestAt def initialize(current_time, record, controller, last_request_at_threshold) @current_time = current_time @record = record @controller = controller @last_request_at_threshold = last_request_at_threshold end def assign return unless assign? @record.last_request_at = @current_time end private # @api private def assign? @record && @record.class.column_names.include?("last_request_at") && @controller.last_request_update_allowed? && ( @record.last_request_at.blank? || @last_request_at_threshold.to_i.seconds.ago >= @record.last_request_at ) end end end end end
ruby
MIT
77da613d09fe8e2be2c980d5a5d3c76109590edd
2026-01-04T15:46:27.836259Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/spec_helper.rb
spec/spec_helper.rb
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib")) $LOAD_PATH.unshift(File.dirname(__FILE__)) require "rspec" require "neat" require "aruba/api" require "css_parser" Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } RSpec.configure do |config| config.include SassSupport config.include CssParser config.include ParserSupport config.include Aruba::Api config.before(:all) do generate_css end config.after(:all) do clean_up end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/support/parser_support.rb
spec/support/parser_support.rb
module ParserSupport def self.parser @parser ||= CssParser::Parser.new end def self.parse_file(identifier) parser.load_file!("tmp/#{identifier}.css") end def self.show_contents(identifier) css_file_contents = File.open("tmp/#{identifier}.css").read css_file_contents.each_line do |line| puts line end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/support/sass_support.rb
spec/support/sass_support.rb
module SassSupport def generate_css _mkdir("tmp") `sass -I . --update spec/fixtures:tmp --quiet --precision 5` end def clean_up FileUtils.rm_rf("tmp") end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/support/matchers/be_contained_in.rb
spec/support/matchers/be_contained_in.rb
RSpec::Matchers.define :be_contained_in do |expected| match do |actual| @query = ParserSupport.parser.find_by_selector(actual, expected) @query.any? end failure_message do |actual| %{expected selector #{actual} to be contained in #{expected}} end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/support/matchers/have_rule.rb
spec/support/matchers/have_rule.rb
RSpec::Matchers.define :have_rule do |expected| match do |selector| @rules = rules_from_selector(selector) @rules.include? expected end failure_message do |selector| if @rules.empty? %{no CSS for selector #{selector} were found} else rules = @rules.join("; ") %{Expected selector #{selector} to have CSS rule "#{expected}". Had "#{rules}".} end end def rules_from_selector(selector) rulesets = ParserSupport.parser.find_by_selector(selector) if rulesets.empty? [] else rules(rulesets) end end def rules(rulesets) rules = [] rulesets.map do |ruleset| ruleset.split(";").each do |rule| rules << rule.strip end end rules end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/support/matchers/have_value.rb
spec/support/matchers/have_value.rb
RSpec::Matchers.define :have_value do |expected| match do |variable| selector_class = variable.sub("$", ".") @value_attribute = ParserSupport.parser.find_by_selector(selector_class)[0] unless @value_attribute.nil? actual_value = @value_attribute.split(":")[1].strip.sub(";", "") actual_value == expected end end failure_message do |variable_name| value_attribute = @value_attribute.to_s %{Expected variable #{variable_name} to have value "#{expected}". Had "#{value_attribute}".} end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/support/matchers/have_ruleset.rb
spec/support/matchers/have_ruleset.rb
RSpec::Matchers.define :have_ruleset do |expected| match do |selector| @ruleset = rules_from_selector(selector) @ruleset.join("; ") == expected end failure_message do |selector| if @ruleset.empty? %{no CSS for selector #{selector} were found} else ruleset = @ruleset.join("; ") %{Expected selector #{selector} to have CSS rule "#{expected}". Had "#{ruleset}".} end end def rules_from_selector(selector) ParserSupport.parser.find_by_selector(selector) end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/neat/functions/neat_opposite_direction_spec.rb
spec/neat/functions/neat_opposite_direction_spec.rb
require "spec_helper" describe "neat-opposite-direction" do before(:all) do ParserSupport.parse_file("functions/neat-opposite-direction") end context "called with ltr" do it "returns right" do rule = "content: right" expect(".neat-opposite-direction-ltr").to have_rule(rule) end end context "called with rtl" do it "returns left" do rule = "content: left" expect(".neat-opposite-direction-rtl").to have_rule(rule) end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/neat/functions/neat_column_width_spec.rb
spec/neat/functions/neat_column_width_spec.rb
require "spec_helper" describe "neat-column-width" do before(:all) do ParserSupport.parse_file("functions/neat-column-width") end context "called with a default twelve column grid" do it "applies one column" do rule = "width: calc(8.33333% - 21.66667px)" expect(".neat-column-width-1-of-12").to have_rule(rule) end it "applies six columns" do rule = "width: calc(50% - 30px)" expect(".neat-column-width-6-of-12").to have_rule(rule) end it "applies twelve columns" do rule = "width: calc(100% - 40px)" expect(".neat-column-width-12-of-12").to have_rule(rule) end end context "called with a custom 6 column grid" do it "applies one column" do rule = "width: calc(16.66667% - 11.66667px)" expect(".neat-column-width-1-of-6").to have_rule(rule) end it "applies six columns" do rule = "width: calc(33.33333% - 13.33333px)" expect(".neat-column-width-2-of-6").to have_rule(rule) end it "applies twelve columns" do rule = "width: calc(100% - 20px)" expect(".neat-column-width-6-of-6").to have_rule(rule) end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/neat/functions/retrieve_neat_settings_spec.rb
spec/neat/functions/retrieve_neat_settings_spec.rb
require "spec_helper" describe "retrieve-neat-settings" do before(:all) do ParserSupport.parse_file("functions/retrieve-neat-settings") end context "called with default settings" do it "gets default columns" do rule = "content: 12" expect(".neat-settings-default-columns").to have_rule(rule) end it "gets default gutter" do rule = "content: 20px" expect(".neat-settings-default-gutter").to have_rule(rule) end end context "called with custom settings" do it "gets default columns" do rule = "content: 18" expect(".neat-settings-eighteen-columns").to have_rule(rule) end it "gets default gutter" do rule = "content: 33px" expect(".neat-settings-eighteen-gutter").to have_rule(rule) end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/neat/functions/neat_float_direction_spec.rb
spec/neat/functions/neat_float_direction_spec.rb
require "spec_helper" describe "neat-float-direction" do before(:all) do ParserSupport.parse_file("functions/neat-float-direction") end context "called with ltr" do it "returns left" do rule = "content: left" expect(".neat-float-direction-ltr").to have_rule(rule) end end context "called with rtl" do it "returns right" do rule = "content: right" expect(".neat-float-direction-rtl").to have_rule(rule) end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/neat/functions/neat_parse_media_spec.rb
spec/neat/functions/neat_parse_media_spec.rb
require "spec_helper" describe "neat-parse-media" do before(:all) do ParserSupport.parse_file("functions/neat-parse-media") end context "called with number" do it "gets min-width wraped number" do rule = 'content: "only screen and (min-width: 100px)"' expect(".neat-parse-media-number").to have_rule(rule) end end context "called with string" do it "gets the string" do rule = 'content: "only screen and (max-width: 25rem)"' expect(".neat-parse-media-string").to have_rule(rule) end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/neat/functions/neat_column_default_spec.rb
spec/neat/functions/neat_column_default_spec.rb
require "spec_helper" describe "neat-column-default" do before(:all) do ParserSupport.parse_file("functions/neat-column-default") end context "called with default grid" do it "gets default columns" do rule = "content: 12" expect(".neat-column-default-grid").to have_rule(rule) end it "gets custom columns" do rule = "content: 10" expect(".neat-column-default-grid-custom-col").to have_rule(rule) end end context "called with custom grid" do it "gets default columns" do rule = "content: 18" expect(".neat-column-custom-grid").to have_rule(rule) end it "gets custom columns" do rule = "content: 10" expect(".neat-column-custom-grid-custom-col").to have_rule(rule) end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/neat/mixins/grid_media_spec.rb
spec/neat/mixins/grid_media_spec.rb
require "spec_helper" describe "@include grid-media() {...}" do before(:all) do ParserSupport.parse_file("mixins/grid-media") end context "with argument ($custom-neat-grid)" do it "outputs @media only screen and (min-width: 1000px)" do expect(".grid-column-media-custom-neat-grid").to be_contained_in("only screen and (min-width: 1000px)") end end context "with argument ($specific-neat-grid)" do it "outputs @media only screen and (min-width: 1000px) and (max-width: 1100px)" do expect(".grid-column-media-specific-neat-grid").to be_contained_in("only screen and (min-width: 1000px) and (max-width: 1100px)") end end context "with argument ($print-neat-grid)" do it "outputs @media print" do expect(".grid-column-media-print-neat-grid").to be_contained_in("print") end end context "with argument ($custom-neat-grid, $specific-neat-grid, $print-neat-grid)" do it "outputs @media only screen and (min-width: 1000px)" do expect(".grid-column-media-combined-grid").to be_contained_in("only screen and (min-width: 1000px)") end it "outputs @media only screen and (min-width: 1000px) and (max-width: 1100px)" do expect(".grid-column-media-combined-grid").to be_contained_in("only screen and (min-width: 1000px) and (max-width: 1100px)") end it "outputs @media print" do expect(".grid-column-media-combined-grid").to be_contained_in("print") end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/neat/mixins/grid_column_spec.rb
spec/neat/mixins/grid_column_spec.rb
require "spec_helper" describe "grid-column" do before(:all) do ParserSupport.parse_file("mixins/grid-column") end context "called without a specified grid" do it "applies one column in the default 12-column grid" do ruleset = "width: calc(8.33333% - 21.66667px); " + "float: left; " + "margin-left: 20px;" expect(".grid-column-1-of-default").to have_ruleset(ruleset) end it "applies six columns in the default 12-column grid" do ruleset = "width: calc(50% - 30px); " + "float: left; " + "margin-left: 20px;" expect(".grid-column-6-of-default").to have_ruleset(ruleset) end it "applies twelve columns in the default 12-column grid" do ruleset = "width: calc(100% - 40px); " + "float: left; " + "margin-left: 20px;" expect(".grid-column-12-of-default").to have_ruleset(ruleset) end it "applies a three fifths column in shorthand with the default grid" do ruleset = "width: calc(60% - 32px); " + "float: left; " + "margin-left: 20px;" expect(".grid-column-3-of-5-shorthand").to have_ruleset(ruleset) end end context "called with a custom grid" do it "applies one column" do ruleset = "width: calc(16.66667% - 1.16667em); " + "float: left; " + "margin-left: 1em;" expect(".grid-column-1-of-6").to have_ruleset(ruleset) end it "applies four columns" do ruleset = "width: calc(66.66667% - 1.66667em); " + "float: left; " + "margin-left: 1em;" expect(".grid-column-4-of-6").to have_ruleset(ruleset) end it "applies six columns" do ruleset = "width: calc(100% - 2em); " + "float: left; " + "margin-left: 1em;" expect(".grid-column-6-of-6").to have_ruleset(ruleset) end it "applies a three fifths column in shorthand" do ruleset = "width: calc(60% - 1.6em); " + "float: left; " + "margin-left: 1em;" expect(".grid-column-3-of-5-shorthand-six-grid").to have_ruleset(ruleset) end end context "called with a weirder custom grid" do it "applies five columns" do ruleset = "width: calc(5.88235% - 10.58824px); " + "float: left; " + "margin-left: 10px;" expect(".grid-column-5-of-17").to have_ruleset(ruleset) end it "applies eleven columns" do ruleset = "width: calc(35.29412% - 13.52941px); " + "float: left; " + "margin-left: 10px;" expect(".grid-column-11-of-17").to have_ruleset(ruleset) end it "applies thirteen columns" do ruleset = "width: calc(70.58824% - 17.05882px); " + "float: left; " + "margin-left: 10px;" expect(".grid-column-13-of-17").to have_ruleset(ruleset) end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/neat/mixins/grid_collapse_spec.rb
spec/neat/mixins/grid_collapse_spec.rb
require "spec_helper" describe "grid-collapse" do before(:all) do ParserSupport.parse_file("mixins/grid-collapse") end context "called with default settings" do it "adds margin for just the gutter with no specified column" do ruleset = "margin-left: -20px; " + "margin-right: -20px; " + "width: calc(100% + 40px);" expect(".grid-collapse-default").to have_ruleset(ruleset) end end context "called with custom settings" do it "adds margin for just the gutter with no specified column" do ruleset = "margin-left: -4rem; " + "margin-right: -4rem; " + "width: calc(100% + 8rem);" expect(".grid-collapse-custom").to have_ruleset(ruleset) end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/neat/mixins/grid_container_spec.rb
spec/neat/mixins/grid_container_spec.rb
require "spec_helper" describe "grid-container" do before(:all) do ParserSupport.parse_file("mixins/grid-container") end context "called with default settings" do it "adds after element" do ruleset = "clear: both; " + "content: \"\"; " + "display: block;" expect(".grid-container::after").to have_ruleset(ruleset) end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/neat/mixins/grid_shift_spec.rb
spec/neat/mixins/grid_shift_spec.rb
require "spec_helper" describe "grid-shift" do before(:all) do ParserSupport.parse_file("mixins/grid-shift") end context "called with default settings" do it "adds relative positioning without moving the object" do rule = "left: auto; position: relative;" expect(".grid-shift-default").to have_ruleset(rule) end it "moves the object one column to the right" do rule = "left: calc(8.33333% - 21.66667px + 20px); position: relative;" expect(".grid-shift-1-default").to have_ruleset(rule) end it "moves the object six columns to the right" do rule = "left: calc(50% - 30px + 20px); position: relative;" expect(".grid-shift-6-default").to have_ruleset(rule) end it "moves the object six columns to the left" do rule = "left: calc(-50% - 10px + 20px); position: relative;" expect(".grid-shift-neg-6-default").to have_ruleset(rule) end end context "called with custom settings" do it "adds relative positioning without moving the object" do rule = "left: auto; position: relative;" expect(".grid-shift-0-six").to have_ruleset(rule) end it "moves the object one column to the right" do rule = "left: calc(16.66667% - 2.33333rem + 2rem); position: relative;" expect(".grid-shift-1-six").to have_ruleset(rule) end it "moves the object three columns to the right" do rule = "left: calc(50% - 3rem + 2rem); position: relative;" expect(".grid-shift-3-six").to have_ruleset(rule) end it "moves the object three columns to the left" do rule = "left: calc(-50% - 1rem + 2rem); position: relative;" expect(".grid-shift-neg-3-six").to have_ruleset(rule) end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/spec/neat/mixins/grid_push_spec.rb
spec/neat/mixins/grid_push_spec.rb
require "spec_helper" describe "grid-push" do before(:all) do ParserSupport.parse_file("mixins/grid-push") end context "called with default settings" do it "adds margin for just the gutter with no specified column" do rule = "margin-left: 20px" expect(".grid-push-default").to have_rule(rule) end it "adds margin for one column" do rule = "margin-left: calc(8.33333% - 21.66667px + 40px)" expect(".grid-push-1-default").to have_rule(rule) end it "adds margin for six columns" do rule = "margin-left: calc(50% - 30px + 40px)" expect(".grid-push-6-default").to have_rule(rule) end it "adds margin for negative six columns" do rule = "margin-left: calc(-50% - 10px + 40px)" expect(".grid-push-neg-6-default").to have_rule(rule) end end context "called with custom settings" do it "adds margin for just the gutter with no specified column" do rule = "margin-left: 2rem" expect(".grid-push-0-six").to have_rule(rule) end it "adds margin for one column" do rule = "margin-left: calc(16.66667% - 2.33333rem + 4rem)" expect(".grid-push-1-six").to have_rule(rule) end it "adds margin for three columns" do rule = "margin-left: calc(50% - 3rem + 4rem)" expect(".grid-push-3-six").to have_rule(rule) end it "adds margin for negative three columns" do rule = "margin-left: calc(-50% - 1rem + 4rem)" expect(".grid-push-neg-3-six").to have_rule(rule) end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/lib/neat.rb
lib/neat.rb
require "neat/generator" module Neat if defined?(Rails) && defined?(Rails::Engine) class Engine < ::Rails::Engine config.assets.paths << File.expand_path("../core", __dir__) end else begin require "sass" Sass.load_paths << File.expand_path("../core", __dir__) rescue LoadError end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/lib/neat/version.rb
lib/neat/version.rb
module Neat VERSION = "4.0.0" end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
thoughtbot/neat
https://github.com/thoughtbot/neat/blob/6c76100ab31585aa1b96354d3992258ce1fc01e3/lib/neat/generator.rb
lib/neat/generator.rb
require "neat/version" require "fileutils" require "thor" module Neat class Generator < Thor map ["-v", "--version"] => :version desc "install", "Install Neat into your project" method_options path: :string, force: :boolean def install if neat_files_already_exist? && !options[:force] puts "Neat files already installed, doing nothing." else install_files puts "Neat files installed to #{install_path}/" end end desc "update", "Update Neat" method_options path: :string def update if neat_files_already_exist? remove_neat_directory install_files puts "Neat files updated." else puts "No existing neat installation. Doing nothing." end end desc "remove", "Remove Neat" method_options path: :string def remove if neat_files_already_exist? remove_neat_directory puts "Neat was successfully removed." else puts "No existing neat installation. Doing nothing." end end desc "version", "Show Neat version" def version say "Neat #{Neat::VERSION}" end private def neat_files_already_exist? install_path.exist? end def install_path @install_path ||= if options[:path] Pathname.new(File.join(options[:path], "neat")) else Pathname.new("neat") end end def remove_neat_directory FileUtils.rm_rf(install_path) end def install_files make_install_directory copy_in_scss_files end def make_install_directory FileUtils.mkdir_p(install_path) end def copy_in_scss_files FileUtils.cp_r(all_stylesheets, install_path) end def all_stylesheets Dir["#{stylesheets_directory}/*"] end def stylesheets_directory File.join(top_level_directory, "core") end def top_level_directory File.dirname(File.dirname(File.dirname(__FILE__))) end end end
ruby
MIT
6c76100ab31585aa1b96354d3992258ce1fc01e3
2026-01-04T15:46:23.561905Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/add_foreign_key_test.rb
test/add_foreign_key_test.rb
require_relative "test_helper" class AddForeignKeyTest < Minitest::Test def test_basic if postgresql? assert_unsafe AddForeignKey else assert_safe AddForeignKey end end def test_safe assert_safe AddForeignKeySafe end def test_validate_same_transaction skip unless postgresql? assert_unsafe AddForeignKeyValidateSameTransaction end def test_validate_no_transaction skip unless postgresql? assert_safe AddForeignKeyValidateNoTransaction end def test_extra_arguments if postgresql? assert_unsafe AddForeignKeyExtraArguments else assert_argument_error AddForeignKeyExtraArguments end end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/remove_column_test.rb
test/remove_column_test.rb
require_relative "test_helper" class RemoveColumnTest < Minitest::Test def test_remove_column assert_unsafe RemoveColumn end def test_remove_columns assert_unsafe RemoveColumns end def test_remove_columns_type assert_unsafe RemoveColumnsType, 'self.ignored_columns += ["name", "other"]' end def test_remove_timestamps assert_unsafe RemoveTimestamps end def test_remove_reference assert_unsafe RemoveReference end def test_remove_reference_polymorphic assert_unsafe RemoveReferencePolymorphic end def test_remove_belongs_to assert_unsafe RemoveBelongsTo end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/start_after_test.rb
test/start_after_test.rb
require_relative "test_helper" class StartAfterTest < Minitest::Test def test_version_safe with_start_after(20170101000001) do assert_safe Version end end def test_version_unsafe with_start_after(20170101000000) do assert_unsafe Version end end def test_revert_version_safe migrate AddReferenceNoIndex with_start_after(20170101000001) do assert_safe RevertAddReference, version: 20170101000001 end ensure migrate AddReferenceNoIndex, direction: :down end def test_revert_version_unsafe with_start_after(20170101000000) do assert_unsafe RevertAddReference, version: 20170101000001 end end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/remove_index_test.rb
test/remove_index_test.rb
require_relative "test_helper" class RemoveIndexTest < Minitest::Test def test_concurrently skip unless postgresql? migrate AddIndexConcurrently begin StrongMigrations.enable_check(:remove_index) assert_unsafe RemoveIndex, "remove_index :users, :name, algorithm: :concurrently" assert_unsafe RemoveIndexExtraArguments, "remove_index :users, :name, algorithm: :concurrently" assert_unsafe RemoveIndexColumn assert_unsafe RemoveIndexName migrate RemoveIndexConcurrently ensure StrongMigrations.disable_check(:remove_index) end end def test_extra_arguments assert_argument_error RemoveIndexExtraArguments end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/change_column_null_test.rb
test/change_column_null_test.rb
require_relative "test_helper" class ChangeColumnNullTest < Minitest::Test def test_basic if postgresql? assert_unsafe ChangeColumnNull else assert_safe ChangeColumnNull end end def test_constraint skip unless postgresql? assert_safe ChangeColumnNullConstraint end def test_constraint_unvalidated skip unless postgresql? assert_unsafe ChangeColumnNullConstraintUnvalidated end def test_constraint_default skip unless postgresql? assert_unsafe ChangeColumnNullConstraintDefault end def test_default assert_unsafe ChangeColumnNullDefault end def test_constraint_methods skip unless postgresql? assert_safe ChangeColumnNullConstraintMethods end def test_quoted skip unless postgresql? assert_safe ChangeColumnNullQuoted end def test_mysql_non_strict_mode skip unless mysql? || mariadb? without_strict_mode do assert_unsafe ChangeColumnNull end end def without_strict_mode with_option(:target_sql_mode, "") do yield end end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/add_exclusion_constraint_test.rb
test/add_exclusion_constraint_test.rb
require_relative "test_helper" class AddExclusionConstraintTest < Minitest::Test def setup skip unless postgresql? super end def test_basic assert_unsafe AddExclusionConstraint end def test_new_table assert_safe AddExclusionConstraintNewTable end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/add_unique_constraint_test.rb
test/add_unique_constraint_test.rb
require_relative "test_helper" class AddUniqueConstraintTest < Minitest::Test def setup skip unless postgresql? super end def test_basic assert_unsafe AddUniqueConstraint end def test_using_index assert_safe AddUniqueConstraintUsingIndex end def test_new_table assert_safe AddUniqueConstraintNewTable end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/add_column_test.rb
test/add_column_test.rb
require_relative "test_helper" class AddColumnTest < Minitest::Test def test_default assert_safe AddColumnDefault end def test_default_null skip unless postgresql? assert_safe AddColumnDefaultNull end def test_default_not_null skip unless postgresql? assert_unsafe AddColumnDefaultNotNull, "Then add the NOT NULL constraint" end def test_default_safe assert_safe AddColumnDefaultSafe end def test_default_callable # TODO check MySQL and MariaDB skip unless postgresql? assert_unsafe AddColumnDefaultCallable end def test_default_uuid skip unless postgresql? assert_unsafe AddColumnDefaultUUID end def test_default_uuid_safe skip unless postgresql? assert_safe AddColumnDefaultUUIDSafe end def test_json skip unless postgresql? assert_unsafe AddColumnJson end def test_generated_stored assert_unsafe AddColumnGeneratedStored end def test_generated_virtual skip if postgresql? assert_safe AddColumnGeneratedVirtual end def test_primary_key if mysql? || mariadb? assert_unsafe AddColumnPrimaryKey, "statement-based replication" else assert_unsafe AddColumnPrimaryKey end end def test_serial skip unless postgresql? assert_unsafe AddColumnSerial end def test_bigserial skip unless postgresql? assert_unsafe AddColumnBigserial end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/safe_by_default_test.rb
test/safe_by_default_test.rb
require_relative "test_helper" class SafeByDefaultTest < Minitest::Test def setup StrongMigrations.safe_by_default = true super end def teardown StrongMigrations.safe_by_default = false end def test_add_index assert_safe AddIndexes end def test_add_index_invalid skip unless postgresql? with_locked_table("users") do with_lock_timeout(0.1) do assert_raises(ActiveRecord::LockWaitTimeout) do migrate AddIndexes end end end error = assert_raises(ActiveRecord::StatementInvalid) do migrate AddIndexes end assert_kind_of PG::DuplicateTable, error.cause with_option(:remove_invalid_indexes, true) do # fail if same name but different options error = assert_raises(ActiveRecord::StatementInvalid) do migrate AddIndexUnique end assert_kind_of PG::DuplicateTable, error.cause migrate AddIndexes # fail if trying to add the same index in a future migration error = assert_raises(ActiveRecord::StatementInvalid) do migrate AddIndexes end assert_kind_of PG::DuplicateTable, error.cause end migrate AddIndexes, direction: :down end def test_add_index_auto_analyze with_auto_analyze do assert_analyzed AddIndexes end end def test_add_index_extra_arguments assert_argument_error AddIndexExtraArguments end def test_add_index_corruption # TODO fix skip # unless postgresql? outside_developer_env do with_target_version(14.3) do assert_unsafe AddIndex, "can cause silent data corruption in Postgres 14.0 to 14.3" end end end def test_remove_index migrate AddIndex assert_safe RemoveIndex assert_safe RemoveIndexColumn ensure migrate AddIndex, direction: :down end def test_remove_index_name migrate AddIndexName migrate RemoveIndexName end def test_remove_index_options migrate RemoveIndexOptions end def test_remove_index_extra_arguments assert_argument_error RemoveIndexExtraArguments end def test_add_reference assert_safe AddReference end def test_add_reference_foreign_key assert_safe AddReferenceForeignKey end def test_add_reference_foreign_key_validate_false assert_safe AddReferenceForeignKeyValidateFalseIndex end def test_add_reference_foreign_key_to_table assert_safe AddReferenceForeignKeyToTable end def test_add_reference_foreign_key_on_delete assert_safe AddReferenceForeignKeyOnDelete end def test_add_reference_auto_analyze with_auto_analyze do assert_analyzed AddReference end end def test_add_reference_extra_arguments assert_argument_error AddReferenceExtraArguments end def test_add_foreign_key assert_safe AddForeignKey end def test_add_foreign_key_extra_arguments assert_argument_error AddForeignKeyExtraArguments end def test_add_foreign_key_name migrate AddForeignKeyName foreign_keys = ActiveRecord::Schema.foreign_keys(:users) assert_equal 2, foreign_keys.size if postgresql? assert foreign_keys.all? { |fk| fk.options[:validate] } end migrate AddForeignKeyName, direction: :down assert_equal 0, ActiveRecord::Schema.foreign_keys(:users).size end def test_add_foreign_key_column migrate AddForeignKeyColumn foreign_keys = ActiveRecord::Schema.foreign_keys(:users) assert_equal 2, foreign_keys.size if postgresql? assert foreign_keys.all? { |fk| fk.options[:validate] } end migrate AddForeignKeyColumn, direction: :down assert_equal 0, ActiveRecord::Schema.foreign_keys(:users).size end def test_add_foreign_key_invalid skip unless postgresql? user = User.create!(order_id: 1) error = assert_raises(ActiveRecord::StatementInvalid) do migrate AddForeignKey end assert_kind_of PG::ForeignKeyViolation, error.cause user.update!(order_id: nil) migrate AddForeignKey # fail if trying to add the same foreign key in a future migration assert_raises(ActiveRecord::StatementInvalid) do migrate AddForeignKey end migrate AddForeignKey, direction: :down ensure User.delete_all end def test_add_check_constraint skip unless postgresql? assert_safe AddCheckConstraint end def test_add_check_constraint_extra_arguments skip unless postgresql? assert_argument_error AddCheckConstraintExtraArguments end def test_add_check_constraint_invalid skip unless postgresql? user = User.create!(credit_score: -1) error = assert_raises(ActiveRecord::StatementInvalid) do migrate AddCheckConstraint end assert_kind_of PG::CheckViolation, error.cause user.update!(credit_score: 1) migrate AddCheckConstraint # fail if trying to add the same constraint in a future migration assert_raises(ActiveRecord::StatementInvalid) do migrate AddCheckConstraint end migrate AddCheckConstraint, direction: :down ensure User.delete_all end def test_change_column_null skip unless postgresql? assert_safe ChangeColumnNull end def test_change_column_null_default skip unless postgresql? User.create!(name: "Existing") User.insert_all!(10000.times.map { {city: "Test"} }) assert_safe ChangeColumnNullDefault assert_equal "Existing", User.first.name assert_equal "Andy", User.last.name ensure User.delete_all end def test_change_column_null_default_callable skip unless postgresql? User.create! assert_safe ChangeColumnNullDefaultCallable refute_nil User.last.deleted_at ensure User.delete_all end def test_change_column_null_default_uuid skip unless postgresql? User.create! assert_safe ChangeColumnNullDefaultUUID ensure User.delete_all end def test_change_column_null_default_version_safe skip unless postgresql? with_start_after(20170101000001) do assert_safe ChangeColumnNullDefault end end def test_change_column_null_invalid skip unless postgresql? user = User.create! error = assert_raises(ActiveRecord::StatementInvalid) do migrate ChangeColumnNull end assert_kind_of PG::CheckViolation, error.cause user.update!(name: "Test") assert_safe ChangeColumnNull ensure User.delete_all end def test_change_column_null_long_name skip unless postgresql? assert_safe ChangeColumnNullLongName end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/check_down_test.rb
test/check_down_test.rb
require_relative "test_helper" class CheckDownTest < Minitest::Test def test_basic migrate CheckDown with_check_down do assert_unsafe CheckDown, direction: :down end assert_safe CheckDown, direction: :down end def test_safe migrate CheckDownSafe with_check_down do assert_safe CheckDownSafe, direction: :down end end def test_change skip unless postgresql? migrate CheckDownChange with_check_down do assert_unsafe CheckDownChange, direction: :down end assert_safe CheckDownChange, direction: :down end def test_change_safe skip unless postgresql? migrate CheckDownChangeSafe with_check_down do assert_safe CheckDownChangeSafe, direction: :down end end def test_safety_assured migrate CheckDownSafetyAssured with_check_down do assert_unsafe CheckDownSafetyAssured, direction: :down end assert_safe CheckDownSafetyAssured, direction: :down end def test_add_column migrate AddColumnDefault with_check_down do assert_unsafe AddColumnDefault, direction: :down end assert_safe AddColumnDefault, direction: :down end def test_add_index skip unless postgresql? migrate AddIndexConcurrently with_check_down do assert_safe AddIndexConcurrently, direction: :down end end def with_check_down StrongMigrations.check_down = true yield ensure StrongMigrations.check_down = false end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/test_helper.rb
test/test_helper.rb
require "bundler/setup" Bundler.require(:default) require "minitest/autorun" require_relative "support/active_record" require_relative "support/helpers" class Minitest::Test include Helpers def migrate(migration, direction: :up, version: 123) schema_migration.delete_all_versions migration = migration.new unless migration.is_a?(TestMigration) migration.version ||= version if direction == :down schema_migration.create_version(migration.version) end args = [schema_migration, connection_class.internal_metadata] ActiveRecord::Migrator.new(direction, [migration], *args).migrate true rescue => e raise e.cause || e end def assert_unsafe(migration, message = nil, **options) error = assert_raises(StrongMigrations::UnsafeMigration) do migrate(migration, **options) end puts error.message if ENV["VERBOSE"] assert_match message, error.message if message end def assert_safe(migration, direction: nil, **options) if direction assert migrate(migration, direction: direction, **options) else assert migrate(migration, direction: :up, **options) assert migrate(migration, direction: :down, **options) end end def assert_argument_error(migration) assert_raises(ArgumentError) do migrate(migration) end end def with_option(name, value) previous_value = StrongMigrations.send(name) begin StrongMigrations.send("#{name}=", value) yield ensure StrongMigrations.send("#{name}=", previous_value) end end def with_start_after(start_after, &block) with_option(:start_after, start_after, &block) end def with_target_version(version, &block) with_option(:target_version, version, &block) end def with_auto_analyze(&block) with_option(:auto_analyze, true, &block) end def with_safety_assured(&block) StrongMigrations::Checker.stub(:safe, true, &block) end def outside_developer_env(&block) StrongMigrations.stub(:developer_env?, false, &block) end def with_lock_timeout(lock_timeout, &block) with_option(:lock_timeout, lock_timeout, &block) ensure ActiveRecord::Base.connection.execute("RESET lock_timeout") end def with_locked_table(table) pool = ActiveRecord::Base.connection_pool connection = pool.checkout if postgresql? connection.transaction do connection.execute("LOCK TABLE #{connection.quote_table_name(table)} IN ROW EXCLUSIVE MODE") yield end else begin connection.execute("LOCK TABLE #{connection.quote_table_name(table)} WRITE") yield ensure connection.execute("UNLOCK TABLES") end end ensure pool.checkin(connection) if connection end def assert_analyzed(migration) assert analyzed?(migration) end def refute_analyzed(migration) refute analyzed?(migration) end def analyzed?(migration) statements = capture_statements do migrate migration, direction: :up end migrate migration, direction: :down statements.any? { |s| s.start_with?("ANALYZE") } end def capture_statements statements = [] callback = lambda do |_, _, _, _, payload| statements << payload[:sql] if payload[:name] != "SCHEMA" end ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do yield end statements end end StrongMigrations.add_check do |method, args| if method == :add_column && args[1].to_s == "forbidden" stop! "Cannot add forbidden column" end end Dir.glob("migrations/*.rb", base: __dir__).sort.each do |file| require_relative file end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/timeouts_test.rb
test/timeouts_test.rb
require_relative "test_helper" class TimeoutsTest < Minitest::Test def teardown reset_timeouts end def test_timeouts skip unless postgresql? || mysql? || mariadb? StrongMigrations.statement_timeout = 1.hour StrongMigrations.transaction_timeout = 2.hours StrongMigrations.lock_timeout = 10.seconds migrate CheckTimeouts if postgresql? assert_equal "1h", $statement_timeout assert_equal "2h", $transaction_timeout if transaction_timeout? assert_equal "10s", $lock_timeout else assert_equal 3600, $statement_timeout assert_equal 10, $lock_timeout end end def test_statement_timeout_float skip unless postgresql? || mysql? || mariadb? StrongMigrations.statement_timeout = 0.5.seconds migrate CheckTimeouts if postgresql? assert_equal "500ms", $statement_timeout else assert_equal 0.5, $statement_timeout end end # designed for 0 case to prevent no timeout # but can't test without statement timeout error def test_statement_timeout_float_ceil skip unless postgresql? || mysql? StrongMigrations.statement_timeout = 1.000001.seconds migrate CheckTimeouts if postgresql? assert_equal "1001ms", $statement_timeout else assert_equal 1.001, $statement_timeout end end def test_transaction_timeout_float skip unless transaction_timeout? StrongMigrations.transaction_timeout = 0.5.seconds migrate CheckTimeouts assert_equal "500ms", $transaction_timeout end # designed for 0 case to prevent no timeout # but can't test without transaction timeout error def test_transaction_timeout_float_ceil skip unless transaction_timeout? StrongMigrations.transaction_timeout = 1.000001.seconds migrate CheckTimeouts assert_equal "1001ms", $transaction_timeout end def test_transaction_timeout_is_set_before_statements skip unless transaction_timeout? StrongMigrations.transaction_timeout = 1.seconds migrate CheckTransactionTimeoutWithoutStatement assert_equal "1s", $transaction_timeout end def test_lock_timeout_float skip unless postgresql? StrongMigrations.lock_timeout = 0.5.seconds migrate CheckTimeouts assert_equal "500ms", $lock_timeout end def test_timeouts_string skip unless postgresql? StrongMigrations.statement_timeout = "1h" StrongMigrations.transaction_timeout = "2h" StrongMigrations.lock_timeout = "1d" migrate CheckTimeouts assert_equal "1h", $statement_timeout assert_equal "2h", $transaction_timeout if transaction_timeout? assert_equal "1d", $lock_timeout end def test_lock_timeout_limit StrongMigrations.lock_timeout_limit = 10.seconds StrongMigrations.lock_timeout = 20.seconds assert_output(nil, /Lock timeout is longer than 10 seconds/) do migrate CheckLockTimeout end ensure StrongMigrations.lock_timeout_limit = nil end def test_lock_timeout_limit_postgresql skip unless postgresql? StrongMigrations.lock_timeout_limit = 10.seconds # no warning ActiveRecord::Base.connection.execute("SET lock_timeout = '100ms'") _, stderr = capture_io do migrate CheckLockTimeout end refute_match(/Lock timeout is longer than 10 seconds/, stderr) # warning ["1min", "1h", "1d"].each do |timeout| ActiveRecord::Base.connection.execute("SET lock_timeout = '#{timeout}'") assert_output(nil, /Lock timeout is longer than 10 seconds/) do migrate CheckLockTimeout end end ensure StrongMigrations.lock_timeout_limit = nil end def test_lock_timeout_retries assert_retries CheckLockTimeoutRetries # MySQL and MariaDB do not support DDL transactions assert_equal (postgresql? ? 3 : 1), $migrate_attempts end def test_lock_timeout_retries_no_retries with_lock_timeout_retries(lock: false) do assert_safe CheckLockTimeoutRetries # up and down assert_equal 2, $migrate_attempts end end def test_lock_timeout_retries_transaction refute_retries CheckLockTimeoutRetriesTransaction # does not retry assert_equal 1, $migrate_attempts assert_equal 1, $transaction_attempts end def test_lock_timeout_retries_transaction_ddl_transaction skip "Requires DDL transaction" unless postgresql? assert_retries CheckLockTimeoutRetriesTransactionDdlTransaction # retries entire migration, not transaction block alone assert_equal 3, $migrate_attempts assert_equal 3, $transaction_attempts end def test_lock_timeout_retries_no_ddl_transaction assert_retries CheckLockTimeoutRetriesNoDdlTransaction # retries only single statement, not migration assert_equal 1, $migrate_attempts end def test_lock_timeout_retries_commit_db_transaction skip "Requires DDL transaction" unless postgresql? refute_retries CheckLockTimeoutRetriesCommitDbTransaction # does not retry since outside DDL transaction assert_equal 1, $migrate_attempts end def test_lock_timeout_retries_add_index skip unless postgresql? error = assert_raises(ActiveRecord::StatementInvalid) do with_lock_timeout_retries do migrate AddIndexConcurrently end end assert_kind_of PG::DuplicateTable, error.cause migrate AddIndexConcurrently, direction: :down end def test_lock_timeout_retries_add_index_remove_invalid_indexes skip unless postgresql? with_option(:remove_invalid_indexes, true) do assert_retries AddIndexConcurrently end migrate AddIndexConcurrently, direction: :down end def reset_timeouts StrongMigrations.lock_timeout = nil StrongMigrations.transaction_timeout = nil StrongMigrations.statement_timeout = nil if postgresql? ActiveRecord::Base.connection.execute("RESET lock_timeout") ActiveRecord::Base.connection.execute("RESET transaction_timeout") if transaction_timeout? ActiveRecord::Base.connection.execute("RESET statement_timeout") elsif mysql? ActiveRecord::Base.connection.execute("SET max_execution_time = DEFAULT") ActiveRecord::Base.connection.execute("SET lock_wait_timeout = DEFAULT") elsif mariadb? ActiveRecord::Base.connection.execute("SET max_statement_time = DEFAULT") ActiveRecord::Base.connection.execute("SET lock_wait_timeout = DEFAULT") end end def with_lock_timeout_retries(lock: true) StrongMigrations.lock_timeout = postgresql? ? 0.1 : 1 StrongMigrations.lock_timeout_retries = 2 StrongMigrations.lock_timeout_retry_delay = 0 $migrate_attempts = 0 $transaction_attempts = 0 if lock with_locked_table("users") do yield end else yield end ensure StrongMigrations.lock_timeout_retries = 0 StrongMigrations.lock_timeout_retry_delay = 5 end def assert_retries(migration, retries: 2, **options) retry_count = 0 original_say = nil count = proc do |message, *args, **options| original_say.call(message, *args, **options) retry_count += 1 if message.include?("Lock timeout") end assert_raises(ActiveRecord::LockWaitTimeout) do with_lock_timeout_retries(**options) do migration = migration.new original_say = migration.method(:say) migration.stub(:say, count) do migrate migration end end end assert_equal retries, retry_count end def refute_retries(migration, **options) assert_retries(migration, retries: 0, **options) end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/alphabetize_schema_test.rb
test/alphabetize_schema_test.rb
require_relative "test_helper" class AlphabetizeSchemaTest < Minitest::Test def test_default schema = dump_schema if ActiveRecord::VERSION::STRING.to_f >= 8.1 expected_columns = <<-EOS t.string "name" t.bigint "order_id" EOS else expected_columns = <<-EOS t.string "name" t.string "city" EOS end assert_match expected_columns, schema end def test_enabled schema = with_option(:alphabetize_schema, true) do dump_schema end expected_columns = <<-EOS t.string "name" t.bigint "order_id" EOS assert_match expected_columns, schema end def test_virtual_column skip unless mysql? || mariadb? migrate AddColumnGeneratedVirtual schema = with_option(:alphabetize_schema, true) do dump_schema end migrate AddColumnGeneratedVirtual, direction: :down assert_match "t.virtual", schema end private def dump_schema require "stringio" io = StringIO.new ActiveRecord::SchemaDumper.dump(connection_class, io) io.string end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/multiple_databases_test.rb
test/multiple_databases_test.rb
require_relative "test_helper" class MultipleDatabasesTest < Minitest::Test def test_target_version skip unless postgresql? with_target_version({primary: 12, animals: 16}) do with_database(:primary) do # TODO use new check # assert_unsafe AddColumnDefault end with_database(:animals) do assert_safe AddColumnDefault end end end def test_target_version_unconfigured error = assert_raises(StrongMigrations::Error) do with_target_version({primary: 12}) do with_database(:animals) do assert_safe AddColumnDefault end end end assert_equal "StrongMigrations.target_version is not configured for :animals database", error.message end def test_skip_database with_skip_database(:animals) do with_database(:primary) do assert_unsafe CreateTableForce end with_database(:animals) do assert_safe CreateTableForce, direction: :up end end # confirm migration ran assert ActiveRecord::Base.connection.table_exists?("admins") migrate CreateTableForce, direction: :down end private def with_database(database, &block) previous_configurations = ActiveRecord::Base.configurations previous_db_config = ActiveRecord::Base.connection_db_config.configuration_hash ActiveRecord::Base.configurations = { "test" => { "primary" => previous_db_config, "animals" => previous_db_config } } ActiveRecord::Base.establish_connection(database) yield ensure ActiveRecord::Base.configurations = previous_configurations if previous_configurations ActiveRecord::Base.establish_connection(previous_db_config) if previous_db_config end def with_skip_database(database) StrongMigrations.skip_database(database) yield ensure StrongMigrations.skipped_databases.clear end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/add_index_test.rb
test/add_index_test.rb
require_relative "test_helper" class AddIndexTest < Minitest::Test def test_non_concurrently if postgresql? assert_unsafe AddIndex, <<~EOF Adding an index non-concurrently blocks writes. Instead, use: class AddIndex < ActiveRecord::Migration[#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}] disable_ddl_transaction! def change add_index :users, :name, algorithm: :concurrently end end EOF else assert_safe AddIndex end end def test_up if postgresql? assert_unsafe AddIndexUp else assert_safe AddIndexUp end end def test_safety_assured assert_safe AddIndexSafetyAssured end def test_new_table assert_safe AddIndexNewTable end def test_schema assert_safe AddIndexSchema end def test_versioned_schema # use define like db/schema.rb ActiveRecord::Schema[migration_version].define do add_index :users, :name, name: "boom2" remove_index :users, name: "boom2" end end def test_concurrently skip unless postgresql? assert_safe AddIndexConcurrently end def test_columns assert_unsafe AddIndexColumns, "more than three columns" end def test_columns_unique skip unless postgresql? assert_safe AddIndexColumnsUnique end def test_auto_analyze with_auto_analyze do assert_analyzed AddIndexSafetyAssured end end def test_auto_analyze_false refute_analyzed AddIndexSafetyAssured end def test_extra_arguments if postgresql? assert_unsafe AddIndexExtraArguments else assert_argument_error AddIndexExtraArguments end end def test_concurrently_extra_arguments assert_argument_error AddIndexConcurrentlyExtraArguments end def test_corruption # TODO fix skip # unless postgresql? outside_developer_env do with_target_version(14.3) do assert_unsafe AddIndexConcurrently, "can cause silent data corruption in Postgres 14.0 to 14.3" end end end def test_remove_invalid_indexes skip unless postgresql? with_locked_table("users") do with_lock_timeout(0.1) do assert_raises(ActiveRecord::LockWaitTimeout) do migrate AddIndexConcurrently end end end assert_raises(ActiveRecord::StatementInvalid) do migrate AddIndexConcurrently end with_option(:remove_invalid_indexes, true) do migrate AddIndexConcurrently # fail if trying to add the same index in a future migration error = assert_raises(ActiveRecord::StatementInvalid) do migrate AddIndexConcurrently end assert_kind_of PG::DuplicateTable, error.cause end migrate AddIndexConcurrently, direction: :down end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false
ankane/strong_migrations
https://github.com/ankane/strong_migrations/blob/de0104c819ddd0a3d973db8e03e8971ac72a7b15/test/add_check_constraint_test.rb
test/add_check_constraint_test.rb
require_relative "test_helper" class AddCheckConstraintTest < Minitest::Test def test_basic assert_unsafe AddCheckConstraint end def test_safe if postgresql? assert_safe AddCheckConstraintSafe else assert_unsafe AddCheckConstraintSafe end end def test_validate_same_transaction assert_unsafe AddCheckConstraintValidateSameTransaction end def test_validate_no_transaction if postgresql? assert_safe AddCheckConstraintValidateNoTransaction else assert_unsafe AddCheckConstraintValidateNoTransaction end end def test_new_table assert_safe AddCheckConstraintNewTable end def test_name assert_unsafe AddCheckConstraintName end def test_extra_arguments assert_unsafe AddCheckConstraintExtraArguments end end
ruby
MIT
de0104c819ddd0a3d973db8e03e8971ac72a7b15
2026-01-04T15:46:43.728076Z
false