{"id":16747835,"url":"https://github.com/janko/rodauth-model","last_synced_at":"2025-04-09T20:13:04.411Z","repository":{"id":57677405,"uuid":"489765663","full_name":"janko/rodauth-model","owner":"janko","description":"Password attribute and associations for Rodauth account model","archived":false,"fork":false,"pushed_at":"2024-12-26T20:09:11.000Z","size":91,"stargazers_count":23,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-09T20:12:57.345Z","etag":null,"topics":["activerecord","rodauth","sequel"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/janko.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-05-07T19:36:16.000Z","updated_at":"2024-12-26T20:09:13.000Z","dependencies_parsed_at":"2024-10-27T11:52:23.602Z","dependency_job_id":"b0519192-c4b5-403a-abb6-5d85bde63d62","html_url":"https://github.com/janko/rodauth-model","commit_stats":{"total_commits":38,"total_committers":1,"mean_commits":38.0,"dds":0.0,"last_synced_commit":"7ca1c053d375175f3b0881af197d612ab981fae3"},"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/janko%2Frodauth-model","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/janko%2Frodauth-model/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/janko%2Frodauth-model/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/janko%2Frodauth-model/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/janko","download_url":"https://codeload.github.com/janko/rodauth-model/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248103872,"owners_count":21048245,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["activerecord","rodauth","sequel"],"created_at":"2024-10-13T02:11:02.641Z","updated_at":"2025-04-09T20:13:04.387Z","avatar_url":"https://github.com/janko.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# rodauth-model\n\nExtension 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.\n\n## Installation\n\n```sh\n$ bundle add rodauth-model\n```\n\n## Usage\n\nThe model mixin is built by calling `Rodauth::Model(...)` with the Rodauth auth class, and included into the account model:\n\n```rb\nrequire \"rodauth/model\" # require before enabling any authentication features\n\nclass RodauthApp \u003c Roda\n  plugin :rodauth do\n    # ...\n  end\nend\n```\n```rb\nclass Account \u003c ActiveRecord::Base # Sequel::Model\n  include Rodauth::Model(RodauthApp.rodauth)\nend\n```\n\n### Password attribute\n\nRegardless 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.\n\n```rb\naccount = Account.create(email: \"user@example.com\", password: \"secret\")\n\n# when password hash is stored in a column on the accounts table\naccount.password_hash #=\u003e \"$2a$12$k/Ub1I2iomi84RacqY89Hu4.M0vK7klRnRtzorDyvOkVI.hKhkNw.\"\n\n# when password hash is stored in a separate table\naccount.password_hash #=\u003e #\u003cAccount::PasswordHash...\u003e (record from `account_password_hashes` table)\naccount.password_hash.password_hash #=\u003e \"$2a$12$k/Ub1...\" (inaccessible when using database authentication functions)\n\n# whether a password is set\naccount.password? #=\u003e true\n\naccount.password = nil # clears password hash\naccount.password_hash #=\u003e nil\naccount.password? #=\u003e false\n```\n\nNote 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.\n\n### Associations\n\nThe mixin defines associations for Rodauth tables associated to the accounts table:\n\n```rb\naccount.remember_key #=\u003e #\u003cAccount::RememberKey\u003e (record from `account_remember_keys` table)\naccount.active_session_keys #=\u003e [#\u003cAccount::ActiveSessionKey\u003e,...] (records from `account_active_session_keys` table)\n```\n\nYou can also reference the associated models directly:\n\n```rb\n# model referencing the `account_authentication_audit_logs` table\nAccount::AuthenticationAuditLog.where(message: \"login\").group(:account_id)\n```\n\nThe associated models define the inverse `account` association:\n\n```rb\nAccount::ActiveSessionKey.eager(:account).map(\u0026:account)\n```\n\n### Association options\n\nBy 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:\n\n```rb\n# don't auto-delete associations when account model is deleted (Active Record)\nRodauth::Model(RodauthApp.rodauth, association_options: { dependent: nil })\n\n# require authentication audit logs to be eager loaded before retrieval (Sequel)\nRodauth::Model(RodauthApp.rodauth, association_options: -\u003e (name) {\n  { forbid_lazy_load: true } if name == :authentication_audit_logs\n})\n```\n\n### Extending models\n\nWhen using Zeitwerk autoloading, extending an associated model in a separate file won't work, because Zeitwerk has no reason to load it, since the constant was already defined. You can work around this by extending the model in the parent file:\n\n```rb\nclass Account \u003c ActiveRecord::Base\n  include Rodauth::Model(RodauthApp.rodauth) # defines associated models\n\n  class ActiveSessionKey \u003c ActiveRecord::Base\n    # extend the model\n  end\nend\n```\n\n## Association reference\n\nBelow is a list of all associations defined depending on the features loaded:\n\n| Feature                 | Association                  | Type       | Model                    | Table (default)                     |\n| :------                 | :----------                  | :---       | :----                    | :----                               |\n| account_expiration      | `:activity_time`             | `has_one`  | `ActivityTime`           | `account_activity_times`            |\n| active_sessions         | `:active_session_keys`       | `has_many` | `ActiveSessionKey`       | `account_active_session_keys`       |\n| audit_logging           | `:authentication_audit_logs` | `has_many` | `AuthenticationAuditLog` | `account_authentication_audit_logs` |\n| disallow_password_reuse | `:previous_password_hashes`  | `has_many` | `PreviousPasswordHash`   | `account_previous_password_hashes`  |\n| email_auth              | `:email_auth_key`            | `has_one`  | `EmailAuthKey`           | `account_email_auth_keys`           |\n| jwt_refresh             | `:jwt_refresh_keys`          | `has_many` | `JwtRefreshKey`          | `account_jwt_refresh_keys`          |\n| lockout                 | `:lockout`                   | `has_one`  | `Lockout`                | `account_lockouts`                  |\n| lockout                 | `:login_failure`             | `has_one`  | `LoginFailure`           | `account_login_failures`            |\n| otp                     | `:otp_key`                   | `has_one`  | `OtpKey`                 | `account_otp_keys`                  |\n| otp_unlock              | `:otp_unlock`                | `has_one`  | `OtpUnlock`              | `account_otp_unlocks`               |\n| password_expiration     | `:password_change_time`      | `has_one`  | `PasswordChangeTime`     | `account_password_change_times`     |\n| recovery_codes          | `:recovery_codes`            | `has_many` | `RecoveryCode`           | `account_recovery_codes`            |\n| remember                | `:remember_key`              | `has_one`  | `RememberKey`            | `account_remember_keys`             |\n| reset_password          | `:password_reset_key`        | `has_one`  | `PasswordResetKey`       | `account_password_reset_keys`       |\n| single_session          | `:session_key`               | `has_one`  | `SessionKey`             | `account_session_keys`              |\n| sms_codes               | `:sms_code`                  | `has_one`  | `SmsCode`                | `account_sms_codes`                 |\n| verify_account          | `:verification_key`          | `has_one`  | `VerificationKey`        | `account_verification_keys`         |\n| verify_login_change     | `:login_change_key`          | `has_one`  | `LoginChangeKey`         | `account_login_change_keys`         |\n| webauthn                | `:webauthn_keys`             | `has_many` | `WebauthnKey`            | `account_webauthn_keys`             |\n| webauthn                | `:webauthn_user_id`          | `has_one`  | `WebauthnUserId`         | `account_webauthn_user_ids`         |\n\n\u003e [!NOTE]\n\u003e Some Rodauth tables use composite primary keys, which are supported in Active Record 7.1+. If you're on an older version of Active Record, you might need to add the [composite_primary_keys] gem to your Gemfile. Sequel has always natively supported composite primary keys.\n\n## Extending associations\n\nIt'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.\n\n```rb\n# lib/rodauth/features/foo.rb\nmodule Rodauth\n  Feature.define(:foo, :Foo) do\n    auth_value_method :foo_table, :account_foos\n    auth_value_method :foo_id_column, :id\n    # ...\n  end\nend\n\nif defined?(Rodauth::Model)\n  Rodauth::Model.register_association(:foo) do\n    { name: :foo, type: :one, table: foo_table, key: foo_id_column }\n  end\nend\n```\n\nThe `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:\n\n* `:name` – association name\n* `:type` – relationship type (`:one` for one-to-one, `:many` for one-to-many)\n* `:table` – associated table name\n* `:key` – foreign key on the associated table\n\nIt's possible to register multiple associations for the same Rodauth feature.\n\n## Examples\n\n### Checking whether account has multifactor authentication enabled\n\n```rb\nclass Account \u003c ActiveRecord::Base\n  include Rodauth::Model(RodauthApp.rodauth)\n\n  def mfa_enabled?\n    otp_key || (sms_code \u0026\u0026 sms_code.num_failures.nil?) || recovery_codes.any?\n  end\nend\n```\n\n### Retrieving all accounts with multifactor authentication enabled\n\n```rb\nclass Account \u003c ActiveRecord::Base\n  include Rodauth::Model(RodauthApp.rodauth)\n\n  scope :otp_setup, -\u003e { where(otp_key: OtpKey.all) }\n  scope :sms_codes_setup, -\u003e { where(sms_code: SmsCode.where(num_failures: nil)) }\n  scope :recovery_codes_setup, -\u003e { where(recovery_codes: RecoveryCode.all) }\n  scope :mfa_enabled, -\u003e { merge(otp_setup.or(sms_codes_setup).or(recovery_codes_setup)) }\nend\n```\n\n## Future plans\n\n### Joined associations\n\nIt'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.\n\n## Contributing\n\nBug 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](https://github.com/janko/rodauth-model/blob/main/CODE_OF_CONDUCT.md).\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).\n\n## Code of Conduct\n\nEveryone interacting in the Rodauth::Model project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/janko/rodauth-model/blob/main/CODE_OF_CONDUCT.md).\n\n[Rodauth]: https://rodauth.jeremyevans.net\n[composite_primary_keys]: https://github.com/composite-primary-keys/composite_primary_keys\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjanko%2Frodauth-model","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjanko%2Frodauth-model","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjanko%2Frodauth-model/lists"}