### Fixture Example with Authlogic Crypto Providers Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase An example of a fixture definition, illustrating how to generate password salts and crypted passwords using Authlogic's random token generation and crypto providers like SCrypt. ```yaml 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 %> ``` -------------------------------- ### Install Authlogic Gem Source: https://www.rubydoc.info/github/binarylogic/authlogic/file/README Provides instructions for installing the Authlogic gem into a Ruby on Rails project by adding it to the `Gemfile` and running `bundle install`. ```ruby gem 'authlogic' ``` -------------------------------- ### Authlogic acts_as_authentic Method Implementation Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Base/Config%3Aacts_as_authentic This Ruby code defines the `acts_as_authentic` method within the Authlogic gem. It yields `self` if a block is given, checks for database setup, and includes relevant authentication modules. This is the core implementation of the authentication setup. ```ruby def acts_as_authentic yield self if block_given? return unless db_setup? acts_as_authentic_modules.each { |mod| include mod } end ``` -------------------------------- ### Configure User and UserSession Models for Authlogic Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/RackAdapter Illustrates the basic setup for User and UserSession models required by Authlogic, including specifying authlogic options and using acts_as_authentic. ```ruby class UserSession < Authlogic::Session::Base # Authlogic options go here end class User < ApplicationRecord acts_as_authentic end ``` -------------------------------- ### Create Custom Rack Adapter for Authlogic Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/RackAdapter Example of creating a custom Rack adapter by inheriting from Authlogic::ControllerAdapters::RackAdapter and defining the cookie_domain method. ```ruby class YourRackAdapter < Authlogic::ControllerAdapters::RackAdapter def cookie_domain 'your_cookie_domain_here.com' end end ``` -------------------------------- ### Login Form View Example (ERB) Source: https://www.rubydoc.info/github/binarylogic/authlogic/file/README This ERB template provides an example of a login form for user authentication using Authlogic. It utilizes Rails form helpers (`form_for`) to create input fields for login, password, and a remember me option, along with displaying validation errors. ```erb <%= form_for @user_session, url: user_session_url do |f| %> <% if @user_session.errors.any? %>

<%= pluralize(@user_session.errors.count, "error") %> prohibited:

<% end %> <%= f.label :login %>
<%= f.text_field :login %>

<%= f.label :password %>
<%= f.password_field :password %>

<%= f.label :remember_me %>
<%= f.check_box :remember_me %>

<%= f.submit "Login" %> <% end %> ``` -------------------------------- ### Basic Authlogic Testing Setup and User Login Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase Demonstrates the fundamental steps for testing Authlogic, including requiring the test case module, activating Authlogic before tests, and logging in a user session. ```ruby require "authlogic/test_case" setup :activate_authlogic UserSession.create(users(:whomever)) ``` -------------------------------- ### Activate Authlogic in Functional/Integration Tests Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase For functional and integration tests in Authlogic, activating the test case is done using the `setup` method. This ensures Authlogic is ready before tests execute. ```ruby setup :activate_authlogic ``` -------------------------------- ### Get logger Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Returns a MockLogger instance for logging purposes. This provides a mock logger for use in tests. ```ruby def logger @logger ||= MockLogger.new end ``` -------------------------------- ### Configure Raise on Model Setup Error (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Base/Config%3Araise_on_model_setup_error Sets or gets the configuration for raising errors during model setup in Authlogic. This is useful when the User model might not be available during the initial setup phase. It accepts a boolean value. ```Ruby def raise_on_model_setup_error(value = nil) rw_config(:raise_on_model_setup_error, value, false) end ``` -------------------------------- ### Get Logger Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockAPIController Provides a logger instance for the MockAPIController. It initializes a new MockLogger if one doesn't exist, facilitating logging during tests. ```ruby def logger @logger ||= MockLogger.new end ``` -------------------------------- ### Get Request Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockAPIController Returns the request object associated with the controller. It initializes a MockRequest object, passing the controller instance itself. ```ruby def request @request ||= MockRequest.new(self) end ``` -------------------------------- ### Setup Authlogic in Rails Test Helper Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase Shows how to require the Authlogic::TestCase module at the top of your test_helper.rb file in a Rails application. This makes Authlogic's testing utilities available throughout your test suite. ```ruby require "authlogic/test_case" ``` -------------------------------- ### Get Params Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockAPIController Returns the parameters hash for the controller. Initializes an empty hash if no parameters have been set, allowing for simulated request parameters. ```ruby def params @params ||= {} end ``` -------------------------------- ### Case-Sensitive Query Example (SQL) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Login/Config%3Afind_by_smart_case_login_field Shows the standard case-sensitive query, which may include a BINARY modifier if necessary for exact matching. ```sql "BINARY #{login_field} = #{login}" ``` -------------------------------- ### Authlogic Persistence Token Setup (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/PersistenceToken/Methods Sets up persistence token functionality when the module is included. This includes extending with class and instance methods, configuring password reset callbacks, and defining validations for the persistence token, ensuring uniqueness and presence under certain conditions. ```ruby 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 ``` -------------------------------- ### Get Controller Instance in AbstractAdapter Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/AbstractAdapter Returns the controller instance associated with this adapter. This attribute is fundamental for delegating requests. ```ruby def controller @controller end ``` -------------------------------- ### Get cookies Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Returns a MockCookieJar instance for managing cookies within the mock controller. It initializes the cookie jar if it hasn't been already. ```ruby def cookies @cookies ||= MockCookieJar.new end ``` -------------------------------- ### Get Session Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockAPIController Returns the session hash for the controller. Initializes an empty hash if the session has not been accessed, simulating session management. ```ruby def session @session ||= {} end ``` -------------------------------- ### Activate Authlogic for Testing (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase%3Aactivate_authlogic Activates Authlogic for use in tests by calling this method during the test setup phase. It ensures that Authlogic's session management is properly initialized for testing environments. ```ruby setup :activate_authlogic ``` ```ruby 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 ``` -------------------------------- ### Get Session in SinatraAdapter Controller Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/SinatraAdapter/Controller Retrieves the session object from the Sinatra environment (env). This is used for managing user sessions. ```ruby def session env["rack.session"] end ``` -------------------------------- ### Configure Model Setup Error Handling (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Base/Config Configures whether to raise an error when acts_as_authentic is called without a database connection or existing users table. Setting this to false allows the User model to be relied upon before the database is fully set up. Defaults to false. ```Ruby def raise_on_model_setup_error(value = nil) rw_config(:raise_on_model_setup_error, value, false) end ``` -------------------------------- ### Get signed cookie jar in Authlogic::TestCase::MockCookieJar Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockCookieJar Returns an instance of MockSignedCookieJar, initializing it with the current cookie jar if it hasn't been created yet. This facilitates testing with signed cookies. ```ruby # File 'lib/authlogic/test_case/mock_cookie_jar.rb', line 27 def signed @signed ||= MockSignedCookieJar.new(self) end ``` -------------------------------- ### Case-Insensitive Query Example (SQL) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Login/Config%3Afind_by_smart_case_login_field Illustrates how the query is modified for case-insensitive searches when the login field's column does not have a case-insensitive collation. ```sql "LOWER(""#{quoted_table_name}"".""#{login_field}"") = LOWER(""#{login}"")" ``` -------------------------------- ### Get Environment Hash in MockRequest (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockRequest Returns the environment hash for the mock request, initializing it if it hasn't been set. This hash often contains session options. ```ruby def env @env ||= { ControllerAdapters::AbstractAdapter::ENV_SESSION_OPTIONS => {} } end ``` -------------------------------- ### Initialize NotActivatedError in Authlogic Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/Session/Activation/NotActivatedError%3Ainitialize This method initializes the NotActivatedError, which is raised when the Authlogic controller has not been activated with a controller object. It provides a specific error message to guide the user. ```ruby def initialize super( "You must activate the Authlogic::Session::Base.controller with " \ "a controller object before creating objects" ) end ``` -------------------------------- ### Extending UserSession with Callbacks in Authlogic Source: https://www.rubydoc.info/github/binarylogic/authlogic/file/README Demonstrates how to extend the `UserSession` model in Authlogic by adding custom callbacks. The example defines a `my_custom_logging` method that is executed after a successful authentication attempt, logging the user's ID. ```ruby # user_session.rb class UserSession < Authlogic::Session::Base after_persisting :my_custom_logging private def my_custom_logging Rails.logger.info( format( 'After authentication attempt, user id is %d', record.send(record.class.primary_key) ) ) end end ``` -------------------------------- ### Authlogic::ModelSetupError: message Method - Ruby Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ModelSetupError The `message` method for Authlogic::ModelSetupError returns a string detailing the setup error. It suggests ensuring a database connection and running migrations before using `acts_as_authentic`. If the User model needs to be loaded before the database is set up, it provides a configuration option to disable this error. ```Ruby 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 ``` -------------------------------- ### Get Crypto Provider Class (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Password/Config Retrieves the configured crypto provider class used for password encryption and verification. Raises NilCryptoProvider if not set. ```Ruby # File 'lib/authlogic/acts_as_authentic/password.rb', line 118 def crypto_provider acts_as_authentic_config[:crypto_provider].tap { |provider| raise NilCryptoProvider if provider.nil? } end ``` -------------------------------- ### Include acts_as_authentic in a User Model Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Base/Config%3Aacts_as_authentic This snippet shows how to include the `acts_as_authentic` functionality in a Ruby on Rails User model. It requires the Authlogic gem to be installed. ```ruby class User < ApplicationRecord acts_as_authentic end ``` -------------------------------- ### Get Crypto Provider Configuration (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Password/Config%3Acrypto_provider Retrieves the configured crypto provider class for password encryption. Raises NilCryptoProvider if no provider is set. Requires the Authlogic library. ```ruby def crypto_provider acts_as_authentic_config[:crypto_provider].tap { |provider| raise NilCryptoProvider if provider.nil? } end ``` -------------------------------- ### Get Cookie Domain for Sinatra Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/SinatraAdapter/Adapter Retrieves the cookie domain by accessing the 'SERVER_NAME' from the environment variables. This method is part of the Sinatra controller adapter for Authlogic. ```ruby def cookie_domain env["SERVER_NAME"] end ``` -------------------------------- ### Get Authlogic Gem Version Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic Retrieves the version of the Authlogic gem. This method returns a `::Gem::Version` object, which is preferred for version comparisons over a simple string. It's defined in `lib/authlogic/version.rb` and was introduced in Authlogic 4.0.0. ```ruby def self.gem_version ::Gem::Version.new("6.5.0") end ``` -------------------------------- ### Initialize RackAdapter in Authlogic Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/RackAdapter Provides the implementation for initializing the RackAdapter, setting up the Rack::Request object, and configuring Authlogic's controller. ```ruby # File 'lib/authlogic/controller_adapters/rack_adapter.rb', line 42 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 ``` -------------------------------- ### Initialize Authlogic Guidance Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/CryptoProviders/Guidance Initializes a new instance of the Guidance class, storing the provided crypto provider. This is a standard constructor method for the Guidance object. ```ruby def initialize(provider) @provider = provider end ``` -------------------------------- ### Get Request Object in Sinatra Adapter Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/SinatraAdapter/Cookies Returns the request object associated with the Cookies instance. This attribute is read-only and provides access to the incoming request details, including cookies. ```ruby def request @request end ``` -------------------------------- ### Get realm Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Returns the value of the realm attribute. The realm is used in HTTP authentication challenges. ```ruby def realm @realm end ``` -------------------------------- ### Set Up Authlogic Middleware in Rack Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/RackAdapter Demonstrates how to define and initialize a Rack middleware that integrates the custom Authlogic adapter. ```ruby class AuthlogicMiddleware def initialize(app) @app = app end def call(env) YourRackAdapter.new(env) @app.call(env) end end ``` -------------------------------- ### Get encrypted cookie jar in Authlogic::TestCase::MockCookieJar Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockCookieJar Returns an instance of MockEncryptedCookieJar, initializing it with the current cookie jar if it hasn't been created yet. This allows for handling encrypted cookies within the test environment. ```ruby # File 'lib/authlogic/test_case/mock_cookie_jar.rb', line 31 def encrypted @encrypted ||= MockEncryptedCookieJar.new(self) end ``` -------------------------------- ### Get http_user Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Returns the value of the http_user attribute. This attribute stores the username for HTTP basic authentication. ```ruby def http_user @http_user end ``` -------------------------------- ### Get cookie_domain Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Returns the cookie domain, which is nil in this mock implementation. This simulates the absence of a specific cookie domain. ```ruby def cookie_domain nil end ``` -------------------------------- ### Handle CSRF Protection in Rails with Authlogic Source: https://www.rubydoc.info/github/binarylogic/authlogic/file/README Overrides `ActionController::Base#handle_unverified_request` to manage unverified requests when using Authlogic. This is necessary because Authlogic's session management differs from Rails' built-in CSRF protection. The example shows options for raising an exception or destroying the session and redirecting. ```ruby class ApplicationController < ActionController::Base ... protected def handle_unverified_request # raise an exception fail ActionController::InvalidAuthenticityToken # or destroy session, redirect if current_user_session current_user_session.destroy end redirect_to root_url end end ``` -------------------------------- ### User Login and Session Management in Ruby Source: https://www.rubydoc.info/github/binarylogic/authlogic/file/README Demonstrates various methods for creating, saving, and finding user sessions using Authlogic. It covers direct creation with credentials, using `UserSession.new` for manual saving, creating sessions with OpenID, and direct user object creation. It also shows how to destroy a session. ```ruby UserSession.create(:login => "bjohnson", :password => "my password", :remember_me => true) session = UserSession.new(:login => "bjohnson", :password => "my password", :remember_me => true) session.save # requires the authlogic-oid "add on" gem UserSession.create(:openid_identifier => "identifier", :remember_me => true) # skip authentication and log the user in directly, the true means "remember me" UserSession.create(my_user_object, true) session.destroy session = UserSession.find ``` -------------------------------- ### Initialize SinatraAdapter Controller Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/SinatraAdapter/Controller Initializes the SinatraAdapter::Controller with request and response objects. It sets up instance variables for request and cookies. ```ruby def initialize(request, response) @request = request @cookies = Cookies.new(request, response) end ``` -------------------------------- ### Sinatra Controller Integration with Authlogic Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/SinatraAdapter/Adapter/Implementation This Ruby code demonstrates how Authlogic integrates with Sinatra controllers. It uses the `before` filter to set up the controller and adapter for session management upon inclusion. ```ruby def self.included(klass) klass.send :before do controller = Controller.new(request, response) Authlogic::Session::Base.controller = Adapter.new(controller) end end ``` -------------------------------- ### Get request_content_type Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Returns the content type of the request, defaulting to 'text/html' if not set. This is useful for simulating request headers in tests. ```ruby def request_content_type @request_content_type ||= "text/html" end ``` -------------------------------- ### Get http_password Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Returns the value of the http_password attribute. This is used in HTTP basic authentication scenarios within the testing framework. ```ruby def http_password @http_password end ``` -------------------------------- ### Initialize AbstractAdapter Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/AbstractAdapter Initializes the AbstractAdapter with a controller instance. This is the constructor for the class. ```ruby def initialize(controller) self.controller = controller end ``` -------------------------------- ### Initialize RackAdapter with Rack::Request Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/RackAdapter%3Ainitialize This Ruby code initializes the RackAdapter by creating a Rack::Request object from the provided environment (env). It then extends the request object with methods like `request` and `remote_ip` to ensure compatibility with Authlogic's controller interface. Finally, it sets the Authlogic session controller to the newly created adapter instance. ```ruby 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 ``` -------------------------------- ### Configure Password Crypto Provider Transition (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Password/Config%3Atransition_from_crypto_providers This Ruby method configures Authlogic to transition user passwords from older crypto providers to newer ones. It handles the migration seamlessly on the next user login and supports transitioning from multiple algorithms. ```ruby def transition_from_crypto_providers(value = nil) rw_config( :transition_from_crypto_providers, (!value.nil? && [value].flatten.compact) || value, [] ) end ``` -------------------------------- ### Initialize SinatraAdapter Controller Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/SinatraAdapter/Controller%3Ainitialize Initializes the SinatraAdapter Controller with the provided request and response objects. It sets up internal instance variables for request handling and cookie management. This is a core part of setting up Authlogic within a Sinatra application. ```ruby def initialize(request, response) @request = request @cookies = Cookies.new(request, response) end ``` -------------------------------- ### Get Cookie Domain Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockAPIController Returns the cookie domain. In this mock implementation, it returns nil, indicating no specific domain is set for cookies. ```ruby def cookie_domain nil end ``` -------------------------------- ### Authenticate with HTTP basic Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Handles HTTP basic authentication by yielding the http_user and http_password. This method is a simplified version of the authentication process. ```ruby def authenticate_with_http_basic yield http_user, http_password end ``` -------------------------------- ### Load Authlogic Middleware in Rack Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/RackAdapter Shows the simple command to include the AuthlogicMiddleware in a Rack application's configuration. ```ruby use AuthlogicMiddleware ``` -------------------------------- ### Get Request Content Type - Ruby Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/AbstractAdapter Retrieves the content type of the current request. This method delegates to the controller's request object. ```ruby def request_content_type request.content_type end ``` -------------------------------- ### Define Warning for Non-Adaptive Crypto Providers Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/CryptoProviders/Guidance Defines a warning message template for crypto providers that are not adaptive. It informs the user that while the algorithm has no known practical attacks, better adaptive choices like scrypt exist, recommending a transition. ```ruby 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 ``` -------------------------------- ### Get IP Address in MockRequest (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockRequest Retrieves the IP address from the controller's environment or defaults to '1.1.1.1'. It safely accesses nested attributes. ```ruby def ip controller&.respond_to?(:env) && controller.env.is_a?(Hash) && controller.env["REMOTE_ADDR"] || "1.1.1.1" end ``` -------------------------------- ### Initialize MockAPIController Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockAPIController Constructor for MockAPIController. Initializes a new instance of the class without performing any actions. ```ruby def initialize end ``` -------------------------------- ### Authlogic::ModelSetupError#message - Ruby Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ModelSetupError%3Amessage Returns a detailed error message for `Authlogic::ModelSetupError`. It advises users to establish a database connection and run migrations before using `acts_as_authentic`. It also provides a workaround by setting `raise_on_model_setup_error` to `false`. ```ruby 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 ``` -------------------------------- ### Remove Authlogic Module from Model (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Base/Config Removes a previously added module from the list of modules to be included during acts_as_authentic setup. This is the inverse operation of add_acts_as_authentic_module. ```Ruby def remove_acts_as_authentic_module(mod) modules = acts_as_authentic_modules.clone modules.delete(mod) self.acts_as_authentic_modules = modules end ``` -------------------------------- ### Define Warning for Vulnerable Crypto Providers Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/CryptoProviders/Guidance Defines a warning message template for crypto providers that are known to be vulnerable. It highlights that the chosen algorithm is a poor choice due to known attacks and strongly recommends transitioning to a secure, adaptive hashing algorithm like scrypt. ```ruby 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 ``` -------------------------------- ### Authenticate with HTTP Basic Authentication Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/AbstractAdapter Handles HTTP Basic authentication by parsing the request environment. It yields the credentials if authentication is provided and basic, otherwise returns false. ```ruby 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 ``` -------------------------------- ### Testing Authlogic Interaction with Mock Controller Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase This snippet demonstrates unit testing Authlogic by interacting with a mock controller. It checks the session state before and after creating a user session, verifying Authlogic's integration. ```ruby ben = users(:ben) assert_nil controller.session["user_credentials"] assert UserSession.create(ben) assert_equal controller.session["user_credentials"], ben.persistence_token ``` -------------------------------- ### Get set_cookies attribute in Authlogic::TestCase::MockCookieJar Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockCookieJar Retrieves the value of the @set_cookies instance variable. This method is part of the Authlogic::TestCase::MockCookieJar class and does not have external dependencies. ```ruby # File 'lib/authlogic/test_case/mock_cookie_jar.rb', line 8 def set_cookies @set_cookies end ``` -------------------------------- ### Authenticate or request with HTTP basic Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Simulates the HTTP basic authentication process. It sets the realm and indicates that authentication is requested, then yields the http_user and http_password. ```ruby def authenticate_or_request_with_http_basic(realm = "DefaultRealm") self.realm = realm @http_auth_requested = true yield http_user, http_password end ``` -------------------------------- ### Get Cookie Domain (RailsAdapter) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/RailsAdapter Retrieves the cookie domain from the Rails controller's session options. This method accesses the session configuration to determine the domain for cookies. ```ruby def cookie_domain controller.request.session_options[:domain] end ``` -------------------------------- ### Initialize AssignsLastRequestAt Instance Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/Session/MagicColumn/AssignsLastRequestAt%3Ainitialize Initializes a new instance of AssignsLastRequestAt with the current time, record, controller, and last request at threshold. This method is part of a private API. ```ruby 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 ``` -------------------------------- ### Authlogic initialize Method Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase This Ruby method is the constructor for Authlogic's test case utilities. It initializes the @request instance variable to nil and calls the superclass constructor. ```ruby # File 'lib/authlogic/test_case.rb', line 182 def initialize(*args) @request = nil super end ``` -------------------------------- ### Get Request Content Type in Rails Request Adapter Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/RailsRequestAdapter Retrieves the content type of the request in the Rails request adapter. It accesses the request object and returns its format as a string. ```ruby def request_content_type request.format.to_s end ``` -------------------------------- ### Authenticate with HTTP Basic Auth (RailsAdapter) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/RailsAdapter Implements HTTP basic authentication for Rails controllers. It delegates the authentication process to the underlying Rails controller. No external dependencies are explicitly mentioned beyond the Rails environment. ```ruby def authenticate_with_http_basic(&block) controller.authenticate_with_http_basic(&block) end ``` -------------------------------- ### Get Cookie Domain in Rails Request Adapter Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/RailsRequestAdapter Retrieves the cookie domain for the Rails request adapter. This method currently returns nil, indicating no specific domain is set. ```ruby def cookie_domain nil end ``` -------------------------------- ### Get Request Content Type Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockAPIController Returns the request content type, defaulting to 'text/html' if not already set. This attribute is part of the MockAPIController's interface for simulating request properties. ```ruby def request_content_type @request_content_type ||= "text/html" end ``` -------------------------------- ### Authenticate with HTTP Basic Auth (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/AbstractAdapter%3Aauthenticate_with_http_basic This method handles HTTP Basic authentication by parsing the request environment and yielding credentials if authentication is provided and basic. It returns false otherwise. Dependencies include Rack::Auth::Basic. ```Ruby 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 ``` -------------------------------- ### Initialize AssignsLastRequestAt Constructor Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/Session/MagicColumn/AssignsLastRequestAt Initializes a new instance of AssignsLastRequestAt with the current time, record, controller, and a threshold. This is a private method and should be used with caution. ```ruby 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 ``` -------------------------------- ### Get Request Content Type (RailsAdapter) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/RailsAdapter Determines and returns the content type of the current request in a Rails application. It uses the 'request' object to access the format and convert it to a string. ```ruby def request_content_type request.format.to_s end ``` -------------------------------- ### Get Password - Authlogic Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Password/Methods/InstanceMethods Retrieves the current password. Returns nil if the password has not been set yet. This method is part of the Authlogic gem's password management features. ```Ruby def password return nil unless defined?(@password) @password end ``` -------------------------------- ### Configure Model for Authlogic Authentication (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Base/Config Sets up a model for authentication using authlogic. It includes helpful methods for authenticating records and can be configured with custom options. It relies on the Authlogic::Session module and requires a database connection. ```Ruby class User < ApplicationRecord acts_as_authentic end ``` ```Ruby acts_as_authentic do |c| c.my_configuration_option = my_value end ``` ```Ruby def acts_as_authentic yield self if block_given? return unless db_setup? acts_as_authentic_modules.each { |mod| include mod } end ``` -------------------------------- ### Initialize Mock Controller Request Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Initializes and returns a `MockRequest` object for the mock controller. This allows for simulating request objects during testing. ```ruby def request @request ||= MockRequest.new(self) end ``` -------------------------------- ### Get Response Object in Sinatra Adapter Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/SinatraAdapter/Cookies Returns the response object associated with the Cookies instance. This attribute is read-only and allows the adapter to set or delete cookies on the outgoing response. ```ruby def response @response end ``` -------------------------------- ### Rails 5 Integration Test Login Helper Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase This Ruby code defines a helper method 'login' to simulate a user logging in by making a POST request to the user sessions URL. It's designed for use in Rails integration tests. ```ruby # 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 ``` -------------------------------- ### Create User Table Migration (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/file/README This Ruby migration defines the schema for the 'users' table, including fields required by Authlogic for email, login, password management, persistence, access tokens, and session tracking. It also sets up indexes for uniqueness and timestamps. ```ruby class CreateUser < ActiveRecord::Migration def change create_table :users do |t| # Authlogic::ActsAsAuthentic::Email t.string :email t.index :email, unique: true # Authlogic::ActsAsAuthentic::Login t.string :login # Authlogic::ActsAsAuthentic::Password t.string :crypted_password t.string :password_salt # Authlogic::ActsAsAuthentic::PersistenceToken t.string :persistence_token t.index :persistence_token, unique: true # Authlogic::ActsAsAuthentic::SingleAccessToken t.string :single_access_token t.index :single_access_token, unique: true # Authlogic::ActsAsAuthentic::PerishableToken t.string :perishable_token t.index :perishable_token, unique: true # See "Magic Columns" in Authlogic::Session::Base t.integer :login_count, default: 0, null: false t.integer :failed_login_count, default: 0, null: false t.datetime :last_request_at t.datetime :current_login_at t.datetime :last_login_at t.string :current_login_ip t.string :last_login_ip # See "Magic States" in Authlogic::Session::Base t.boolean :active, default: false t.boolean :approved, default: false t.boolean :confirmed, default: false t.timestamps end end end ``` -------------------------------- ### Conditionally disable last_request_at update (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ControllerAdapters/AbstractAdapter%3Alast_request_update_allowed%3F This Ruby example shows how to conditionally control the updating of `last_request_at` based on the current controller action. It prevents updates for the 'update_session_time_left' action. ```ruby def last_request_update_allowed? action_name != "update_session_time_left" end ``` -------------------------------- ### Authlogic::ActsAsAuthentic::Password::Config - transition_from_crypto_providers Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Password/Config Allows specifying previous crypto providers for gradual migration to new encryption methods. ```APIDOC ## GET /acts_as_authentic/password/transition_from_crypto_providers ### Description Specifies an array of previous crypto provider classes to allow for gradual transitions. This is useful when migrating password encryption methods. ### Method GET (or can be set via POST-like configuration) ### Endpoint `/acts_as_authentic/password/transition_from_crypto_providers` ### Parameters #### Query Parameters - `value` (Array) - Optional - An array of crypto provider classes to transition from. ### Request Example ```json { "value": ["Authlogic::CryptoProviders::Sha512"] } ``` ### Response #### Success Response (200) - `transition_from_crypto_providers` (Array) - The list of previous crypto providers. #### Response Example ```json { "transition_from_crypto_providers": ["Authlogic::CryptoProviders::Sha1"] } ``` ``` -------------------------------- ### Initialize MockController Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Constructor for MockController. Initializes a new instance of the class. This method is part of the testing utility for Authlogic. ```ruby def initialize end ``` -------------------------------- ### Initialize Mock Controller Session Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Initializes and returns the session hash for the mock controller. This is used for simulating user sessions in tests. ```ruby def session @session ||= {} end ``` -------------------------------- ### Configure Password Confirmation Requirement (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Password/Config%3Arequire_password_confirmation Sets or gets the configuration value for requiring password confirmation. If not explicitly set, it defaults to true. This method is part of the Authlogic gem for handling user authentication. ```ruby def require_password_confirmation(value = nil) rw_config(:require_password_confirmation, value, true) end ``` -------------------------------- ### Initialize Mock Controller Params Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockController Initializes and returns the params hash for the mock controller. This is typically used in testing to simulate request parameters. ```ruby def params @params ||= {} end ``` -------------------------------- ### Ruby: Authlogic::ActsAsAuthentic::Password::Methods.included Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Password/Methods The `included` method is a hook that gets called whenever this module is included into another class. It ensures that `InstanceMethods` are included and sets up an `after_save` callback to reset the `password_changed` attribute. ```ruby def self.included(klass) return if klass.crypted_password_field.nil? klass.class_eval do include InstanceMethods after_save :reset_password_changed end end ``` -------------------------------- ### Sessions Controller Implementation (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/file/README This Ruby code demonstrates a typical Rails controller for managing user sessions using Authlogic. It includes actions for creating a new session (login form), handling the login submission, and destroying a session (logout). It also defines private methods for parameter handling and retrieving the current user session. ```ruby class UserSessionsController < ApplicationController def new @user_session = UserSession.new end def create @user_session = UserSession.new(user_session_params.to_h) if @user_session.save redirect_to root_url else render :new, status: 422 end end def destroy current_user_session.destroy redirect_to new_user_session_url end private def user_session_params params.require(:user_session).permit(:login, :password, :remember_me) end end ``` -------------------------------- ### Initialize FindWithCase - Ruby Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Queries/FindWithCase Initializes a new instance of the FindWithCase class with the model class, field, value, and sensitivity flag. This method is part of Authlogic's private API. ```ruby def initialize(model_class, field, value, sensitive) @model_class = model_class @field = field.to_s @value = value @sensitive = sensitive end ``` -------------------------------- ### Configure Logged In Timeout - Ruby Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/LoggedInStatus/Config Sets or gets the timeout duration for determining if a user is logged in. It accepts an integer value and defaults to 10 minutes. This configuration is crucial for managing user session validity. ```ruby def logged_in_timeout(value = nil) rw_config(:logged_in_timeout, (!value.nil? && value.to_i) || value, 10.minutes.to_i) end ``` -------------------------------- ### Rails Routes for User Authentication (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/file/README This Ruby code defines the necessary routes in a Rails application for managing users and user sessions. It uses `resources :users` for user management and `resource :user_session` for handling login and logout actions, integrating with Authlogic's conventions. ```ruby Rails.application.routes.draw do # ... resources :users resource :user_session end ``` -------------------------------- ### Initialize FindWithCase in Ruby Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Queries/FindWithCase%3Ainitialize Initializes a new FindWithCase object with the provided model class, field, value, and sensitivity flag. This method is part of Authlogic's private API. ```ruby def initialize(model_class, field, value, sensitive) @model_class = model_class @field = field.to_s @value = value @sensitive = sensitive end ``` -------------------------------- ### Configure Ignoring Blank Passwords in Authlogic (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Password/Config%3Aignore_blank_passwords Sets whether Authlogic should ignore blank passwords. By default, blank passwords are ignored when a record is new or the crypted_password is blank. Set to false to disable this behavior, for example, on password reset pages. ```Ruby def ignore_blank_passwords(value = nil) rw_config(:ignore_blank_passwords, value, true) end ``` -------------------------------- ### Initialize MockRequest in Ruby Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockRequest Initializes a new instance of MockRequest, setting the associated controller. This is crucial for mocking request objects in tests. ```ruby def initialize(controller) self.controller = controller end ``` -------------------------------- ### Initialize MockSignedCookieJar (Ruby) Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/TestCase/MockSignedCookieJar Constructs a new instance of MockSignedCookieJar, initializing it with cookies from a parent jar. It iterates through the parent jar and sets each cookie in the new instance, ensuring that any existing cookies are copied over. ```ruby def initialize(parent_jar) @parent_jar = parent_jar parent_jar.each { |k, v| self[k] = v } end ``` -------------------------------- ### Initialize CaseSensitivity in Ruby Source: https://www.rubydoc.info/github/binarylogic/authlogic/Authlogic/ActsAsAuthentic/Queries/CaseSensitivity%3Ainitialize Initializes a new instance of the CaseSensitivity class. This method takes the model class and attribute as arguments and stores them internally. It is intended for internal use within the Authlogic gem. ```ruby def initialize(model_class, attribute) @model_class = model_class @attribute = attribute.to_sym end ```