### 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? %>

<%= 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 %> ``` -------------------------------- ### Handle Unverified Request in Rails Controller Source: https://github.com/binarylogic/authlogic/blob/master/README.md Override `handle_unverified_request` in `ApplicationController` to implement custom CSRF protection handling when using Authlogic. This example shows 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 ``` -------------------------------- ### Create User and Log In Source: https://github.com/binarylogic/authlogic/blob/master/README.md Creates a new user record and automatically logs the user in after successful registration. This behavior can be configured. ```ruby User.create(params[:user]) ``` -------------------------------- ### Create User Session Source: https://github.com/binarylogic/authlogic/blob/master/README.md Log in a user by creating a UserSession instance with login credentials and an option to remember the user. ```ruby UserSession.create(:login => "bjohnson", :password => "my password", :remember_me => true) ``` -------------------------------- ### Multiple Session IDs Source: https://context7.com/binarylogic/authlogic/llms.txt Demonstrates how to manage multiple session types, such as a regular session and a secure/admin session. ```ruby # Regular session @user_session = UserSession.find ``` ```ruby # Admin/secure session @admin_session = UserSession.find(:secure) UserSession.create(admin_user, :secure) ``` -------------------------------- ### Save User Session Source: https://github.com/binarylogic/authlogic/blob/master/README.md Instantiate a UserSession with login credentials and save it to establish the user's session. ```ruby session = UserSession.new(:login => "bjohnson", :password => "my password", :remember_me => true) session.save ``` -------------------------------- ### Create User Session Source: https://github.com/binarylogic/authlogic/blob/master/README.md Creates a user session and optionally remembers the user. This handles authentication and sets up session cookies. ```ruby UserSession.create(my_user_object, true) ``` -------------------------------- ### User Registration Controller Source: https://context7.com/binarylogic/authlogic/llms.txt Handles user creation, validation, and automatic login after registration. Ensure acts_as_authentic is configured for login behavior. ```ruby # app/controllers/users_controller.rb class UsersController < ApplicationController before_action :require_no_user, only: [:new, :create] before_action :require_user, only: [:show, :edit, :update] def new @user = User.new end def create @user = User.new(user_params) if @user.save # User is automatically logged in if log_in_after_create is true flash[:notice] = "Account registered!" redirect_to account_url else render :new, status: :unprocessable_entity end end def show @user = current_user end def edit @user = current_user end def update @user = current_user if @user.update(user_params) # Session automatically updated if password changed flash[:notice] = "Account updated!" redirect_to account_url else render :edit, status: :unprocessable_entity end end private def user_params params.require(:user).permit(:login, :email, :password, :password_confirmation) end end ``` -------------------------------- ### Run Tests with Rails 7.2 Source: https://github.com/binarylogic/authlogic/blob/master/CONTRIBUTING.md Executes tests using the Rails 7.2 environment. ```bash BUNDLE_GEMFILE=gemfiles/rails_7.2.rb bundle exec rake ``` -------------------------------- ### Run a Single Test Source: https://github.com/binarylogic/authlogic/blob/master/CONTRIBUTING.md Executes a specific test file using the Rails 8.1 environment. ```bash BUNDLE_GEMFILE=gemfiles/rails_8.1.rb \ bundle exec ruby -I test path/to/test.rb ``` -------------------------------- ### Configure UserSession Security and Persistence Source: https://context7.com/binarylogic/authlogic/llms.txt Configure security settings like brute force protection and ban duration, as well as session persistence options such as remember me duration and cookie security attributes. ```ruby class UserSession < Authlogic::Session::Base # Security configuration consecutive_failed_logins_limit 50 # Brute force protection failed_login_ban_for 2.hours # Ban duration after limit exceeded generalize_credentials_error_messages true # Hide which field was wrong # Session persistence remember_me true # Remember by default remember_me_for 3.months # Cookie duration logout_on_timeout false # Require re-login after inactivity # Cookie security secure true # HTTPS only cookies httponly true # Not accessible via JavaScript same_site "Lax" # SameSite cookie attribute sign_cookie false # Sign cookie to prevent tampering encrypt_cookie false # Encrypt cookie contents # HTTP Basic Auth allow_http_basic_auth false # Single access token configuration single_access_allowed_request_types ["application/rss+xml", "application/atom+xml"] # Custom record finder record_selection_method :find_by_username_or_email # Callbacks after_persisting :my_custom_logging private def my_custom_logging Rails.logger.info("User #{record.id} authenticated successfully") end end ``` -------------------------------- ### Run Tests with Rails 8.1 Source: https://github.com/binarylogic/authlogic/blob/master/CONTRIBUTING.md Executes tests using the Rails 8.1 environment. ```bash BUNDLE_GEMFILE=gemfiles/rails_8.1.rb bundle exec rake ``` -------------------------------- ### Unit Test User Session Creation Source: https://context7.com/binarylogic/authlogic/llms.txt Tests the creation of a user session with valid credentials and verifies that the correct user is found. ```ruby class UserSessionTest < ActiveSupport::TestCase test "should create session with valid credentials" do ben = users(:ben) assert UserSession.create(login: "bjohnson", password: "password123") assert_equal ben, UserSession.find.user end test "should not create session with invalid password" do session = UserSession.new(login: "bjohnson", password: "wrong") assert_not session.save assert session.errors[:password].any? end end ``` -------------------------------- ### Database Migration for Users Table Source: https://context7.com/binarylogic/authlogic/llms.txt Set up the users table with columns required by Authlogic for authentication, session management, and login statistics. Includes fields for credentials, tokens, and magic columns. ```ruby # db/migrate/20240101000000_create_users.rb class CreateUsers < ActiveRecord::Migration[7.0] def change create_table :users do |t| # Login credentials t.string :email t.string :login t.index :email, unique: true # Password (encrypted) t.string :crypted_password t.string :password_salt # Session persistence token t.string :persistence_token t.index :persistence_token, unique: true # Single access token for API/RSS access t.string :single_access_token t.index :single_access_token, unique: true # Perishable token for password resets/confirmations t.string :perishable_token t.index :perishable_token, unique: true # Magic columns - login statistics 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 # Magic states - account status t.boolean :active, default: false t.boolean :approved, default: false t.boolean :confirmed, default: false t.timestamps end end end ``` -------------------------------- ### Run Tests with Rails 8.0 Source: https://github.com/binarylogic/authlogic/blob/master/CONTRIBUTING.md Executes tests using the Rails 8.0 environment. ```bash BUNDLE_GEMFILE=gemfiles/rails_8.0.rb bundle exec rake ``` -------------------------------- ### Define Application Controller Helper Methods Source: https://context7.com/binarylogic/authlogic/llms.txt Provides helper methods for accessing the current user session and user object throughout the application. Includes methods to require user login or ensure the user is logged out. ```ruby # app/controllers/application_controller.rb class ApplicationController < ActionController::Base helper_method :current_user_session, :current_user private 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 def require_user unless current_user store_location flash[:notice] = "You must be logged in to access this page" redirect_to new_user_session_url return false end end def require_no_user if current_user store_location flash[:notice] = "You must be logged out to access this page" redirect_to account_url return false end end def store_location session[:return_to] = request.url end def redirect_back_or_default(default) redirect_to(session[:return_to] || default) session[:return_to] = nil end # CSRF protection override for Authlogic sessions def handle_unverified_request current_user_session&.destroy redirect_to root_url end end ``` -------------------------------- ### Transition Crypto Providers Source: https://context7.com/binarylogic/authlogic/llms.txt Configure Authlogic to transition from older crypto providers (Sha512, Sha256) to BCrypt. Users will be automatically upgraded on their next login. ```ruby class User < ApplicationRecord acts_as_authentic do |c| c.crypto_provider = Authlogic::CryptoProviders::BCrypt c.transition_from_crypto_providers = [ Authlogic::CryptoProviders::Sha512, Authlogic::CryptoProviders::Sha256 ] end end ``` -------------------------------- ### Integration Test User Login and Logout Source: https://context7.com/binarylogic/authlogic/llms.txt Tests the user login process by posting credentials and verifying redirection and session presence. Also tests the logout process. ```ruby class UserSessionsControllerTest < ActionDispatch::IntegrationTest test "should login user" do post user_session_url, params: { user_session: { login: "bjohnson", password: "password123" } } assert_redirected_to account_url assert session[:user_credentials].present? end test "should logout user" do # Login first post user_session_url, params: { user_session: { login: "bjohnson", password: "password123" } } # Then logout delete user_session_url assert_redirected_to new_user_session_url assert session[:user_credentials].blank? end end ``` -------------------------------- ### Implement User Sessions Controller Source: https://context7.com/binarylogic/authlogic/llms.txt Handles user login, logout, and session creation. It uses the UserSession model and standard Rails controller patterns, including before_action filters for authentication state. ```ruby # app/controllers/user_sessions_controller.rb class UserSessionsController < ApplicationController before_action :require_no_user, only: [:new, :create] before_action :require_user, only: [:destroy] def new @user_session = UserSession.new end def create @user_session = UserSession.new(user_session_params.to_h) if @user_session.save flash[:notice] = "Login successful!" redirect_to account_url else render :new, status: :unprocessable_entity end end def destroy current_user_session.destroy flash[:notice] = "Logout successful!" redirect_to new_user_session_url end private def user_session_params params.require(:user_session).permit(:login, :password, :remember_me) end end ``` -------------------------------- ### Run RuboCop Linter Source: https://github.com/binarylogic/authlogic/blob/master/CONTRIBUTING.md Executes the RuboCop linter to check code style and quality within the Rails 8.1 environment. ```bash BUNDLE_GEMFILE=gemfiles/rails_8.1.rb bundle exec rubocop ``` -------------------------------- ### Application Controller Helper Methods Source: https://github.com/binarylogic/authlogic/blob/master/README.md Adds helper methods `current_user_session` and `current_user` to `ApplicationController` for easy access to the current session and user object throughout the application. ```ruby class ApplicationController < ActionController::Base helper_method :current_user_session, :current_user private 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 end ``` -------------------------------- ### Create User Table Migration Source: https://github.com/binarylogic/authlogic/blob/master/README.md This migration creates the 'users' table with columns required by Authlogic features like email, login, password, and persistence tokens. It also includes indexes for uniqueness and performance. ```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 ``` -------------------------------- ### Transition from Sha512 to SCrypt in Authlogic Source: https://github.com/binarylogic/authlogic/blob/master/UPGRADING.md Configure Authlogic to automatically upgrade passwords from Sha512 to SCrypt as users log in. This requires specifying the previous crypto providers and the new default. ```ruby c.transition_from_crypto_providers = [Authlogic::CryptoProviders::Sha512] c.crypto_provider = Authlogic::CryptoProviders::SCrypt ``` -------------------------------- ### Configure User Model with acts_as_authentic Source: https://context7.com/binarylogic/authlogic/llms.txt Integrate authentication functionality into your ActiveRecord model. Ensure crypto provider is configured for v6+ and consider password confirmation and blank password settings. Add custom validations for email, login, and password. ```ruby # app/models/user.rb class User < ApplicationRecord acts_as_authentic do |c| # Crypto provider configuration (required in v6+) c.crypto_provider = Authlogic::CryptoProviders::BCrypt # Transition from older crypto providers c.transition_from_crypto_providers = [Authlogic::CryptoProviders::Sha512] # Password configuration c.require_password_confirmation = true c.ignore_blank_passwords = true c.check_passwords_against_database = true # Logged in status timeout (for "who's online" features) c.logged_in_timeout = 10.minutes # Perishable token validity for password resets c.perishable_token_valid_for = 10.minutes # Automatic login after registration c.log_in_after_create = true c.log_in_after_password_change = true end # Validations (recommended to add your own in v5+) 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? } end ``` -------------------------------- ### User Model with Magic States Source: https://context7.com/binarylogic/authlogic/llms.txt Implement magic state methods (`active?`, `approved?`, `confirmed?`) in your User model. Authlogic checks these before allowing login. ```ruby class User < ApplicationRecord acts_as_authentic # Implement magic state methods def active? active == true end def approved? approved == true end def confirmed? confirmed == true end end ``` -------------------------------- ### Configure SCrypt Crypto Provider Source: https://context7.com/binarylogic/authlogic/llms.txt Use this to configure Authlogic to use the SCrypt crypto provider for password hashing. ```ruby class User < ApplicationRecord acts_as_authentic do |c| c.crypto_provider = Authlogic::CryptoProviders::SCrypt end end ``` -------------------------------- ### Define User Session Model Source: https://github.com/binarylogic/authlogic/blob/master/README.md Define a UserSession model by inheriting from Authlogic::Session::Base. Configuration options can be specified within the class. ```ruby class UserSession < Authlogic::Session::Base # specify configuration here, such as: # logout_on_timeout true # ...many more options in the documentation end ``` -------------------------------- ### Enable Single Access Token for API Source: https://context7.com/binarylogic/authlogic/llms.txt Configure UserSession to allow single access tokens for API authentication. This can be set for all request types or specific ones like JSON or RSS. ```ruby class UserSession < Authlogic::Session::Base # Allow single access for all request types single_access_allowed_request_types :all # Or restrict to specific types single_access_allowed_request_types ["application/rss+xml", "application/atom+xml", "application/json"] end ``` -------------------------------- ### Create Login Form View Source: https://context7.com/binarylogic/authlogic/llms.txt An ERB template for a user login form using Rails form helpers. It displays error messages and includes fields for login, password, and a 'remember me' checkbox. ```erb <%# app/views/user_sessions/new.html.erb %>

Login

<%= form_for @user_session, url: user_session_url do |f| %> <% if @user_session.errors.any? %>

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

<% end %>
<%= f.label :login %>
<%= f.text_field :login, autofocus: true %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.check_box :remember_me %> <%= f.label :remember_me, "Remember me on this computer" %>
<%= f.submit "Login" %>
<% end %>

<%= 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.