### Fixture Setup with Password Hashing Source: https://context7.com/binarylogic/authlogic/llms.txt Example of setting up user fixtures with proper password hashing, salts, and tokens using Authlogic's random generators. ```yaml # test/fixtures/users.yml ben: email: ben@example.com login: bjohnson password_salt: <%= salt = Authlogic::Random.hex_token %> crypted_password: <%= Authlogic::CryptoProviders::BCrypt.encrypt("password123" + salt) %> persistence_token: <%= Authlogic::Random.hex_token %> single_access_token: <%= Authlogic::Random.friendly_token %> perishable_token: <%= Authlogic::Random.friendly_token %> ``` -------------------------------- ### Test PostgreSQL Database Setup Source: https://github.com/binarylogic/authlogic/blob/master/CONTRIBUTING.md Creates the 'authlogic' PostgreSQL database and runs tests with PostgreSQL as the database. ```bash psql -c 'create database authlogic;' -U postgres DB=postgres BUNDLE_GEMFILE=gemfiles/rails_8.1.rb bundle exec rake ``` -------------------------------- ### Test MySQL Database Setup Source: https://github.com/binarylogic/authlogic/blob/master/CONTRIBUTING.md Drops and creates the 'authlogic' MySQL database, then runs tests with MySQL as the database. ```bash mysql -e 'drop database authlogic; create database authlogic;' && \ DB=mysql BUNDLE_GEMFILE=gemfiles/rails_8.1.rb bundle exec rake ``` -------------------------------- ### Install Rails 8.1 Dependencies Source: https://github.com/binarylogic/authlogic/blob/master/CONTRIBUTING.md Installs dependencies for testing with Rails 8.1. ```bash BUNDLE_GEMFILE=gemfiles/rails_8.1.rb bundle install ``` -------------------------------- ### Install Rails 7.2 Dependencies Source: https://github.com/binarylogic/authlogic/blob/master/CONTRIBUTING.md Installs dependencies for testing with Rails 7.2. ```bash BUNDLE_GEMFILE=gemfiles/rails_7.2.rb bundle install ``` -------------------------------- ### Install Rails 8.0 Dependencies Source: https://github.com/binarylogic/authlogic/blob/master/CONTRIBUTING.md Installs dependencies for testing with Rails 8.0. ```bash BUNDLE_GEMFILE=gemfiles/rails_8.0.rb bundle install ``` -------------------------------- ### Setup Authlogic Test Helpers Source: https://context7.com/binarylogic/authlogic/llms.txt Include Authlogic's test case helpers in `test_helper.rb` and set up `activate_authlogic` for testing. ```ruby # test/test_helper.rb require "authlogic/test_case" class ActiveSupport::TestCase include Authlogic::TestCase setup :activate_authlogic end ``` -------------------------------- ### URL-Based Authentication with Single Access Token Source: https://context7.com/binarylogic/authlogic/llms.txt Example of how to authenticate using a single access token appended to a URL. ```http # GET /posts.json?user_credentials=SINGLE_ACCESS_TOKEN ``` -------------------------------- ### Account Confirmation Flow Source: https://context7.com/binarylogic/authlogic/llms.txt Example controller logic for confirming a user's account using a token and setting the `confirmed` attribute. ```ruby class ConfirmationsController < ApplicationController def create @user = User.find_using_perishable_token(params[:token]) if @user @user.confirmed = true @user.save flash[:notice] = "Account confirmed!" redirect_to new_user_session_url else flash[:error] = "Invalid confirmation token" redirect_to root_url end end end ``` -------------------------------- ### Run a Single Test Without Bundler Source: https://github.com/binarylogic/authlogic/blob/master/CONTRIBUTING.md Executes a specific test file using the latest installed gem dependencies, omitting Bundler. This is suitable for certain unit tests. ```bash ruby –I test path/to/test.rb ``` -------------------------------- ### Controller-Level Single Access Control Source: https://context7.com/binarylogic/authlogic/llms.txt Control which controller actions allow single access tokens. This example restricts it to 'index' and 'show' actions. ```ruby class PostsController < ApplicationController private def single_access_allowed? %w[index show].include?(action_name) end end ``` -------------------------------- ### Extend UserSession with Custom Logging Callback Source: https://github.com/binarylogic/authlogic/blob/master/README.md Extend the UserSession class to include a custom logging callback after a session is persisted. This example demonstrates logging the user ID after authentication. ```ruby 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 ``` -------------------------------- ### Scoped Session Lookup Source: https://context7.com/binarylogic/authlogic/llms.txt Use `with_scope` to isolate authentication lookups for multi-tenant applications, for example, by `account_id`. ```ruby UserSession.with_scope( find_options: User.where(account_id: current_account.id), id: "account_" + current_account.id ) do @user_session = UserSession.find end ``` -------------------------------- ### User Session Form View Source: https://github.com/binarylogic/authlogic/blob/master/README.md Example ERB template for a user login form using Authlogic's form builder. Ensure you have the necessary instance variables and routes defined. ```erb <%= form_for @user_session, url: user_session_url do |f| %> <% if @user_session.errors.any? %>
<%= link_to "Forgot password?", new_password_reset_url %>
``` -------------------------------- ### Rails Routes for Authlogic Source: https://github.com/binarylogic/authlogic/blob/master/README.md Defines the necessary routes for user and user session management within a Rails application using `resources` and `resource`. ```ruby Rails.application.routes.draw do # ... resources :users resource :user_session end ``` -------------------------------- ### Direct BCrypt Crypto Provider Usage Source: https://context7.com/binarylogic/authlogic/llms.txt Directly use the BCrypt crypto provider for encrypting passwords, matching them, and checking the cost factor. ```ruby Authlogic::CryptoProviders::BCrypt.encrypt("password", "salt") ``` ```ruby Authlogic::CryptoProviders::BCrypt.matches?(crypted, "password", "salt") ``` ```ruby Authlogic::CryptoProviders::BCrypt.cost_matches?(crypted) # Check if cost is current ``` -------------------------------- ### Rails Routes Configuration for Sessions and Users Source: https://context7.com/binarylogic/authlogic/llms.txt Configures RESTful routes for user sessions, user management, account settings, and password resets in a Rails application. ```ruby Rails.application.routes.draw do # Session routes (singular resource) resource :user_session, only: [:new, :create, :destroy] # Convenience routes get "login" => "user_sessions#new", as: :login delete "logout" => "user_sessions#destroy", as: :logout # User routes resources :users, only: [:new, :create, :show, :edit, :update] resource :account, only: [:show, :edit, :update] # Current user's account # Password reset routes resources :password_resets, only: [:new, :create, :edit, :update] root "home#index" end ``` -------------------------------- ### Authlogic Password Management Methods Source: https://context7.com/binarylogic/authlogic/llms.txt Provides methods for password verification, reset, and persistence token management on the User model. Use `valid_password?` for checking, `reset_password` for resetting, and `reset_persistence_token` for token management. ```ruby # Password verification examples user = User.find_by(login: "bjohnson") # Check if password is valid user.valid_password?("mypassword") # Returns true/false user.valid_password?("mypassword", true) # Check against database value user.valid_password?("mypassword", false) # Check against object value # Password reset user.reset_password # Sets random password user.reset_password! # Sets random password and saves user.randomize_password # Alias for reset_password user.randomize_password! # Alias for reset_password! # Check if password is required user.require_password? # True if new record or crypted_password blank # Change password user.password = "newpassword" user.password_confirmation = "newpassword" user.save # Session automatically updated # Persistence token management user.reset_persistence_token # Generate new token user.reset_persistence_token! # Generate and save user.forget! # Alias - forces re-login User.forget_all # Reset all users' tokens ``` -------------------------------- ### Run Tests Without Linting Source: https://github.com/binarylogic/authlogic/blob/master/CONTRIBUTING.md Executes the test suite without running the linter, using the Rails 8.1 environment. ```bash BUNDLE_GEMFILE=gemfiles/rails_8.1.rb bundle exec rake test ``` -------------------------------- ### Password Reset Controller with Perishable Tokens Source: https://context7.com/binarylogic/authlogic/llms.txt Implements password reset functionality using perishable tokens that automatically expire. Requires `load_user_using_perishable_token` before edit and update actions. ```ruby # app/controllers/password_resets_controller.rb class PasswordResetsController < ApplicationController before_action :require_no_user before_action :load_user_using_perishable_token, only: [:edit, :update] def new end def create @user = User.find_by(email: params[:email]) if @user @user.reset_perishable_token! PasswordResetMailer.reset_email(@user).deliver_later flash[:notice] = "Instructions have been sent to your email." redirect_to root_url else flash[:error] = "No user was found with that email address" render :new, status: :unprocessable_entity end end def edit end def update @user.password = params[:user][:password] @user.password_confirmation = params[:user][:password_confirmation] if @user.save flash[:notice] = "Password successfully updated" redirect_to account_url else render :edit, status: :unprocessable_entity end end private def load_user_using_perishable_token @user = User.find_using_perishable_token(params[:id]) unless @user flash[:error] = "We're sorry, but we could not locate your account. " \ "If you are having issues try copying and pasting the URL " \ "from your email into your browser or restarting the reset password process." redirect_to root_url end end end # Custom perishable token validity # User.find_using_perishable_token(token) # Uses default 10 minutes # User.find_using_perishable_token(token, 1.hour) # Custom validity # User.find_using_perishable_token!(token) # Raises RecordNotFound if not found ``` -------------------------------- ### OpenID Authentication Source: https://github.com/binarylogic/authlogic/blob/master/README.md Authenticate a user using OpenID by providing the OpenID identifier and an option to remember the user. Requires the authlogic-oid gem. ```ruby UserSession.create(:openid_identifier => "identifier", :remember_me => true) ``` -------------------------------- ### Configure ActsAsAuthentic Source: https://github.com/binarylogic/authlogic/blob/master/README.md Integrates Authlogic authentication functionality into an ActiveRecord model. The configuration block is optional. ```ruby class User < ApplicationRecord acts_as_authentic do |c| c.my_config_option = my_value end # the configuration block is optional end ``` -------------------------------- ### Create User from OmniAuth Data Source: https://github.com/binarylogic/authlogic/wiki/Authlogic-Omniauth-Facebook This class method is used to find or initialize a user record based on OmniAuth authentication data. It sets user attributes from the auth hash and saves the record. Ensure the User model has corresponding attributes. ```ruby def self.from_omniauth(auth) where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user| user.provider = auth.provider user.uid = auth.uid user.first_name = auth.info.first_name user.last_name = auth.info.last_name user.name = auth.info.name user.email = auth.info.email user.oauth_token = auth.credentials.token user.oauth_expires_at = Time.at(auth.credentials.expires_at) user.save! end end ``` -------------------------------- ### UserSession Model Source: https://github.com/binarylogic/authlogic/blob/master/README.md Defines the `UserSession` model by inheriting from `Authlogic::Session::Base`. This model handles user session management. ```ruby class UserSession < Authlogic::Session::Base end ``` -------------------------------- ### Configure Crypto Provider Source: https://github.com/binarylogic/authlogic/blob/master/README.md Specifies how passwords should be cryptographically hashed or encrypted using Authlogic's crypto providers. ```ruby c.crypto_provider = Authlogic::CryptoProviders::BCrypt ``` -------------------------------- ### ApplicationController Session Scoping Source: https://context7.com/binarylogic/authlogic/llms.txt Implement session scoping within `ApplicationController` using an `around_action` to isolate authentication by account. ```ruby class ApplicationController < ActionController::Base around_action :scope_authentication private def scope_authentication UserSession.with_scope( find_options: current_account.users, id: current_account.id ) do yield end end def current_account @current_account ||= Account.find_by!(subdomain: request.subdomain) end end ``` -------------------------------- ### BCrypt Crypto Provider Configuration Source: https://context7.com/binarylogic/authlogic/llms.txt Configures Authlogic to use BCrypt for password hashing, which is recommended for new applications. The cost factor can be adjusted for security and performance. ```ruby # BCrypt configuration (recommended) class User < ApplicationRecord acts_as_authentic do |c| c.crypto_provider = Authlogic::CryptoProviders::BCrypt end end # Set BCrypt cost (default is 10, higher = more secure but slower) Authlogic::CryptoProviders::BCrypt.cost = 12 ``` -------------------------------- ### Generate and Find Single Access Token Source: https://context7.com/binarylogic/authlogic/llms.txt Methods to reset a user's single access token and find a user by their token. ```ruby user.reset_single_access_token ``` ```ruby user.reset_single_access_token! ``` ```ruby User.find_by_single_access_token(token) ``` -------------------------------- ### Find User Session Source: https://github.com/binarylogic/authlogic/blob/master/README.md Finds and retrieves an existing user session, persisting the login across requests. ```ruby session = UserSession.find ``` -------------------------------- ### Disable Log In After Create Source: https://github.com/binarylogic/authlogic/blob/master/README.md Configures Authlogic to not automatically log in a user after a successful registration. ```ruby class User < ApplicationRecord acts_as_authentic do |c| c.log_in_after_create = false end # the configuration block is optional end ``` -------------------------------- ### User Sessions Controller Source: https://github.com/binarylogic/authlogic/blob/master/README.md A standard Rails controller for managing user sessions, including creating new sessions, handling login attempts, and destroying sessions (logout). It uses `UserSession.new` and `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 ``` -------------------------------- ### Configure Authlogic Authentication Source: https://github.com/binarylogic/authlogic/wiki/Authlogic-Omniauth-Facebook Customize Authlogic's authentication behavior by setting login fields, validation rules, and password handling. This configuration is typically placed within the User model. ```ruby acts_as_authentic do |c| c.login_field = :email c.validate_email_field = true c.validate_login_field = false c.ignore_blank_passwords = true c.validate_password_field = false end ``` -------------------------------- ### Modify User Table Columns for Social Auth Source: https://github.com/binarylogic/authlogic/wiki/Authlogic-Omniauth-Facebook These database migration commands change the `crypted_password` and `password_salt` columns in the `users` table to allow null values. This is necessary when users can log in via social accounts without a traditional password. ```ruby change_column :users, :crypted_password, :string, :default => nil, :null => true change_column :users, :password_salt, :string, :default => nil, :null => true ``` -------------------------------- ### Update User Controller for OmniAuth Integration Source: https://github.com/binarylogic/authlogic/wiki/Authlogic-Omniauth-Facebook This controller action handles both existing user login and new user creation via OmniAuth. It checks for an existing logged-in user to link accounts, handles email/password authentication, and processes new social logins, including error handling for existing email accounts. ```ruby def create if current_user # add facebook to their already existing account User.existing_user_from_omniauth(env["omniauth.auth"], current_user) user = UserSession.find.user if user flash[:notice] = 'You successfully connected your Facebook account!' end elsif params.has_key?(:user_session) # email/password authentication @user_session = UserSession.new(params[:user_session]) if @user_session.save user = UserSession.find.user flash[:notice] = 'You successfully logged in. Welcome back!' end else # facebook authentication begin user = User.from_omniauth(env["omniauth.auth"]) rescue flash[:notice] = 'An account with this email already exists. Please login with your email and click "Connect with Facebook"' redirect_to new_session_path and return end @user_session = UserSession.create(user, true) if @user_session.save flash[:notice] = 'Welcome!' end end end ``` -------------------------------- ### Disable Magic States Checking Source: https://context7.com/binarylogic/authlogic/llms.txt Configure `UserSession` to disable the automatic checking of magic state methods. ```ruby class UserSession < Authlogic::Session::Base disable_magic_states true end ``` -------------------------------- ### Replace Authlogic Validations with ActiveRecord Source: https://github.com/binarylogic/authlogic/blob/master/doc/use_normal_rails_validation.md Instead of Authlogic's specific validation methods, use standard ActiveRecord `validates` with appropriate options. ```ruby validates :email, length: { ... } ``` -------------------------------- ### Destroy User Session Source: https://github.com/binarylogic/authlogic/blob/master/README.md Destroys the current user session, effectively logging the user out. ```ruby session.destroy ``` -------------------------------- ### User Model with Authlogic Source: https://github.com/binarylogic/authlogic/blob/master/README.md This User model integrates Authlogic using `acts_as_authentic`. It includes custom validations for email, login, and password, adhering to modern Rails validation practices. ```ruby class User < ApplicationRecord acts_as_authentic # Validate email, login, and password as you see fit. # # Authlogic < 5 added these validation for you, making them a little awkward # to change. In 4.4.0, those automatic validations were deprecated. See # https://github.com/binarylogic/authlogic/blob/master/doc/use_normal_rails_validation.md validates :email, format: { with: /@/, message: "should look like an email address." }, length: { maximum: 100 }, uniqueness: { case_sensitive: false, if: :will_save_change_to_email? } validates :login, format: { with: /\A[a-z0-9]+\z/, message: "should use only letters and numbers." }, length: { within: 3..100 }, uniqueness: { case_sensitive: false, 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 ``` -------------------------------- ### Authlogic Default Validations for Email, Login, and Password Source: https://github.com/binarylogic/authlogic/blob/master/doc/use_normal_rails_validation.md These are the default validation configurations for email, login, and password in Authlogic 4. Merge these with your existing settings. Ensure `will_save_change_to_email?`, `will_save_change_to_login?`, and `require_password?` methods are defined in your model. ```ruby EMAIL = / \A [A-Z0-9_.&%+\-']+ # mailbox @ (?:[A-Z0-9\-]+\.)+ # subdomains (?:[A-Z]{2,25}) # TLD \z /ix LOGIN = /\A[a-zA-Z0-9_][a-zA-Z0-9\.+\-_@ ]+\z/ ``` ```ruby 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? } ``` ```ruby 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: { case_sensitive: false, if: :will_save_change_to_login? } ``` ```ruby validates :password, confirmation: { if: :require_password? }, length: { minimum: 8, if: :require_password? } ``` ```ruby validates :password_confirmation, length: { minimum: 8, if: :require_password? } ``` -------------------------------- ### Specify Sha512 Crypto Provider in Authlogic Source: https://github.com/binarylogic/authlogic/blob/master/UPGRADING.md If you are upgrading from a version prior to 3.4.0 and did not previously set a crypto provider, specify Authlogic::CryptoProviders::Sha512 to prevent password breakage. ```ruby c.crypto_provider = Authlogic::CryptoProviders::Sha512 ``` -------------------------------- ### Update Existing User with OmniAuth Data Source: https://github.com/binarylogic/authlogic/wiki/Authlogic-Omniauth-Facebook This method updates an existing user's record with social authentication details. It's useful for linking a social account to an already logged-in user. The method saves the changes to the user record. ```ruby def self.existing_user_from_omniauth(auth, user) user.provider = auth.provider user.uid = auth.uid user.oauth_token = auth.credentials.token user.oauth_expires_at = Time.at(auth.credentials.expires_at) user.save end ``` -------------------------------- ### Disable Log In After Password Change Source: https://github.com/binarylogic/authlogic/blob/master/README.md Configures Authlogic to not automatically update the session when a user changes their password. ```ruby class User < ApplicationRecord acts_as_authentic do |c| c.log_in_after_password_change = false end # the configuration block is optional end ``` -------------------------------- ### Disable Authlogic Validations Source: https://github.com/binarylogic/authlogic/blob/master/doc/use_normal_rails_validation.md In Authlogic 4.4.0, disable the deprecated email, login, and password field validations to prepare for version 5.0.0. ```ruby acts_as_authentic do |c| c.validate_email_field = false c.validate_login_field = false c.validate_password_field = false end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.