### WebAuthn Setup Source: https://github.com/jeremyevans/rodauth/blob/master/doc/internal_request.rdoc Creates a WebAuthn credential for the account. ```APIDOC ## WebAuthn Setup ### Description Creates a WebAuthn credential for the account. ### Method POST ### Endpoint /webauthn/setup ### Parameters #### Query Parameters - **account_id** (string) - Required - The ID of the account. #### Request Body - **webauthn_setup** (object) - Required - The WebAuthn credential provided by the client during registration. - **webauthn_setup_challenge** (string) - Required - The WebAuthn challenge generated for registration. - **webauthn_setup_challenge_hmac** (string) - Required - The HMAC of the WebAuthn challenge generated for registration. ### Request Example ```json { "webauthn_setup": { "id": "credential_id", "rawId": "raw_credential_id", "response": { "clientDataJSON": "client_data_json_string", "attestationObject": "attestation_object_string" }, "type": "public-key" }, "webauthn_setup_challenge": "challenge_string", "webauthn_setup_challenge_hmac": "hmac_string" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the WebAuthn credential was created successfully. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### WebAuthn Setup Parameters Source: https://github.com/jeremyevans/rodauth/blob/master/doc/internal_request.rdoc Retrieves parameters required for WebAuthn registration setup. ```APIDOC ## WebAuthn Setup Parameters ### Description Returns a hash with `:webauthn_setup`, `:webauthn_setup_challenge`, and `:webauthn_setup_challenge_hmac` keys. The `:webauthn_setup` options should be provided to the client for WebAuthn registration, while `:webauthn_setup_challenge` and `:webauthn_setup_challenge_hmac` should be passed to the `webauthn_setup` method. ### Method GET ### Endpoint /webauthn/setup/params ### Parameters #### Query Parameters - **account_id** (string) - Required - The ID of the account. ### Response #### Success Response (200) - **webauthn_setup** (object) - Options for client-side WebAuthn registration. - **webauthn_setup_challenge** (string) - Challenge for WebAuthn registration. - **webauthn_setup_challenge_hmac** (string) - HMAC of the WebAuthn registration challenge. #### Response Example ```json { "webauthn_setup": { "publicKey": { "challenge": "challenge_string", "rp": {"name": "Rodauth"}, "user": {"id": "user_id_bytes", "name": "username"}, "pubKeyCredParams": [{"type": "public-key", "alg": -7}] } }, "webauthn_setup_challenge": "challenge_string", "webauthn_setup_challenge_hmac": "hmac_string" } ``` ``` -------------------------------- ### require_two_factor_setup Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Requires that the session has set up two-factor authentication. Redirects to the two-factor setup page if not configured. ```APIDOC ## require_two_factor_setup ### Description (two_factor_base feature) Require the session to have setup two factor authentication, redirecting the request to the two factor authentication setup page if not. ### Method (Not specified, typically called within a Roda route block) ### Endpoint (Not applicable, method call within application logic) ### Parameters None ``` -------------------------------- ### Rodauth Object Model Example Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/internals.rdoc Illustrates the relationships between Rodauth::Configuration, Rodauth::Auth, and Rodauth::Feature instances during configuration and runtime. ```ruby Roda.plugin :rodauth do self # => # (instance) auth # => Rodauth::Auth subclass singleton_class.ancestors # => [#> (singleton class of self), # Rodauth::FeatureConfiguration::Base (instance of Rodauth::FeatureConfiguration), # Rodauth::Configuration, # ...] auth.ancestors # => [Rodauth::Auth subclass, # Rodauth::Base (instance of Rodauth::Feature), # Rodauth::Auth, # ...] enable :login singleton_class.ancestors # => [#> (singleton class of self), # Rodauth::FeatureConfiguration::Login (instance of Rodauth::FeatureConfiguration), # Rodauth::FeatureConfiguration::Base (instance of Rodauth::FeatureConfiguration), # Rodauth::Configuration, # ...] auth.ancestors # => [Rodauth::Auth subclass, # Rodauth::Login (instance of Rodauth::Feature), # Rodauth::Base (instance of Rodauth::Feature), # Rodauth::Auth, # ...] end Roda.rodauth # => Rodauth::Auth subclass Roda.rodauth.ancestors # => [Rodauth::Auth subclass, # Rodauth::Login (instance of Rodauth::Feature), # Rodauth::Base (instance of Rodauth::Feature), # Rodauth::Auth, # ...] Roda.route do |r| rodauth # => Rodauth::Auth subclass instance end ``` -------------------------------- ### Rodauth Feature Creation Example Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/internals.rdoc Demonstrates the internal process of defining a new Rodauth feature using Feature.define. ```ruby module Rodauth # Feature.define takes a symbol, specifying the name of the feature. This # is the same symbol you would pass to enable when loading the feature into # the Rodauth configuration. Feature is a module subclass, and Feature.define # is a class method that creates an instance of Feature (a module) and executes # the block in the context of the Feature instance. # # The second argument is optional, and sets the Feature instance and related # FeatureConfiguration instance to a constant in the Rodauth namespace, which # makes it easier to locate via inspect. Feature.define(:foo, :Foo) do ``` -------------------------------- ### Example i18n Translation File Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/i18n.rdoc A sample translation file structure for the i18n gem, demonstrating how to define translations for Rodauth-specific keys in English. ```yaml en: rodauth: login_notice_flash: "You have been signed in" require_login_error_flash: "Login is required for accessing this page" no_matching_login_message: "user with this email address doesn't exist" reset_password_email_subject: "Password Reset Instructions" ``` -------------------------------- ### JWT Feature Setup and Configuration Source: https://github.com/jeremyevans/rodauth/blob/master/doc/jwt.rdoc Explains how to set up and configure the JWT feature, including the required secret and options for handling JSON requests. ```APIDOC ## JWT Feature Setup ### Description The JWT feature adds support for JSON API access for all other features that ship with Rodauth, using JWT (JSON Web Tokens) to hold the session information. It depends on the json feature. ### Configuration To use this feature, you must set the `+jwt_secret+` configuration option with the secret used to cryptographically protect the token. ### Handling JSON API Requests When processing responses for requests to a Rodauth endpoint, check for the `Authorization` header. Use the value of the response `Authorization` header as the request `Authorization` header in future requests if the response `Authorization` header is set. If the response `Authorization` header is not set, continue to use the previous `Authorization` header. ### `json: :only` Option Consider using the `json: :only` option when loading the rodauth plugin if you want Rodauth to only handle JSON requests. If you don't use this option, the jwt feature might result in an error if a request to a Rodauth endpoint comes in with a `Content-Type` that isn't `application/json`, unless you also set `only_json? false` in your rodauth configuration. ``` -------------------------------- ### Run Migrations for a Specific User Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc This example shows how to run Sequel migrations for a specific database user, useful for managing separate migration contexts. ```ruby Sequel.extension :migration Sequel.postgres('DATABASE_NAME', user: 'PASSWORD_USER_NAME') do |db| Sequel::Migrator.run(db, 'path/to/password_user/migrations', table: 'schema_info_password') end ``` -------------------------------- ### Create PostgreSQL Database Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Creates a new PostgreSQL database and assigns ownership to the application's database account. This is a common setup for application databases. ```bash createdb -U postgres -O ${DATABASE_NAME} ${DATABASE_NAME} ``` -------------------------------- ### Rodauth Configuration with Prefix and Route Branch Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc This example configures Rodauth with a prefix and calls `r.rodauth` within a matching routing tree branch for specific paths like '/auth'. ```ruby plugin :rodauth do enable :login, :logout prefix "/auth" end route do |r| r.on "auth" do r.rodauth end rodauth.require_authentication # ... end ``` -------------------------------- ### OTP API Source: https://github.com/jeremyevans/rodauth/blob/master/doc/internal_request.rdoc APIs for One-Time Password (OTP) setup and management. ```APIDOC ## otp_setup_params (requires account) ### Description Retrieves parameters required for OTP setup. Returns a hash containing OTP secret and potentially raw secret if `hmac_secret` is configured. ### Method POST ### Endpoint /otp_setup_params ### Parameters #### Query Parameters - **account_id** (integer) - Required - The ID of the account. ### Response #### Success Response (200) - **otp_setup** (string) - The OTP secret. - **otp_setup_raw** (string) - The raw OTP secret (if applicable). ### Response Example { "otp_setup": "JBSWY3DPEHPK3PXP", "otp_setup_raw": "secret_key_123" } ``` ```APIDOC ## otp_setup (requires account) ### Description Enables OTP multifactor authentication for the account. ### Method POST ### Endpoint /otp_setup ### Parameters #### Query Parameters - **account_id** (integer) - Required - The ID of the account. - **otp_setup** (string) - Required - The OTP secret obtained from `otp_setup_params`. ### Response #### Success Response (200) - **success** (boolean) - True if OTP setup was successful. ### Response Example { "success": true } ``` -------------------------------- ### Enforcing Authentication in Roda Route Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc This example demonstrates how to force all users to log in by calling `rodauth.require_authentication` after `r.rodauth`. ```ruby route do |r| r.rodauth rodauth.require_authentication # ... end ``` -------------------------------- ### WebAuthn Feature Enhancements Source: https://github.com/jeremyevans/rodauth/blob/master/doc/release_notes/2.31.0.txt Details on new methods and configurations for the WebAuthn feature, including setup, authentication, and removal. ```APIDOC ## WebAuthn Feature Methods ### Description These methods are available when the `webauthn` feature is enabled. ### Methods - `webauthn_setup_params` - `webauthn_setup` - `webauthn_auth_params` - `webauthn_auth` - `webauthn_remove ## WebAuthn Login Feature Methods ### Description These methods are available when the `webauthn_login` feature is enabled. ### Methods - `webauthn_login_params` - `webauthn_login ### Configuration Methods - `webauthn_login_user_verification_additional_factor?` - Description: Configures whether user verification by WebAuthn should be treated as a second factor. Defaults to `false`. - `webauthn_invalid_webauthn_id_message` - Description: Customizes the error message for invalid WebAuthn IDs. ``` -------------------------------- ### Configure Multiple Rodauth Configurations Source: https://github.com/jeremyevans/rodauth/blob/master/doc/release_notes/2.37.0.txt Use `default_rodauth_name` to specify which Rodauth configuration to use within a route block. This simplifies installations with multiple Rodauth configurations by centralizing the logic for selecting a configuration. ```ruby attr_reader :default_rodauth_name route do |r| r.on 'secondary' do @default_rodauth_name = :secondary r.rodauth # will use the :secondary configuration end r.rodauth # will use the default configuration end ``` -------------------------------- ### Using Rodauth as a Library Source: https://github.com/jeremyevans/rodauth/blob/master/doc/release_notes/2.16.0.txt Demonstrates how to use Rodauth as a library in non-web applications by initializing Rodauth.lib and calling its methods. Requires the 'rodauth' gem. ```ruby require 'rodauth' rodauth = Rodauth.lib do enable :create_account, :change_password end rodauth.create_account(login: 'foo@example.com', password: '...') rodauth.change_password(account_id: 24601, password: '...') ``` -------------------------------- ### Create Application Database Account (PostgreSQL) Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Creates a new PostgreSQL database user account for the application. This account will typically own the database and its tables. ```bash createuser -U postgres ${DATABASE_NAME} ``` -------------------------------- ### Configuring Email Parameters Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/internals.rdoc Sets up email subject, body rendering using a template, email message creation, and sending. ```ruby email :foo, 'Foo Subject' ``` -------------------------------- ### Pass Query Parameters to Create Account Path Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/query_params.rdoc Use the `create_account_path` method to generate a URL for account creation, including additional query parameters. ```ruby rodauth.create_account_path(type: "seller") #=> "/create-account?type=seller" ``` -------------------------------- ### Configure Rodauth accounts_table Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Sets the database table used for accounts. This example shows overriding the default `accounts_table` method with a specific table name. ```ruby plugin :rodauth do enable :login, :logout accounts_table :users end ``` -------------------------------- ### Configure Rodauth with Instance Variables Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Demonstrates how to configure Rodauth to use specific instance variables within its callbacks, ensuring shape-friendliness. ```ruby plugin :rodauth do enable :login uses_instance_variables(:@some_iv) before_login do @some_iv = 1 super() end after_login do super() set_session_value(:something, @some_iv) end end ``` -------------------------------- ### Configure Rodauth with i18n Gem Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/i18n.rdoc Integrate the i18n gem with Rodauth to enable translations for user-facing text. This setup requires enabling specific Rodauth features. ```ruby plugin :rodauth do enable :login, :logout, :reset_password translate do |key, default| I18n.translate("rodauth." key)) || default end end ``` -------------------------------- ### Create MySQL Database Users and Grant Privileges Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Set up MySQL users for Rodauth, granting necessary privileges including the ability to grant permissions to other accounts. ```sql CREATE USER '${DATABASE_NAME}'@'localhost' IDENTIFIED BY '${PASSWORD}'; CREATE USER '${DATABASE_NAME}_password'@'localhost' IDENTIFIED BY '${OTHER_PASSWORD}'; GRANT ALL ON ${DATABASE_NAME}.* TO '${DATABASE_NAME}_password'@'localhost' WITH GRANT OPTION; ``` -------------------------------- ### Rodauth after_login Hook Example Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Adds custom logging to the `after_login` hook. This snippet demonstrates how to execute code after a user successfully logs in, logging their email. ```ruby plugin :rodauth do enable :login, :logout after_login do LOGGER.info "#{account[:email]} logged in!" end end ``` -------------------------------- ### Create Account for Tests with Minimum Cost Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/create_account_programmatically.rdoc When creating accounts in tests, use the `:cost` option with `BCrypt::Engine::MIN_COST` to significantly speed up test execution. This is crucial for avoiding slow tests. ```ruby account_id = DB[:accounts].insert( email: "name@example.com", status_id: 2, # verified ) DB[:account_password_hashes].insert( id: account_id, password_hash: BCrypt::Password.create("secret", cost: BCrypt::Engine::MIN_COST).to_s, ) ``` -------------------------------- ### Configure Internal Request Login Minimum Length Source: https://github.com/jeremyevans/rodauth/blob/master/doc/internal_request.rdoc Example of configuring Rodauth to use a different login minimum length for internal requests compared to normal requests. ```ruby plugin :rodauth do enable :create_account, :internal_request login_minimum_length 15 internal_request_configuration do login_minimum_length 3 end end ``` -------------------------------- ### Generate Absolute Authentication URLs with Rodauth Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/links.rdoc Use *_url methods on the Rodauth instance to get absolute URLs for authentication actions. This is useful for external links or emails. ```erb Sign in Sign up ``` -------------------------------- ### Render Account Created View Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/render_confirmation.rdoc After an account is created, render the "account_created" view with a specific page title. This is useful for guiding users to verify their account. ```ruby after_create_account do # render "account_created" view template with page title of "Account created!" return_response view("account_created", "Account created!") end ``` -------------------------------- ### Create SQL Server Logins and Database Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Create SQL Server logins for Rodauth and its password hash user, create the database, and set the password hash user as the database owner. ```sql CREATE LOGIN rodauth_test WITH PASSWORD = 'rodauth_test'; CREATE LOGIN rodauth_test_password WITH PASSWORD = 'rodauth_test'; CREATE DATABASE rodauth_test; USE rodauth_test; CREATE USER rodauth_test FOR LOGIN rodauth_test; GRANT CONNECT, EXECUTE TO rodauth_test; EXECUTE sp_changedbowner 'rodauth_test_password'; ``` -------------------------------- ### Create Account Password Hashes Table and Functions Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc This migration creates the `account_password_hashes` table and associated authentication functions. It includes database-specific permission grants for PostgreSQL, MySQL, and Microsoft SQL Server. ```ruby require 'rodauth/migrations' Sequel.migration do up do create_table(:account_password_hashes) do foreign_key :id, :accounts, primary_key: true, type: :Bignum String :password_hash, null: false end Rodauth.create_database_authentication_functions(self) case database_type when :postgres user = get(Sequel.lit('current_user')).sub(/_password\z/, '') run "REVOKE ALL ON account_password_hashes FROM public" run "REVOKE ALL ON FUNCTION rodauth_get_salt(int8) FROM public" run "REVOKE ALL ON FUNCTION rodauth_valid_password_hash(int8, text) FROM public" run "GRANT INSERT, UPDATE, DELETE ON account_password_hashes TO #{user}" run "GRANT SELECT(id) ON account_password_hashes TO #{user}" run "GRANT EXECUTE ON FUNCTION rodauth_get_salt(int8) TO #{user}" run "GRANT EXECUTE ON FUNCTION rodauth_valid_password_hash(int8, text) TO #{user}" when :mysql user = get(Sequel.lit('current_user')).sub(/_password@/, '@') db_name = get(Sequel.function(:database)) run "GRANT EXECUTE ON #{db_name}.* TO #{user}" run "GRANT INSERT, UPDATE, DELETE ON account_password_hashes TO #{user}" run "GRANT SELECT (id) ON account_password_hashes TO #{user}" when :mssql user = get(Sequel.function(:DB_NAME)) run "GRANT EXECUTE ON rodauth_get_salt TO #{user}" run "GRANT EXECUTE ON rodauth_valid_password_hash TO #{user}" run "GRANT INSERT, UPDATE, DELETE ON account_password_hashes TO #{user}" run "GRANT SELECT ON account_password_hashes(id) TO #{user}" end # Used by the disallow_password_reuse feature create_table(:account_previous_password_hashes) do primary_key :id, type: :Bignum foreign_key :account_id, :accounts, type: :Bignum String :password_hash, null: false end Rodauth.create_database_previous_password_check_functions(self) case database_type when :postgres user = get(Sequel.lit('current_user')).sub(/_password\z/, '') run "REVOKE ALL ON account_previous_password_hashes FROM public" run "REVOKE ALL ON FUNCTION rodauth_get_previous_salt(int8) FROM public" run "REVOKE ALL ON FUNCTION rodauth_previous_password_hash_match(int8, text) FROM public" run "GRANT INSERT, UPDATE, DELETE ON account_previous_password_hashes TO #{user}" run "GRANT SELECT(id, account_id) ON account_previous_password_hashes TO #{user}" run "GRANT USAGE ON account_previous_password_hashes_id_seq TO #{user}" run "GRANT EXECUTE ON FUNCTION rodauth_get_previous_salt(int8) TO #{user}" run "GRANT EXECUTE ON FUNCTION rodauth_previous_password_hash_match(int8, text) TO #{user}" when :mysql user = get(Sequel.lit('current_user')).sub(/_password@/, '@') db_name = get(Sequel.function(:database)) run "GRANT EXECUTE ON #{db_name}.* TO #{user}" run "GRANT INSERT, UPDATE, DELETE ON account_previous_password_hashes TO #{user}" run "GRANT SELECT (id, account_id) ON account_previous_password_hashes TO #{user}" when :mssql user = get(Sequel.function(:DB_NAME)) run "GRANT EXECUTE ON rodauth_get_previous_salt TO #{user}" run "GRANT EXECUTE ON rodauth_previous_password_hash_match TO #{user}" run "GRANT INSERT, UPDATE, DELETE ON account_previous_password_hashes TO #{user}" run "GRANT SELECT ON account_previous_password_hashes(id, account_id) TO #{user}" end end down do Rodauth.drop_database_previous_password_check_functions(self) Rodauth.drop_database_authentication_functions(self) drop_table(:account_previous_password_hashes, :account_password_hashes) end end ``` -------------------------------- ### Generate Relative Authentication URLs with Rodauth Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/links.rdoc Use *_path methods on the Rodauth instance to get relative URLs for authentication actions. This is useful for internal links within your application. ```erb Sign in Sign up ``` -------------------------------- ### Configure Rodauth for MFA Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/require_mfa.rdoc Enable login, logout, and OTP features. Optionally disable the error flash for MFA redirects and set the MFA notice flash to match the login notice flash. ```ruby plugin :rodauth do enable :login, :logout, :otp # If you don't want to show an error message when redirecting # to the multifactor authentication page. two_factor_need_authentication_error_flash nil # Display the same flash message after multifactor # authentication than is displayed after login two_factor_auth_notice_flash { login_notice_flash } end ``` -------------------------------- ### Grant Schema Rights on PostgreSQL 15+ Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Temporarily grant CREATE privilege on the public schema to the specified user for Rodauth setup on PostgreSQL 15 and later. This privilege is revoked after migration. ```bash psql -U postgres -c "GRANT CREATE ON SCHEMA public TO ${DATABASE_NAME}_password" ${DATABASE_NAME} ``` -------------------------------- ### Set Up Separate Schemas in PostgreSQL Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Configure separate schemas for Rodauth users in PostgreSQL by dropping the public schema and creating new ones, then granting necessary usage privileges. ```bash psql -U postgres -c "DROP SCHEMA public;" ${DATABASE_NAME} ``` ```bash psql -U postgres -c "CREATE SCHEMA AUTHORIZATION ${DATABASE_NAME};" ${DATABASE_NAME} ``` ```bash psql -U postgres -c "CREATE SCHEMA AUTHORIZATION ${DATABASE_NAME}_password;" ${DATABASE_NAME} ``` ```bash psql -U postgres -c "GRANT USAGE ON SCHEMA ${DATABASE_NAME} TO ${DATABASE_NAME}_password;" ${DATABASE_NAME} ``` ```bash psql -U postgres -c "GRANT USAGE ON SCHEMA ${DATABASE_NAME}_password TO ${DATABASE_NAME};" ${DATABASE_NAME} ``` -------------------------------- ### Override Rodauth Redirect Destinations Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/redirects.rdoc Change the redirect destination for Rodauth actions by overriding the corresponding `*_redirect` method. For example, `login_redirect` can be set to a specific path or a block that returns a path. ```ruby plugin :rodauth do enable :login, :logout, :create_account, :reset_password # Redirect to "/dashboard" after login login_redirect "/dashboard" # Redirect to wherever login redirects to after creating account create_account_redirect { login_redirect } # Redirect to login page after password reset reset_password_redirect { login_path } end ``` -------------------------------- ### Utility and Configuration Methods Source: https://github.com/jeremyevans/rodauth/blob/master/doc/base.rdoc Miscellaneous methods for redirection, error handling, translation, and configuration. ```APIDOC ## Utility and Configuration Methods ### Description Miscellaneous methods for redirection, error handling, translation, and configuration. ### Methods - **use_template_fixed_locals?**: Whether to specify fixed locals for rodauth templates. True by default, should only be set to false if overriding the templates and having them accept different local variables. - **function_name(name)**: The name of the database function to call. It's passed either :rodauth_get_salt or :rodauth_valid_password_hash. - **open_account?**: Whether the current account is an open account (not closed or unverified). - **redirect(path)**: Redirect the request to the given path. - **session_value**: The value for session_key in the current session. - **set_error_flash(message)**: Set the current error flash to the given message. - **set_error_reason(reason)**: You can override this method to customize handling of specific error types (does nothing by default). Each separate error type has a separate reason symbol, you can see the {list of error reason symbols}[rdoc-ref:doc/error_reasons.rdoc]. - **set_notice_flash(message)**: Set the next notice flash to the given message. - **set_notice_now_flash(message)**: Set the current notice flash to the given message. - **set_redirect_error_flash(message)**: Set the next error flash to the given message. - **set_title(title)**: Set the title of the page to the given title. - **translate(key, default_value)**: Return a translated version for the key (uses the default value by default). - **unverified_account_message**: The message to use when attempting to login to an unverified account. ``` -------------------------------- ### Configure Deadline Values for Tokens Source: https://github.com/jeremyevans/rodauth/blob/master/doc/release_notes/1.0.0.txt Configure deadline values for tokens using set_deadline_values? and *_interval methods. This requires Sequel's date_arithmetic extension to be loaded. ```ruby set_deadline_values? true account_lockouts_deadline_interval :days=>2 remember_deadline_interval :days=>60 reset_password_deadline_interval :days=>7 ``` -------------------------------- ### Login Account with Password Source: https://github.com/jeremyevans/rodauth/blob/master/doc/login.rdoc Logs in the current account using the provided password. Assumes the account is already loaded. ```ruby rodauth.account #=> { id: 123, ... } rodauth.login('password') # login the current account ``` -------------------------------- ### Implement Custom Password Complexity Check Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/password_requirements.rdoc Use the `password_meets_requirements?` method to define custom password complexity rules. This example requires passwords to contain at least one number and one special character. ```ruby plugin :rodauth do enable :login, :logout, :create_account password_meets_requirements? do |password| super(password) && password_complex_enough?(password) end auth_class_eval do # If password doesn't pass custom validation, add field error with error # reason, and return false. def password_complex_enough?(password) return true if password.match?(/\d/) && password.match?(/[^a-zA-Z\d])/) set_password_requirement_error_message(:password_simple, "requires one number and one special character") false end end end ``` -------------------------------- ### Handle Password Setting with Grace Period and Remember Login Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/delay_password.rdoc When using `verify_account_grace_period` and `remember` features, set `verify_account_set_password` to true and use `after_create_account` to call `remember_login`. This ensures users can log in during the grace period and their login is remembered. ```ruby plugin :rodauth do enable :login, :logout, :verify_account_grace_period, :remember verify_account_set_password? true after_create_account do remember_login end end ``` -------------------------------- ### Lockout Feature Overview Source: https://github.com/jeremyevans/rodauth/blob/master/doc/lockout.rdoc The lockout feature implements bruteforce protection for accounts. It depends on the login feature. If a user fails to login due to a password error more than a given number of times, their account gets locked out, and they are given an option to request an account unlock via an email sent to them. ```APIDOC ## Lockout Feature ### Description Implements bruteforce protection for accounts by locking them out after a specified number of failed login attempts. Users can then request an account unlock via email. ### Dependencies - Login feature ``` -------------------------------- ### Customize Login Confirmation Comparison Source: https://github.com/jeremyevans/rodauth/blob/master/doc/release_notes/2.37.0.txt The `login_confirmation_matches?` configuration method allows customization of the login confirmation comparison. This can be used to maintain case-sensitive comparisons if desired, as the default is now case-insensitive. ```ruby login_confirmation_matches? ``` -------------------------------- ### Create Account API Source: https://github.com/jeremyevans/rodauth/blob/master/doc/internal_request.rdoc API for creating a new user account. ```APIDOC ## create_account ### Description Creates a new user account. ### Method POST ### Endpoint /create_account ### Parameters #### Query Parameters - **login** (string) - Required - The login for the new account. - **password** (string) - Optional - The password for the new account. ### Response #### Success Response (200) - **account_id** (integer) - The ID of the newly created account. ### Response Example { "account_id": 124 } ``` -------------------------------- ### Enable 2FA with Backup Options Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Enables login, logout, OTP, recovery codes, and SMS codes as 2FA options, treating SMS and recovery codes as backup methods by default. ```ruby plugin :rodauth do enable :login, :logout, :otp, :recovery_codes, :sms_codes end route do |r| r.rodauth rodauth.require_authentication # ... end ``` -------------------------------- ### Create Account Feature Configuration Source: https://github.com/jeremyevans/rodauth/blob/master/doc/create_account.rdoc Configuration options for customizing the create account feature. ```APIDOC ## Create Account Feature Configuration This section details the configuration options available for the create account feature. ### Auth Value Methods These methods allow customization of various aspects of the create account form and process. - `create_account_additional_form_tags`: HTML fragment for additional form tags. - `create_account_button`: Text for the create account button. - `create_account_error_flash`: Flash error message for unsuccessful creation. - `create_account_notice_flash`: Flash notice message for successful creation. - `create_account_page_title`: Page title for the create account form. - `create_account_redirect`: URL to redirect to after account creation. - `create_account_route`: The route for the create account action (defaults to `create-account`). - `create_account_set_password?`: Boolean, whether to prompt for a password during account creation. Defaults to true if accounts are not verified. If false, an alternative password setting method is required. ### Auth Methods These methods define the behavior and logic of the create account process. - `after_create_account`: Hook to run custom code after an account is created. - `before_create_account`: Hook to run custom code before an account is created. - `before_create_account_route`: Hook to run custom code before the create account route is handled. - `create_account_autologin?`: Boolean, whether to automatically log in the user after successful creation. Defaults to true unless accounts require verification. - `create_account_link_text`: Text for the link to the create account form. - `create_account_response`: Custom response after successful account creation. Defaults to redirecting to `create_account_redirect`. - `create_account_view`: The HTML content for the create account form. - `new_account(login)`: Instantiates a new account hash for a given login without saving it. - `save_account`: Inserts the account into the database. Returns nil/false on failure. - `set_new_account_password`: Sets the password for a new account if `account_password_hash_column` is set, without saving. ``` -------------------------------- ### Create Account Password Hashes Table (PostgreSQL) Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Define the 'account_password_hashes' table using Sequel, specifying foreign key constraints and associating it with database authentication functions for a specific schema. ```ruby create_table(:account_password_hashes) do foreign_key :id, Sequel[:'${DATABASE_NAME}'][:accounts], primary_key: true, type: :Bignum String :password_hash, null: false end Rodauth.create_database_authentication_functions(self, table_name: Sequel[:'${DATABASE_NAME}_password'][:account_password_hashes]) ``` -------------------------------- ### Load Rodauth Plugin Basic Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Loads the Rodauth plugin into a Roda application. This is the initial step for integrating Rodauth. ```ruby plugin :rodauth do end ``` -------------------------------- ### Verify Login Change Configuration Options Source: https://github.com/jeremyevans/rodauth/blob/master/doc/verify_login_change.rdoc Configuration options for customizing the verify login change feature. ```APIDOC ## Verify Login Change Configuration Options This section details the configuration options available for the verify login change feature. ### Configuration Options - **no_matching_verify_login_change_key_error_flash** (string) - The flash error message to show when an invalid verify login change key is used. - **change_login_needs_verification_notice_flash** (string) - The flash notice to show after changing a login when using this feature, if `change_login_notice_flash` is not overridden. - **verify_login_change_additional_form_tags** (string) - HTML fragment containing additional form tags to use on the verify login change form. - **verify_login_change_autologin?** (boolean) - Whether to autologin the user after successful login change verification, false by default. - **verify_login_change_button** (string) - The text to use for the verify login change button. - **verify_login_change_deadline_column** (string) - The column name in the `verify_login_change_table` storing the deadline after which the token will be ignored. - **verify_login_change_deadline_interval** (string) - The amount of time for which to allow users to verify login changes, 1 day by default. - **verify_login_change_duplicate_account_error_flash** (string) - The flash error message to show when attempting to verify a login change when the login is already taken. - **verify_login_change_duplicate_account_redirect** (string) - Where to redirect if not changing a login during verification because the new login is already taken. - **verify_login_change_email_subject** (string) - The subject to use for the verify login change email. - **verify_login_change_error_flash** (string) - The flash error to show if no matching key is submitted when verifying login change. - **verify_login_change_id_column** (string) - The id column in the `verify_login_change_table`, should be a foreign key referencing the accounts table. - **verify_login_change_key_column** (string) - The verify login change key/token column in the `verify_login_change_table`. - **verify_login_change_key_param** (string) - The parameter name to use for the verify login change key. - **verify_login_change_login_column** (string) - The login column in the `verify_login_change_table`, containing the new login. - **verify_login_change_notice_flash** (string) - The flash notice to show after verifying the login change. - **verify_login_change_page_title** (string) - The page title to use on the verify login change form. - **verify_login_change_redirect** (string) - Where to redirect after verifying the login change. - **verify_login_change_route** (string) - The route to the verify login change action. Defaults to `verify-login-change`. - **verify_login_change_session_key** (string) - The key in the session to hold the verify login change key temporarily. - **verify_login_change_table** (string) - The name of the verify login change keys table. ``` -------------------------------- ### Token and Parameter Handling Source: https://github.com/jeremyevans/rodauth/blob/master/doc/base.rdoc Methods for handling token conversion, normalization, and parameter validation. ```APIDOC ## Token and Parameter Handling ### Description Methods for handling token conversion, normalization, and parameter validation. ### Methods - **convert_token_id(id)**: Convert the token id string to an appropriate object to use for the token id (or return +nil+ to signal an invalid token id). By default, converts to a 64-bit signed integer if +convert_token_id_to_integer?+ is true. - **normalize_login(login)**: How to normalize the submitted login parameter value, returns the argument by default. - **null_byte_parameter_value(key, value)**: The value to use for the parameter if the parameter includes an ASCII NUL byte ("\0"), nil by default to ignore the parameter. - **over_max_bytesize_param_value(key, value)**: The value to use for the parameter if the parameter is over the maximum allowed bytesize, nil by default to ignore the parameter. - **password_match?(password)**: Check whether the given password matches the stored password hash. - **random_key**: A randomly generated string, used for creating tokens. ``` -------------------------------- ### Defining Before Action Hook Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/internals.rdoc Sets up a callback method that will be executed before the primary action of the feature. ```ruby before ``` -------------------------------- ### Configure Verify Account Password Setting Source: https://github.com/jeremyevans/rodauth/blob/master/doc/release_notes/1.15.0.txt Set `verify_account_set_password?` to true to require the password to be set on the verify account form instead of the create account form. This enhances security by ensuring only the email recipient can set the account password. ```ruby verify_account_set_password? true ``` -------------------------------- ### possible_authentication_methods Source: https://github.com/jeremyevans/rodauth/blob/master/README.rdoc Returns an array of strings listing the possible authentication types that can be used for the account. ```APIDOC ## possible_authentication_methods ### Description An array of strings for possible authentication types that can be used for the account. ### Method (Not specified, typically called within a Roda route block) ### Endpoint (Not applicable, method call within application logic) ### Parameters None ### Response #### Success Response - **array of strings** - List of possible authentication methods. ``` -------------------------------- ### Enable Password Setting on Account Verification Source: https://github.com/jeremyevans/rodauth/blob/master/doc/guides/delay_password.rdoc Enable the login, logout, and verify account features. Set `verify_account_set_password` to true to prompt users to set their password when they verify their account. This is the default behavior when the verify account feature is loaded. ```ruby plugin :rodauth do enable :login, :logout, :verify_account verify_account_set_password? true end ``` -------------------------------- ### WebAuthn Configuration Options Source: https://github.com/jeremyevans/rodauth/blob/master/doc/webauthn.rdoc Configuration options for customizing WebAuthn behavior, including routes, page titles, flash messages, and parameter names. ```APIDOC ## WebAuthn Configuration Options ### Description Configuration options for customizing WebAuthn behavior, including routes, page titles, flash messages, and parameter names. ### Parameters #### Query Parameters - **webauthn_remove_notice_flash** (string) - The flash notice to show after removing an existing WebAuthn authenticator. - **webauthn_remove_page_title** (string) - The page title to use on the page for removing an existing WebAuthn authenticator. - **webauthn_remove_param** (string) - The parameter name for the WebAuthn ID to remove. - **webauthn_remove_redirect** (string) - Where to redirect after successfully removing an existing WebAuthn authenticator. - **webauthn_remove_route** (string) - The route to the webauthn remove action. - **webauthn_rp_id** (string) - The relying party ID to use when registering a WebAuthn authenticator or authenticating via WebAuthn. - **webauthn_rp_name** (string) - The relying party name to use when registering a WebAuthn authenticator. - **webauthn_setup_additional_form_tags** (string) - HTML fragment containing additional form tags when registering a new WebAuthn authenticator. - **webauthn_setup_button** (string) - Text to use for button on the form to register a new WebAuthn authenticator. - **webauthn_setup_challenge_hmac_param** (string) - The parameter name for the HMAC of the WebAuthn challenge during registration. - **webauthn_setup_challenge_param** (string) - The parameter name for the WebAuthn challenge during registration. - **webauthn_setup_error_flash** (string) - The flash error to show if unable to register a new WebAuthn authenticator. - **webauthn_setup_js** (string) - The javascript code to execute on the page to register a new WebAuthn credential. - **webauthn_setup_js_route** (string) - The route to the webauthn setup javascript file. - **webauthn_setup_link_text** (string) - The text to use for the setup link from the multifactor manage page. - **webauthn_setup_notice_flash** (string) - The flash notice to show after registering a new WebAuthn authenticator. - **webauthn_setup_page_title** (string) - The page title to use on the page for registering a new WebAuthn authenticator. - **webauthn_setup_param** (string) - The parameter name for the WebAuthn registration data. - **webauthn_setup_redirect** (string) - Where to redirect after successfully registering a new WebAuthn authenticator. - **webauthn_setup_timeout** (string) - The number of milliseconds to wait when registering a new WebAuthn authenticator. - **webauthn_setup_route** (string) - The route to the webauthn setup action. - **webauthn_user_ids_account_id_column** (string) - The column in the +webauthn_user_ids_table+ containing the account id. - **webauthn_user_ids_table** (string) - The table name containing the WebAuthn user IDs. - **webauthn_user_ids_webauthn_id_column** (string) - The column in the +webauthn_user_ids_table+ containing the accounts WebAuthn user ID. - **webauthn_user_verification** (string) - The value of the WebAuthn userVerification option when registering a new WebAuthn authenticator. ```