Git Product home page Git Product logo

rodauth-model's Introduction

rodauth-model

Extension for Rodauth providing a mixin for the account model that defines password attribute and associations based on enabled authentication features. Supports both Active Record and Sequel models.

Installation

$ bundle add rodauth-model

Usage

The model mixin is built by calling Rodauth::Model(...) with the Rodauth auth class, and included into the account model:

require "rodauth/model" # require before enabling any authentication features

class RodauthApp < Roda
  plugin :rodauth do
    # ...
  end
end
class Account < ActiveRecord::Base # Sequel::Model
  include Rodauth::Model(RodauthApp.rodauth)
end

Password attribute

Regardless of whether you're storing the password hash in a column in the accounts table, or in a separate table, the #password attribute can be used to set or clear the password hash.

account = Account.create(email: "[email protected]", password: "secret")

# when password hash is stored in a column on the accounts table
account.password_hash #=> "$2a$12$k/Ub1I2iomi84RacqY89Hu4.M0vK7klRnRtzorDyvOkVI.hKhkNw."

# when password hash is stored in a separate table
account.password_hash #=> #<Account::PasswordHash...> (record from `account_password_hashes` table)
account.password_hash.password_hash #=> "$2a$12$k/Ub1..." (inaccessible when using database authentication functions)

account.password = nil # clears password hash
account.password_hash #=> nil

Note that the password attribute doesn't come with validations, making it unsuitable for forms. It was primarily intended to allow easily creating accounts in development console and in tests.

Associations

The mixin defines associations for Rodauth tables associated to the accounts table:

account.remember_key #=> #<Account::RememberKey> (record from `account_remember_keys` table)
account.active_session_keys #=> [#<Account::ActiveSessionKey>,...] (records from `account_active_session_keys` table)

You can also reference the associated models directly:

# model referencing the `account_authentication_audit_logs` table
Account::AuthenticationAuditLog.where(message: "login").group(:account_id)

The associated models define the inverse account association:

Account::ActiveSessionKey.eager(:account).map(&:account)

Association options

By default, all associations are configured to be deleted when the associated account record is deleted. When using Active Record, you can use :association_options to modify global or per-association options:

# don't auto-delete associations when account model is deleted (Active Record)
Rodauth::Model(RodauthApp.rodauth, association_options: { dependent: nil })

# require authentication audit logs to be eager loaded before retrieval (Sequel)
Rodauth::Model(RodauthApp.rodauth, association_options: -> (name) {
  { forbid_lazy_load: true } if name == :authentication_audit_logs
})

Association reference

Below is a list of all associations defined depending on the features loaded:

Feature Association Type Model Table (default)
account_expiration :activity_time has_one ActivityTime account_activity_times
active_sessions :active_session_keys has_many ActiveSessionKey account_active_session_keys
audit_logging :authentication_audit_logs has_many AuthenticationAuditLog account_authentication_audit_logs
disallow_password_reuse :previous_password_hashes has_many PreviousPasswordHash account_previous_password_hashes
email_auth :email_auth_key has_one EmailAuthKey account_email_auth_keys
jwt_refresh :jwt_refresh_keys has_many JwtRefreshKey account_jwt_refresh_keys
lockout :lockout has_one Lockout account_lockouts
lockout :login_failure has_one LoginFailure account_login_failures
otp :otp_key has_one OtpKey account_otp_keys
password_expiration :password_change_time has_one PasswordChangeTime account_password_change_times
recovery_codes :recovery_codes has_many RecoveryCode account_recovery_codes
remember :remember_key has_one RememberKey account_remember_keys
reset_password :password_reset_key has_one PasswordResetKey account_password_reset_keys
single_session :session_key has_one SessionKey account_session_keys
sms_codes :sms_code has_one SmsCode account_sms_codes
verify_account :verification_key has_one VerificationKey account_verification_keys
verify_login_change :login_change_key has_one LoginChangeKey account_login_change_keys
webauthn :webauthn_keys has_many WebauthnKey account_webauthn_keys
webauthn :webauthn_user_id has_one WebauthnUserId account_webauthn_user_ids

Note that some Rodauth tables use composite primary keys, which Active Record doesn't support out of the box. For associations to work properly in Active Record, you might need to add the composite_primary_keys gem to your Gemfile. On Sequel, associations will work without any changes, because Sequel supports composite primary keys.

Extending associations

It's possible to register custom associations for an external feature, which the model mixin would pick up and automatically define the association on the model if the feature is enabled.

# lib/rodauth/features/foo.rb
module Rodauth
  Feature.define(:foo, :Foo) do
    auth_value_method :foo_table, :account_foos
    auth_value_method :foo_id_column, :id
    # ...
  end
end

if defined?(Rodauth::Model)
  Rodauth::Model.register_association(:foo) do
    { name: :foo, type: :one, table: foo_table, key: foo_id_column }
  end
end

The Rodauth::Model.register_association method receives the feature name and a block, which is evaluted in the context of a Rodauth instance and should return the association definition with the following items:

  • :name – association name
  • :type – relationship type (:one for one-to-one, :many for one-to-many)
  • :table – associated table name
  • :key – foreign key on the associated table

It's possible to register multiple associations for the same Rodauth feature.

Examples

Checking whether account has multifactor authentication enabled

class Account < ActiveRecord::Base
  include Rodauth::Model(RodauthApp.rodauth)

  def mfa_enabled?
    otp_key || (sms_code && sms_code.num_failures.nil?) || recovery_codes.any?
  end
end

Retrieving all accounts with multifactor authentication enabled

class Account < ActiveRecord::Base
  include Rodauth::Model(RodauthApp.rodauth)

  scope :otp_setup, -> { where(otp_key: OtpKey.all) }
  scope :sms_codes_setup, -> { where(sms_code: SmsCode.where(num_failures: nil)) }
  scope :recovery_codes_setup, -> { where(recovery_codes: RecoveryCode.all) }
  scope :mfa_enabled, -> { merge(otp_setup.or(sms_codes_setup).or(recovery_codes_setup)) }
end

Future plans

Joined associations

It's possible to have multiple Rodauth configurations that operate on the same tables, but it's currently possible to define associations just for a single configuration. I would like to support grabbing associations from multiple associations.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/janko/rodauth-model. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Rodauth::Model project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

rodauth-model's People

Contributors

janko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

thedumbtechguy

rodauth-model's Issues

Custom model name?

Is it possible to use an alternative to Account, or perhaps a namespaced Account model, like MyApp::Account?

ActiveRecord::AssociationTypeMismatch on password assignment

I have started getting this error when assignining passwords to an account:

ActiveRecord::AssociationTypeMismatch: Authentication::Account::PasswordHash(#130740) expected, 
got "$2a$12$FZ4poi3KsWfFVbnLdkBYlubKzTJV3vAYenkbSstQfE7H7jCYjpKmC" 
which is an instance of BCrypt::Password(#130760) (ActiveRecord::AssociationTypeMismatch)

Context:

relevant /app/mist/rodauth_main.rb settings:

class RodauthMain < Rodauth::Rails::Auth
  configure do
    enable :create_account, :verify_account,
           :login, :logout, :remember,
           :reset_password, :change_password, :change_password_notify,
           :change_login, :verify_login_change, :close_account,
           :i18n

    accounts_table :authentication_accounts
    rails_account_model Authentication::Account
    account_password_hash_column :password_hash

The Authentication::Account class inherits Rodauth::Model thusly (and has for a year since I wrote this code). Relevant code:

class Authentication::Account < ApplicationRecord
  include Rodauth::Model(RodauthMain) unless ENV['ASSET_PRECOMPILE']
  validates :password, presence: true, password_complexity: true, if: :password_validation_required?, on: :update

Duplicating the error:

Loading development environment (Rails 7.1.2)
irb(main):001> account = Authentication::Account.new
=> #<Authentication::Account:0x0000000165a54ef0
 id: nil,
 status: "unverified",
 role: "user",
 email: nil,
 password_hash: nil,
 is_locked: false,
 party_id: nil,
 email_hash: nil,
 data: {"client_targets"=>[]},
 code_int: nil,
 discarded_at: nil,
 created_at: nil,
 updated_at: nil>
irb(main):002> account.password
=> nil
irb(main):003> account.password = 'MyBestPassword'
Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/associations/association.rb:313:in `raise_on_type_mismatch!': Authentication::Account::PasswordHash(#198460) expected, got "$2a$12$wJeBmJUvhbhX/OjW0UIxe.yN/nG/hQhiUXuhjJR9c0hmMym935zm2" which is an instance of BCrypt::Password(#198480) (ActiveRecord::AssociationTypeMismatch)

Backtrace:

Authentication::Account::PasswordHash(#130740) expected, got "$2a$12$d8j72Mh8039mZEhBr76/j.o80zYCEmoRnp4R34sQgzqme5WEaie4O" which is an instance of BCrypt::Password(#130760)
/Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/associations/association.rb:313:in `raise_on_type_mismatch!'
/Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/associations/has_one_association.rb:60:in `replace'
/Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/associations/singular_association.rb:19:in `writer'
/Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/associations/builder/association.rb:112:in `password_hash='
/Users/hmasing/gems/gems/rodauth-model-0.2.1/lib/rodauth/model/active_record.rb:25:in `public_send'
/Users/hmasing/gems/gems/rodauth-model-0.2.1/lib/rodauth/model/active_record.rb:25:in `block in define_methods'
/Users/hmasing/gems/gems/rodauth-model-0.2.1/lib/rodauth/model/active_record.rb:20:in `block in define_methods'
/Users/hmasing/gems/gems/activemodel-7.1.2/lib/active_model/attribute_assignment.rb:49:in `public_send'
/Users/hmasing/gems/gems/activemodel-7.1.2/lib/active_model/attribute_assignment.rb:49:in `_assign_attribute'
/Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/attribute_assignment.rb:19:in `block in _assign_attributes'
/Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/attribute_assignment.rb:11:in `each'
/Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/attribute_assignment.rb:11:in `_assign_attributes'
/Users/hmasing/gems/gems/activemodel-7.1.2/lib/active_model/attribute_assignment.rb:34:in `assign_attributes'
/Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/core.rb:432:in `initialize'
/Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/inheritance.rb:76:in `new'
/Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/inheritance.rb:76:in `new'
/Users/hmasing/Development/Hum/letshum-core/db/seeds.rb:148:in `<main>'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/engine.rb:556:in `load'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/engine.rb:556:in `block in load_seed'
/Users/hmasing/gems/gems/activesupport-7.1.2/lib/active_support/callbacks.rb:121:in `block in run_callbacks'
/Users/hmasing/gems/gems/activesupport-7.1.2/lib/active_support/execution_wrapper.rb:92:in `wrap'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/engine.rb:642:in `block (2 levels) in <class:Engine>'
/Users/hmasing/gems/gems/activesupport-7.1.2/lib/active_support/callbacks.rb:130:in `instance_exec'
/Users/hmasing/gems/gems/activesupport-7.1.2/lib/active_support/callbacks.rb:130:in `block in run_callbacks'
/Users/hmasing/gems/gems/activesupport-7.1.2/lib/active_support/callbacks.rb:141:in `run_callbacks'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/engine.rb:556:in `load_seed'
/Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/tasks/database_tasks.rb:468:in `load_seed'
/Users/hmasing/gems/gems/activerecord-7.1.2/lib/active_record/railties/databases.rake:405:in `block (2 levels) in <main>'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/task.rb:281:in `block in execute'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/task.rb:281:in `each'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/task.rb:281:in `execute'
/Users/hmasing/Development/Hum/letshum-core/lib/tasks/hum.rake:51:in `block (2 levels) in <main>'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/task.rb:281:in `block in execute'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/task.rb:281:in `each'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/task.rb:281:in `execute'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/task.rb:219:in `block in invoke_with_call_chain'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/task.rb:199:in `synchronize'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/task.rb:199:in `invoke_with_call_chain'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/task.rb:188:in `invoke'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/application.rb:182:in `invoke_task'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/application.rb:138:in `block (2 levels) in top_level'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/application.rb:138:in `each'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/application.rb:138:in `block in top_level'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/application.rb:147:in `run_with_threads'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/application.rb:132:in `top_level'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/commands/rake/rake_command.rb:27:in `block (2 levels) in perform'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/application.rb:208:in `standard_exception_handling'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/commands/rake/rake_command.rb:27:in `block in perform'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/commands/rake/rake_command.rb:44:in `block in with_rake'
/Users/hmasing/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib/rake/rake_module.rb:59:in `with_application'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/commands/rake/rake_command.rb:41:in `with_rake'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/commands/rake/rake_command.rb:20:in `perform'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/command.rb:156:in `invoke_rake'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/command.rb:73:in `block in invoke'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/command.rb:149:in `with_argv'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/command.rb:69:in `invoke'
/Users/hmasing/gems/gems/railties-7.1.2/lib/rails/commands.rb:18:in `<main>'
/Users/hmasing/gems/gems/bootsnap-1.17.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
/Users/hmasing/gems/gems/bootsnap-1.17.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'

Issue is consistent with Rails 7.0.2 and 7.1.2, and Ruby 3.2.1 and 3.3.0.

bcrypt 3.1.20 with native extensions

I have dug through my change logs and codebase, and cannot identify why this may be happening quite suddenly. This area of the stack hasn't changed in about 6 months, and it's been working fine.

I suspect somewhere around here?

define_method(:password=) do |password|

Fix already initialized constant Account::VerificationKey warning

Overview

Hello. 👋 I'm experiencing an issue where I'm seeing a bunch of warnings in my console (dev and test) when using Rodauth in my Rails app:

/Users/bkuhlmann/.cache/frum/versions/3.1.3/lib/ruby/gems/3.1.0/gems/rodauth-model-0.2.1/lib/rodauth/model/active_record.rb:69: warning: already initialized constant Account::VerificationKey
/Users/bkuhlmann/.cache/frum/versions/3.1.3/lib/ruby/gems/3.1.0/gems/rodauth-model-0.2.1/lib/rodauth/model/active_record.rb:69: warning: previous definition of VerificationKey was here
/Users/bkuhlmann/.cache/frum/versions/3.1.3/lib/ruby/gems/3.1.0/gems/rodauth-model-0.2.1/lib/rodauth/model/active_record.rb:69: warning: already initialized constant Account::RememberKey
/Users/bkuhlmann/.cache/frum/versions/3.1.3/lib/ruby/gems/3.1.0/gems/rodauth-model-0.2.1/lib/rodauth/model/active_record.rb:69: warning: previous definition of RememberKey was here
/Users/bkuhlmann/.cache/frum/versions/3.1.3/lib/ruby/gems/3.1.0/gems/rodauth-model-0.2.1/lib/rodauth/model/active_record.rb:69: warning: already initialized constant Account::PasswordResetKey
/Users/bkuhlmann/.cache/frum/versions/3.1.3/lib/ruby/gems/3.1.0/gems/rodauth-model-0.2.1/lib/rodauth/model/active_record.rb:69: warning: previous definition of PasswordResetKey was here
/Users/bkuhlmann/.cache/frum/versions/3.1.3/lib/ruby/gems/3.1.0/gems/rodauth-model-0.2.1/lib/rodauth/model/active_record.rb:69: warning: already initialized constant Account::LoginChangeKey
/Users/bkuhlmann/.cache/frum/versions/3.1.3/lib/ruby/gems/3.1.0/gems/rodauth-model-0.2.1/lib/rodauth/model/active_record.rb:69: warning: previous definition of LoginChangeKey was here

Steps to Recreate

I'm afraid I don't have a quick way to reproduce this for you in an isolated environment but can try to do that if it'd help. I mostly wanted to report this in case you weren't aware. As a workaround, I can use the excellent Warning gem to workaround these issues.

Environment

  • Ruby: ruby 3.1.3p185 (2022-11-24 revision 1a6b16756e) [arm64-darwin22.4.0]
  • Rails: 7.0.4
  • Rodauth: 2.29.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.