Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
45.8 KB
Raw Blame
class User < ApplicationRecord
  has_many :financekit_items, dependent: :destroy

  include Encryptable

  # Allow nil password for SSO-only users (JIT provisioning).
  # Custom validation ensures password is present for non-SSO registration.
  has_secure_password validations: false

  # Encrypt sensitive fields if ActiveRecord encryption is configured
  if encryption_ready?
    # MFA secrets
    encrypts :otp_secret, deterministic: true

    # PII - emails (deterministic for lookups, downcase for case-insensitive)
    encrypts :email, deterministic: true, downcase: true
    encrypts :unconfirmed_email, deterministic: true, downcase: true

    # PII - names (non-deterministic for maximum security)
    encrypts :first_name
    encrypts :last_name
  end

  belongs_to :family
  belongs_to :last_viewed_chat, class_name: "Chat", optional: true
  belongs_to :default_account, class_name: "Account", optional: true
  has_many :sessions, dependent: :destroy
  has_many :chats, dependent: :destroy
  has_many :api_keys, dependent: :destroy
  has_many :push_subscriptions, dependent: :destroy
  has_many :web_push_subscriptions, dependent: :destroy
  has_many :webauthn_credentials, dependent: :destroy
  has_many :mobile_devices, dependent: :destroy
  has_many :invitations, foreign_key: :inviter_id, dependent: :destroy
  has_many :impersonator_support_sessions, class_name: "ImpersonationSession", foreign_key: :impersonator_id, dependent: :destroy
  has_many :impersonated_support_sessions, class_name: "ImpersonationSession", foreign_key: :impersonated_id, dependent: :destroy
  has_many :oidc_identities, dependent: :destroy
  has_many :sso_audit_logs, dependent: :nullify
  has_many :owned_accounts, class_name: "Account", foreign_key: :owner_id
  has_many :account_shares, dependent: :destroy
  has_many :shared_accounts, through: :account_shares, source: :account
  has_many :budget_shares_given, class_name: "BudgetShare", foreign_key: :owner_id, inverse_of: :owner, dependent: :destroy
  has_many :budget_shares_received, class_name: "BudgetShare", foreign_key: :viewer_id, inverse_of: :viewer, dependent: :destroy
  accepts_nested_attributes_for :family, update_only: true

  MFA_BACKUP_CODE_COUNT = 8

  validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP }
  validate :ensure_valid_profile_image
  validates :default_period, inclusion: { in: Period::PERIODS.keys }
  validates :default_account_order, inclusion: { in: AccountOrder::ORDERS.keys }
  validates :locale, inclusion: { in: I18n.available_locales.map(&:to_s) }, allow_nil: true

  # Password is required on create unless the user is being created via SSO JIT.
  # SSO JIT users have password_digest = nil and authenticate via OIDC only.
  validates :password, presence: true, on: :create, unless: :skip_password_validation?
  validates :password, length: { minimum: 8 }, allow_nil: true
  # `validations: false` above also drops Rails' confirmation and current-password
  # (password_challenge) checks, so restore both here.
  validates :password, confirmation: true, allow_blank: true
  validate :password_challenge_matches, unless: -> { password_challenge.nil? }
  normalizes :email, with: ->(email) { email.strip.downcase }
  normalizes :unconfirmed_email, with: ->(email) { email&.strip&.downcase }
  normalizes :locale, with: ->(locale) { locale.presence }

  normalizes :first_name, :last_name, with: ->(value) { value.strip.presence }

  enum :role, { guest: "guest", member: "member", admin: "admin", super_admin: "super_admin" }, validate: true

  # SQL counterpart to #preview_features_enabled?, for callers that filter
  # users (or their families) in one query instead of loading and iterating.
  # The `@>` containment operator uses index_users_on_preferences (GIN) and
  # matches only a JSON boolean true, so it agrees with that predicate's
  # strict `== true` — a stray "yes" enables neither.
  scope :with_preview_features, -> {
    where("preferences @> ?", { preview_features_enabled: true }.to_json)
  }

  attribute :ui_layout, :string
  enum :ui_layout, { dashboard: "dashboard", intro: "intro" }, validate: true, prefix: true

  before_validation :apply_ui_layout_defaults
  before_validation :apply_role_based_ui_defaults

  # Returns the appropriate role for a new user creating a family.
  # The very first user of an instance becomes super_admin; subsequent users
  # get the specified admin-capable fallback role.
  # Keep this one-key advisory lock stable across deploys so old and new app
  # processes serialize first-user role selection on the same database lock.
  FIRST_USER_ROLE_LOCK_KEY = 8_391_247

  def self.lock_first_user_role!
    connection.execute(sanitize_sql_array([ "SELECT pg_advisory_xact_lock(?)", FIRST_USER_ROLE_LOCK_KEY ]))
  end

  def self.role_for_new_family_creator(fallback_role: :admin)
    fallback_role = fallback_role.to_s.in?(%w[admin super_admin]) ? fallback_role : :admin

    User.exists? ? fallback_role : :super_admin
  end

  # Deterministic lookups like `find_by(email:)` and `authenticate_by` miss
  # rows whose email is still legacy plaintext (stored before encryption was
  # active and not yet re-encrypted by `bin/rails security:backfill_encryption`):
  # extend_queries does not cover attributes that also use `normalizes`. The
  # fallback matches those rows by their literal column value.
  def self.find_by_email_with_legacy_fallback(email)
    normalized = email.to_s.strip.downcase
    return nil if normalized.blank?

    find_by(email: normalized) || find_by_legacy_plaintext_email(normalized)
  end

  # Takes the legacy path only for a plaintext row; every other case goes
  # through authenticate_by, which stays timing-safe for wrong passwords and
  # unknown emails. The legacy lookup runs first on every login (one indexed
  # query) so that legacy and encrypted rows cost the same single password
  # check. Nil and empty passwords are rejected up front, as authenticate_by does.
  # A user without a local password (SSO only) still costs one hash, so
  # response time does not reveal such accounts. A non-String password (a
  # JSON number) is checked as text instead of raising.
  def self.authenticate_by_email(email:, password:)
    return nil if password.nil? || password.to_s.empty?

    password = password.to_s
    normalized = email.to_s.strip.downcase
    legacy_user = find_by_legacy_plaintext_email(normalized)
    user = legacy_user || find_by(email: normalized)
    if user && user.password_digest.blank?
      new(password: password)
      return nil
    end
    return authenticate_by(email: normalized, password: password) unless legacy_user

    legacy_user if legacy_user.authenticate(password)
  end

  # Legacy rows were always stored normalized (`normalizes :email` predates
  # encryption), so an exact match uses the unique index. Only well-formed
  # emails are looked up, so a pasted ciphertext can never match its own row.
  def self.find_by_legacy_plaintext_email(normalized_email)
    return nil unless normalized_email.match?(URI::MailTo::EMAIL_REGEXP)

    find_by([ "email = ?", normalized_email ])
  end
  private_class_method :find_by_legacy_plaintext_email

  class << self
    def human_attribute_name(attribute, options = {})
      locale = options[:locale] || I18n.locale
      moniker = I18n.with_locale(locale) do
        Current.family&.moniker_label || I18n.t("shared.family_moniker.singular", default: "Family")
      end

      options = {
        moniker: moniker
      }.merge(options)

      super(attribute, options)
    end
  end

  has_one_attached :profile_image, dependent: :purge_later do |attachable|
    attachable.variant :thumbnail, resize_to_fill: [ 300, 300 ], convert: :webp, saver: { quality: 80 }
    attachable.variant :small, resize_to_fill: [ 72, 72 ], convert: :webp, saver: { quality: 80 }, preprocessed: true
  end

  validate :profile_image_size

  generates_token_for :password_reset, expires_in: 15.minutes do
    password_salt&.last(10)
  end

  generates_token_for :email_confirmation, expires_in: 1.day do
    unconfirmed_email
  end

  def pending_email_change?
    unconfirmed_email.present?
  end

  def initiate_email_change(new_email)
    return false if new_email == email

    if Rails.application.config.app_mode.self_hosted? && !Setting.require_email_confirmation
      update(email: new_email)
    else
      if update(unconfirmed_email: new_email)
        EmailConfirmationMailer.with(user: self).confirmation_email.deliver_later
        true
      else
        false
      end
    end
  end

  def resend_confirmation_email
    if pending_email_change?
      EmailConfirmationMailer.with(user: self).confirmation_email.deliver_later
      true
    else
      false
    end
  end

  def request_impersonation_for(user_id)
    impersonated = User.find(user_id)
    impersonator_support_sessions.create!(impersonated: impersonated)
  end

  def admin?
    super_admin? || role == "admin"
  end

  # Setting values are shared by every family on the instance, so changing them
  # is a super admin's job: a family admin is anyone who signed up. A
  # self-hosted instance with a single real family has no other tenant to
  # protect. Generated demo households must neither revoke that family's access
  # nor grant instance access to demo users. Use the generator's synthetic
  # subscription marker, never an editable family name or user email.
  def manages_instance_settings?
    return true if super_admin?
    return false unless admin? && Rails.application.config.app_mode.self_hosted?
    return false if family.subscription&.synthetic?
    return true if Family.count == 1

    demo_family_ids = Subscription.where(stripe_id: Subscription::DEMO_STRIPE_ID).select(:family_id)
    Family.where.not(id: demo_family_ids).limit(2).pluck(:id) == [ family_id ]
  end

  def accessible_accounts
    family.accounts.accessible_by(self)
  end

  def finance_accounts
    family.accounts.included_in_finances_for(self)
  end

  # Other family members who have granted this user access to their personal
  # budget (see BudgetShare). Used to build the budget owner switcher.
  def budget_owners_shared_with_me
    User.where(id: budget_shares_received.select(:owner_id))
  end

  def display_name
    [ first_name, last_name ].compact.join(" ").presence || email
  end

  def initial
    (display_name&.first || email.first).upcase
  end

  def initials
    if first_name.present? && last_name.present?
      "#{first_name.first}#{last_name.first}".upcase
    else
      initial
    end
  end

  def show_ai_sidebar?
    show_ai_sidebar
  end

  def ai_available?
    effective_type = family&.effective_assistant_type || "builtin"
    return false if effective_type == "mcp_only"
    return true unless Rails.application.config.app_mode.self_hosted?

    case effective_type
    when "external"
      Assistant::External.available_for?(self)
    else
      openai_configured? || anthropic_configured?
    end
  end

  def openai_configured?
    Provider::Openai.configured?
  end

  def anthropic_configured?
    Provider::Anthropic.configured?
  end

  def ai_enabled?
    ai_enabled && ai_available?
  end

  def self.default_ui_layout
    layout = Rails.application.config.x.ui&.default_layout || "dashboard"
    layout.in?(%w[intro dashboard]) ? layout : "dashboard"
  end

  # SSO-only users have OIDC identities but no local password.
  # They cannot use password reset or local login.
  def sso_only?
    password_digest.nil? && oidc_identities.any?
  end

  # Check if user has a local password set (can authenticate locally)
  def has_local_password?
    password_digest.present?
  end

  # Attribute to skip password validation during SSO JIT provisioning
  attr_accessor :skip_password_validation

  # Deactivation
  validate :can_deactivate, if: -> { active_changed? && !active }

  # Super Admin Invariant
  validate :ensure_not_last_super_admin, if: :losing_super_admin_privileges?
  before_destroy :ensure_not_last_super_admin_on_destroy

  after_update_commit :purge_later, if: -> { saved_change_to_active?(from: true, to: false) }
  after_update_commit :revoke_all_access_tokens, if: -> { saved_change_to_active?(from: true, to: false) }
  # Runs inside the update's transaction, so the user row stays locked until
  # commit. Every endpoint that issues a token from an existing credential
  # (/api/v1/auth/refresh and Oauth::TokensController) takes the same lock
  # first, so none can mint a token this sweep misses. The sweep after commit
  # catches grants issued without that lock, such as an authorization code
  # created by /oauth/authorize while the change was in flight.
  after_update :revoke_oauth_access, if: :saved_change_to_password_digest?
  after_update_commit :revoke_oauth_access, if: :saved_change_to_password_digest?

  def deactivate
    return true unless active?

    transaction do
      update(active: false, email: deactivated_email)
    end || false
  end

  private

    def losing_super_admin_privileges?
      (role_changed? && role_was == "super_admin" && role != "super_admin") ||
        (active_changed? && active_was == true && !active && role == "super_admin")
    end

    def ensure_not_last_super_admin
      return unless check_last_super_admin_invariant_failed?

      attribute = role_changed? ? :role : :base
      errors.add(attribute, :cannot_remove_last_super_admin, message: I18n.t("admin.users.update.last_super_admin_error"))
    end

    def ensure_not_last_super_admin_on_destroy
      return unless role == "super_admin" && active?

      if check_last_super_admin_invariant_failed?
        errors.add(:base, :cannot_remove_last_super_admin, message: I18n.t("admin.users.update.last_super_admin_error"))
        throw(:abort)
      end
    end

    def check_last_super_admin_invariant_failed?
      # Lock all active super admins in a consistent order to prevent deadlocks
      locked_ids = User.where(role: :super_admin, active: true).order(:id).lock.pluck(:id)
      locked_ids.size <= 1 && locked_ids.include?(id)
    end

  public

  # Permanent removal of another user, initiated by a super admin from the
  # instance users page. Reuses the sanctioned deactivate -> UserPurgeJob path
  # (which reassigns owned accounts, or destroys the family when this is its
  # last member) for the heavy data cleanup, but additionally revokes every
  # live authentication vector *synchronously* so there is no window in which
  # the removed user can keep acting or re-authenticate before the async purge
  # runs. Returns false (with errors populated) when the user cannot be
  # deactivated, e.g. an admin who still has co-members in their family.
  def permanently_remove!
    was_active = active?
    removed = transaction do
      identity_label = email
      raise ActiveRecord::Rollback unless deactivate

      SsoIdentityBlock.block_all!(oidc_identities, identity_label: identity_label)
      revoke_all_credentials!
      true
    end || false

    purge_later if removed && !was_active
    removed
  end

  # Destroys every credential/session that can authenticate as this user.
  # Web sessions and the SSO identity re-auth path (OidcIdentity lookup by
  # provider+uid) are not gated on #active?, so they must be torn down here for
  # revocation to be immediate; the async purge would otherwise leave a window.
  def revoke_all_credentials!
    revoke_oauth_tokens!
    sessions.destroy_all
    api_keys.destroy_all
    mobile_devices.destroy_all
    webauthn_credentials.destroy_all
    oidc_identities.destroy_all
  end

  # Raised by #with_active_lock! to reject session/token issuance for a
  # deactivated or concurrently-purged user. The one error contract every
  # web/JSON/mobile/OAuth-adapter caller rescues, so a deactivation result
  # can never be confused with an unrelated persistence failure.
  class InactiveError < StandardError; end

  # Raised by #with_active_lock! when the password changed between the
  # caller's password check and the locked issuance step. The new password's
  # revocation sweep has already run by then, so issuing would hand out a
  # session or token for the old password that nothing revokes.
  class StaleCredentialsError < StandardError; end

  # The one locked primitive for the actual authorization boundary: asserts
  # this user is eligible for new session/token issuance *right now*, under
  # a row lock, immediately before minting. Callers may additionally check
  # #active? earlier for a fast, friendly rejection (skip an MFA/device
  # round trip) — that's a UX optimization only, never a substitute for
  # this check, however "obviously" already-checked the user seems.
  # Pass the #password_fingerprint taken when the password was checked to
  # also reject issuance after a concurrent password change.
  def with_active_lock!(password_fingerprint: nil)
    lock_acquired = false

    with_lock do
      lock_acquired = true
      raise InactiveError unless active?
      raise StaleCredentialsError if password_fingerprint && password_fingerprint != self.password_fingerprint
      yield self
    end
  rescue ActiveRecord::RecordNotFound
    # Only translate a RecordNotFound raised by with_lock's own reload (the
    # row was deleted by a concurrent purge before we could lock it) into
    # InactiveError. Once the lock is held, re-raise: a RecordNotFound from
    # inside the caller's block is an unrelated failure and must not be
    # misreported as "inactive" either.
    raise if lock_acquired
    raise InactiveError
  end

  def can_deactivate
    if admin? && family.users.count > 1
      errors.add(:base, :cannot_deactivate_admin_with_other_users)
    end
  end

  def purge_later
    UserPurgeJob.perform_later(self)
  end

  def transfer_to_family!(new_family, role: self.role)
    transaction do
      lock!

      accounts_to_move = owned_accounts.order(:id).to_a
      provider_items_to_move = provider_items_for_transfer(accounts_to_move)
      moving_default_account = accounts_to_move.any? { |account| account.id == default_account_id }

      provider_items_to_move.sort_by(&:id).each(&:lock!)
      accounts_to_move.each(&:lock!)

      account_shares.delete_all

      update!(family: new_family, role: role, default_account: moving_default_account ? default_account : nil)

      accounts_to_move.each do |account|
        account.update!(family: new_family)
      end

      AccountStatement.where(account: accounts_to_move).update_all(family_id: new_family.id, updated_at: Time.current) if accounts_to_move.any?

      provider_items_to_move.each do |provider_item|
        if provider_item.is_a?(FinancekitItem)
          lineage_ids = provider_item.financekit_account_lineages.select(:id)
          FinancekitAccountLineage.where(id: lineage_ids).update_all(family_id: new_family.id, updated_at: Time.current)
          provider_item.financekit_conflicts.update_all(family_id: new_family.id, updated_at: Time.current)
        end
        attrs = { family: new_family }

        # provider_items_for_transfer only returns items whose accounts all
        # belong to this user, so the connection genuinely follows them. Its
        # owner has to follow too: the previous owner stays behind in the old
        # family, and ProviderItemOwnable validates that an owner and its item
        # share a family.
        attrs[:owner] = self if provider_item.respond_to?(:owner_id)

        provider_item.update!(**attrs)
      end

      new_family.auto_share_existing_accounts_with(self)
    end
  end

  def provider_items_for_transfer(accounts_to_move)
    account_ids_to_move = accounts_to_move.map(&:id)
    provider_items = accounts_to_move.flat_map do |account|
      account.account_providers.includes(:provider).filter_map do |account_provider|
        provider_items_for(account_provider.provider)
      end
    end.flatten.uniq
    provider_items.concat(financekit_items)
    provider_items.uniq!

    provider_items.each do |provider_item|
      if provider_item.is_a?(FinancekitItem) && provider_item.user_id != id
        errors.add(:base, :provider_item_has_other_accounts)
        raise ActiveRecord::RecordInvalid, self
      end

      linked_account_ids = provider_item.accounts.map(&:id)
      next if linked_account_ids.all? { |account_id| account_ids_to_move.include?(account_id) }

      errors.add(:base, :provider_item_has_other_accounts)
      raise ActiveRecord::RecordInvalid, self
    end

    provider_items
  end

  def provider_items_for(provider)
    if provider.is_a?(FinancekitAccountLineage)
      return provider.financekit_accounts.includes(:financekit_item).map(&:financekit_item).uniq
    end

    item_association = provider.class.reflect_on_all_associations(:belongs_to).find do |association|
      association.name.to_s.end_with?("_item") && provider.respond_to?(association.name)
    end

    Array(provider.public_send(item_association.name)) if item_association
  end

  # Revokes every Doorkeeper access token issued to this user (mobile app and
  # third-party OAuth clients; a revoked token's refresh token is refused too)
  # and every authorization grant not yet exchanged for one. Returns the
  # number of tokens and grants revoked.
  def revoke_oauth_tokens!
    now = Time.current
    [
      Doorkeeper::AccessToken.where(resource_owner_id: id, revoked_at: nil).update_all(revoked_at: now),
      Doorkeeper::AccessGrant.where(resource_owner_id: id, revoked_at: nil).update_all(revoked_at: now)
    ]
  end

  # Revokes mobile/third-party API access alongside the web-session
  # invalidation above. Without this, a deactivated user's existing
  # Doorkeeper tokens and API keys stay valid on the wire — currently
  # harmless only because Api::V1::BaseController/McpController re-check
  # active? on every request, but that's a second, independent safeguard,
  # not a substitute for actually revoking the credentials. Also revokes
  # unexchanged OAuth authorization grants — /oauth/token doesn't go
  # through the cookie authenticator, so a still-valid grant issued right
  # before deactivation could otherwise be exchanged for a fresh token
  # afterward.
  def revoke_all_access_tokens
    tokens_revoked, grants_revoked = revoke_oauth_tokens!
    keys_revoked = api_keys.active.visible.update_all(revoked_at: Time.current)

    if tokens_revoked > 0 || grants_revoked > 0 || keys_revoked > 0
      Rails.logger.warn(
        "[AUTH] Revoked #{tokens_revoked} access token(s), #{grants_revoked} authorization grant(s), " \
        "and #{keys_revoked} API key(s) for deactivated user_id=#{id}"
      )
    end
  end

  # A new password must lock out whoever signed in to the mobile app or an
  # OAuth client with the old one: their access and refresh tokens would
  # otherwise stay valid for up to 30 days and keep renewing. API keys are
  # created deliberately for integrations and do not depend on the password,
  # so they stay.
  def revoke_oauth_access
    tokens_revoked, grants_revoked = revoke_oauth_tokens!

    if tokens_revoked > 0 || grants_revoked > 0
      Rails.logger.info(
        "[AUTH] Revoked #{tokens_revoked} access token(s) and #{grants_revoked} authorization grant(s) " \
        "after password change for user_id=#{id}"
      )
    end
  end

  def password_fingerprint
    Digest::SHA256.hexdigest(password_digest.to_s)
  end

  def purge
    if last_user_in_family?
      family.destroy
    else
      reassign_owned_accounts!
      destroy
    end
  end

  # MFA
  def setup_mfa!
    update!(
      otp_secret: ROTP::Base32.random(32),
      otp_required: false,
      otp_backup_codes: [],
      otp_last_used_at: nil
    )
  end

  def enable_mfa!
    raise ArgumentError, "OTP secret must be set before enabling MFA" if otp_secret.blank?

    backup_codes = generate_backup_codes

    # Store bcrypt digests only; this Postgres array cannot use AR encryption.
    update!(
      otp_required: true,
      otp_backup_codes: backup_codes.map { |code| digest_backup_code(code) }
    )

    backup_codes
  end

  def disable_mfa!
    transaction do
      update!(
        otp_secret: nil,
        otp_required: false,
        otp_backup_codes: [],
        otp_last_used_at: nil
      )
      webauthn_credentials.destroy_all
    end
  end

  # Same answer as verify_otp, but spends nothing: lets a passkey registration
  # refuse a bad code before the browser creates a credential the server would
  # then throw away. The code is still consumed by verify_otp when it is saved.
  def otp_code_status(code)
    return :invalid if otp_secret.blank?

    normalized_code = normalize_mfa_code(code)
    return :invalid if normalized_code.blank?

    return :accepted if totp.verify(normalized_code, drift_behind: 15, after: otp_last_used_at)

    if backup_code_input?(normalized_code)
      matched = Array(otp_backup_codes).any? { |stored_code| backup_code_matches?(stored_code, normalized_code) }
      return matched ? :accepted : :invalid
    end

    totp.verify(normalized_code, drift_behind: 15) ? :replayed : :invalid
  end

  def verify_otp?(code)
    verify_otp(code) == :accepted
  end

  # Enrollment needs to tell a replayed (correct but already-used) code apart
  # from a wrong one so a duplicate submit does not tear down MFA; login
  # callers use verify_otp?, where a replay stays a plain failure.
  def verify_otp(code)
    return :invalid if otp_secret.blank?

    normalized_code = normalize_mfa_code(code)
    return :invalid if normalized_code.blank?

    # after: rejects the time step already used, so a code seen once (over a
    # shoulder, in a proxy log) cannot sign in again while it is still valid.
    if (time_step = totp.verify(normalized_code, drift_behind: 15, after: otp_last_used_at))
      return claim_otp_time_step!(time_step) ? :accepted : :replayed
    end

    if backup_code_input?(normalized_code)
      return consume_backup_code!(normalized_code) ? :accepted : :invalid
    end

    # Still valid for the secret? Then only its time step was already used.
    totp.verify(normalized_code, drift_behind: 15) ? :replayed : :invalid
  end

  def provisioning_uri
    return nil unless otp_secret.present?
    totp.provisioning_uri(email)
  end

  def ensure_webauthn_id!
    return webauthn_id if webauthn_id.present?

    with_lock do
      update!(webauthn_id: WebAuthn.generate_user_id) unless webauthn_id.present?
    end

    webauthn_id
  end

  def webauthn_enabled?
    otp_required? && webauthn_credentials.exists?
  end

  def onboarded?
    onboarded_at.present?
  end

  def needs_onboarding?
    !onboarded?
  end

  def account_order
    AccountOrder.find(default_account_order) || AccountOrder.default
  end

  # Answers to onboarding's Tools/AI step: where the user is coming from and
  # how they want AI. They don't import anything or configure a provider.
  ONBOARDING_TOOLS = %w[
    actual_budget banktivity copilot_money firefly_iii gnucash lunch_money maybe
    monarch_money money_manager_ex moneywiz pocketsmith quicken_classic quicken_simplifi ynab other
  ].freeze
  ONBOARDING_NO_TOOLS = "nothing_yet".freeze
  ONBOARDING_AI_MODES = %w[none builtin external].freeze
  ONBOARDING_OTHER_TOOL_MAX_LENGTH = 80

  def onboarding_tools
    tools = preferences&.dig("onboarding_tools")
    tools.is_a?(Array) ? tools : []
  end

  def onboarding_other_tool
    preferences&.dig("onboarding_other_tool").presence
  end

  # The saved answer, unless the AI switch has changed since: then the switch wins, so
  # resubmitting the step without touching it never turns AI (or household consent) on or off.
  def onboarding_ai_mode
    mode = preferences&.dig("onboarding_ai_mode")
    current = ai_enabled ? "builtin" : "none"
    return current unless ONBOARDING_AI_MODES.include?(mode)

    (mode != "none") == ai_enabled ? mode : current
  end

  # "Nothing yet" excludes every other tool and unknown values are dropped.
  # Built-in and external AI enable this user's AI features; only no AI turns them off.
  # The household's assistant settings still select the conversation backend.
  # For an admin that switch is also the household's AI consent (Family#ai_consented?).
  # Guests always have AI on, so they aren't asked.
  # rendered_ai_mode is the choice the page showed: when the user left it as it was,
  # the AI switch stays as it is now, even if it changed after the page rendered.
  def save_onboarding_tools_and_ai(tools:, other_tool:, ai_mode:, rendered_ai_mode: nil)
    chosen = Array(tools).map(&:to_s)
    chosen = chosen.include?(ONBOARDING_NO_TOOLS) ? [ ONBOARDING_NO_TOOLS ] : chosen & ONBOARDING_TOOLS
    other = other_tool.to_s.strip.first(ONBOARDING_OTHER_TOOL_MAX_LENGTH).presence if chosen.include?("other")
    mode = ONBOARDING_AI_MODES.include?(ai_mode.to_s) ? ai_mode.to_s : "none"

    transaction do
      with_locked_preferences do |prefs|
        prefs["onboarding_tools"] = chosen
        prefs["onboarding_ai_mode"] = mode unless guest?
        other ? prefs["onboarding_other_tool"] = other : prefs.delete("onboarding_other_tool")
      end
      attributes = { set_onboarding_goals_at: Time.current, onboarded_at: Time.current }
      attributes[:ai_enabled] = mode != "none" unless guest? || mode == rendered_ai_mode.to_s
      update!(attributes)
    end
  end

  # Whether the activity feed of a linked account always lists the balance
  # updates its syncs leave behind (see Account#hides_balance_updates_by_default?).
  # Off until turned on in Settings > Preferences. The activity Filter menu can
  # show them for one view without changing this.
  def show_balance_updates?
    preferences&.dig("show_balance_updates") == true
  end

  # @param value [Boolean, String] a form value such as "true" or "false"
  def update_show_balance_updates(value)
    shown = ActiveModel::Type::Boolean.new.cast(value) == true
    with_locked_preferences { |prefs| prefs["show_balance_updates"] = shown }
  end

  MANUAL_ACCOUNT_ORDER_LIMIT = 500

  # Drag-and-drop order of accounts per account group, keyed by accountable
  # key (e.g. "depository") with account ids in display order.
  def manual_account_order
    order = preferences&.dig("manual_account_order")
    order.is_a?(Hash) ? order : {}
  end

  # Stores the order of one account group. Ids the user cannot access are
  # dropped so the stored preference never references foreign accounts.
  def update_manual_account_order(group_key, account_ids)
    group_key = group_key.to_s
    return false unless Accountable::TYPES.map(&:underscore).include?(group_key)
    return false unless account_ids.is_a?(Array)

    requested_ids = account_ids.map(&:to_s).uniq.first(MANUAL_ACCOUNT_ORDER_LIMIT)
    accessible_ids = accessible_accounts.where(id: requested_ids, accountable_type: group_key.camelize).pluck(:id).to_set
    ordered_ids = requested_ids.select { |id| accessible_ids.include?(id) }

    with_locked_preferences do |prefs|
      prefs["manual_account_order"] = manual_account_order.merge(group_key => ordered_ids)
    end
  end

  # Locked read-modify-write of the preferences JSONB: yields a copy of the
  # current preferences (re-read under a row lock) to change in place, then
  # saves it, so concurrent updates of other keys are not lost. Attributes set
  # on the user inside the block are saved with it.
  def with_locked_preferences
    transaction do
      lock!
      updated_prefs = (preferences || {}).deep_dup
      yield updated_prefs
      update!(preferences: updated_prefs)
    end
  end

  def default_account_for_transactions
    return nil unless default_account_id.present?

    account = default_account
    return nil unless account&.eligible_for_transaction_default? && account.family_id == family_id

    account
  end

  # Release highlight ("What's new" popup) tracking. Account-level so every
  # device the user signs in from stays in sync.
  def last_seen_release_tag
    preferences&.[]("last_seen_release_tag")
  end

  def release_seen?(tag)
    tag == last_seen_release_tag || Array(preferences&.[]("seen_release_tags")).include?(tag)
  end

  def mark_release_seen!(tag)
    parsed_release_tag_version!(tag)

    with_lock do
      # Acknowledgement is about identity, not version precedence: hotfix tags
      # sort before their base release, and users can switch release channels.
      # Merge after reloading under the lock so stale tabs cannot lose tags.
      seen_tags = Array(preferences&.[]("seen_release_tags"))
      legacy_tag = last_seen_release_tag
      seen_tags += [ legacy_tag ] if parsed_release_tag_version(legacy_tag)
      seen_tags = (seen_tags + [ tag ]).uniq

      update!(preferences: (preferences || {}).merge(
        "seen_release_tags" => seen_tags,
        "last_seen_release_tag" => tag
      ))
    end
  end

  def parsed_release_tag_version!(tag)
    raise ArgumentError, "invalid release tag" unless tag.to_s.match?(/\Av\d+\.\d+\.\d+(?:[-+.][0-9A-Za-z.-]+)?\z/)

    Calver.from_release_tag(tag).version
  end

  def parsed_release_tag_version(tag)
    parsed_release_tag_version!(tag)
  rescue ArgumentError
    nil
  end

  # Dashboard preferences management
  def dashboard_section_collapsed?(section_key)
    preferences&.dig("collapsed_sections", section_key) == true
  end

  def dashboard_section_order
    preferences&.[]("section_order") || default_dashboard_section_order
  end

  def dashboard_hidden_sections
    preferences&.[]("hidden_sections") || []
  end

  # Adds or removes one key rather than taking the whole list, so a stale tab
  # hiding one widget can't bring back another hidden elsewhere.
  def update_dashboard_section_hidden(section_key, hidden)
    with_locked_preferences do |prefs|
      keys = dashboard_hidden_sections - [ section_key ]
      keys << section_key if hidden
      prefs["hidden_sections"] = keys
    end
  end

  # Per-widget height preset override ("compact" | "auto" | "tall"); nil = use default.
  def dashboard_section_height(section_key)
    preferences&.dig("dashboard_section_layout", section_key, "height")
  end

  CASHFLOW_SANKEY_GROUPINGS = IncomeStatement::CashFlowGraph::GROUPINGS.keys.freeze

  # Preview cash-flow Sankey: flows by category (default) or through each account.
  def cashflow_sankey_group_by
    group_by = preferences&.dig("cashflow_sankey_group_by")
    CASHFLOW_SANKEY_GROUPINGS.include?(group_by) ? group_by : "category"
  end

  # Per-widget column-span override ("single" | "full"); nil = use default.
  def dashboard_section_width(section_key)
    preferences&.dig("dashboard_section_layout", section_key, "col_span")
  end

  # laid_out_order is the order the dashboard laid its widgets out in, which
  # also places widgets the saved order doesn't list yet.
  def update_dashboard_preferences(prefs, laid_out_order: nil)
    # Locked so sections collapsed in quick succession don't overwrite each other.
    with_locked_preferences do |updated_prefs|
      if prefs["section_order"]
        prefs = prefs.merge("section_order" => keep_hidden_sections_in_order(prefs["section_order"], laid_out_order || dashboard_section_order))
      end
      prefs.each do |key, value|
        if value.is_a?(Hash)
          updated_prefs[key] ||= {}
          # deep_merge so a partial update of one nested dimension (e.g. a widget's
          # col_span) doesn't clobber a sibling dimension (e.g. its height).
          updated_prefs[key] = updated_prefs[key].deep_merge(value)
        else
          updated_prefs[key] = value
        end
      end
    end
  end

  # Section preferences for the pages built on the Reports section
  # framework (Reports, the portfolio hub). Each page is a namespace; its
  # order lives under "<namespace>_section_order" and its collapsed set under
  # "<namespace>_collapsed_sections", so two pages never read or write each
  # other's keys. Reports' original keys are the "reports" namespace, so
  # nothing already stored changes meaning. Each namespace maps to its
  # default order; the portfolio's is read from its registry so the two
  # lists cannot drift.
  SECTION_DEFAULT_ORDERS = {
    "reports" => %w[trends_insights transactions_breakdown].freeze,
    "portfolio" => Portfolio::SectionRegistry::KEYS
  }.freeze

  def section_order(namespace)
    prefix = section_namespace!(namespace)
    stored = preferences&.[]("#{prefix}_section_order")
    stored.is_a?(Array) ? stored.map(&:to_s).uniq : SECTION_DEFAULT_ORDERS.fetch(prefix).dup
  end

  def section_collapsed?(namespace, section_key)
    prefix = section_namespace!(namespace)
    collapsed = preferences&.[]("#{prefix}_collapsed_sections")
    collapsed.is_a?(Hash) && collapsed[section_key] == true
  end

  # `order` replaces the namespace's order; `collapsed` merges into the
  # namespace's collapsed set (one key per toggle, so quick successive
  # toggles keep each other's state). The namespace decides which keys are
  # written: a caller cannot reach another page's keys through this method.
  # Only an array of keys (deduplicated) and a hash of key => flag are stored;
  # any other shape is dropped, since the readers index into them.
  def update_section_preferences(namespace, order: nil, collapsed: nil)
    prefix = section_namespace!(namespace)
    prefs = {}
    prefs["#{prefix}_section_order"] = order.map(&:to_s).uniq if order.is_a?(Array)
    collapsed = collapsed.to_unsafe_h if collapsed.respond_to?(:to_unsafe_h)
    if collapsed.is_a?(Hash)
      prefs["#{prefix}_collapsed_sections"] = collapsed.to_h { |key, flag| [ key.to_s, ActiveModel::Type::Boolean.new.cast(flag) == true ] }
    end
    return true if prefs.empty?

    with_locked_preferences do |updated_prefs|
      prefs.each do |key, value|
        if value.is_a?(Hash)
          stored = updated_prefs[key]
          updated_prefs[key] = (stored.is_a?(Hash) ? stored : {}).merge(value)
        else
          updated_prefs[key] = value
        end
      end
    end
  end

  # Reports preferences management
  def reports_section_collapsed?(section_key)
    section_collapsed?("reports", section_key)
  end

  def reports_section_order
    section_order("reports")
  end

  REPORTS_BIGGEST_EXPENSES_LIMITS = [ 5, 10, 25 ].freeze
  DEFAULT_REPORTS_BIGGEST_EXPENSES_LIMIT = 10

  def reports_biggest_expenses_limit
    stored = preferences&.[]("reports_biggest_expenses_limit")
    REPORTS_BIGGEST_EXPENSES_LIMITS.include?(stored) ? stored : DEFAULT_REPORTS_BIGGEST_EXPENSES_LIMIT
  end

  def update_reports_preferences(prefs)
    return false unless update_section_preferences(
      "reports",
      order: prefs["reports_section_order"],
      collapsed: prefs["reports_collapsed_sections"]
    )

    # A limit outside the offered choices is dropped, like any other bad value.
    limit = Integer(prefs["reports_biggest_expenses_limit"].to_s, exception: false)
    return true unless REPORTS_BIGGEST_EXPENSES_LIMITS.include?(limit)

    with_locked_preferences { |updated_prefs| updated_prefs["reports_biggest_expenses_limit"] = limit }
  end

  # Transactions preferences management
  def show_split_grouped?
    preferences&.dig("show_split_grouped") != false
  end

  # Returns whether the user has enabled the two-column dashboard layout.
  def dashboard_two_column?
    preferences&.dig("dashboard_two_column") == true
  end

  # Returns the accountable keys (e.g. "depository", "credit_card") that should
  # start expanded in the sidebar and dashboard balance sheet, or an empty
  # array when unset. Stored in the preferences JSONB column.
  def always_expanded_account_groups
    preferences&.dig("always_expanded_account_groups") || []
  end

  # Returns whether the given key (coerced to a string) is selected to start
  # expanded in the sidebar and dashboard balance sheet.
  def always_expanded_account_group?(account_group_key)
    always_expanded_account_groups.include?(account_group_key.to_s)
  end

  # Returns whether clicking outside a modal is prevented from closing it.
  def disable_modal_click_outside?
    preferences&.dig("disable_modal_click_outside") == true
  end

  def push_budget_warnings_enabled?
    preferences&.dig("push_budget_warnings_enabled") == true
  end

  def preview_features_enabled?
    preferences&.dig("preview_features_enabled") == true
  end

  # The experimental Sankey comparison chart (and its feedback prompt) is
  # opt-in on top of preview features, so a user can keep preview features
  # enabled without a second chart rendering underneath the cash flow widget.
  def cashflow_preview_enabled?
    preferences&.dig("cashflow_preview_enabled") == true
  end

  private
    def apply_ui_layout_defaults
      self.ui_layout = (ui_layout.presence || self.class.default_ui_layout)
    end

    def apply_role_based_ui_defaults
      if ui_layout_intro?
        if guest?
          self.show_sidebar = false
          self.show_ai_sidebar = false
          self.ai_enabled = true
        else
          self.ui_layout = "dashboard"
        end
      elsif guest?
        self.ui_layout = "intro"
        self.show_sidebar = false
        self.show_ai_sidebar = false
        self.ai_enabled = true
      end

      if leaving_guest_role?
        self.show_sidebar = true unless show_sidebar
        self.show_ai_sidebar = true unless show_ai_sidebar
      end

      if new_record? && member? && !ai_available?
        self.show_ai_sidebar = false
      end
    end

    def leaving_guest_role?
      return false unless will_save_change_to_role?

      previous_role, new_role = role_change_to_be_saved
      previous_role == "guest" && new_role != "guest"
    end

    def skip_password_validation?
      skip_password_validation == true
    end

    def password_challenge_matches
      digest_was = password_digest_was
      return if digest_was.present? && BCrypt::Password.new(digest_was).is_password?(password_challenge)

      errors.add(:password_challenge)
    end

    # The dashboard only sends the order of the widgets it rendered, so put
    # each hidden widget back after the one it followed before.
    def keep_hidden_sections_in_order(new_order, old_order)
      hidden = dashboard_hidden_sections
      (old_order & hidden).reduce(new_order - hidden) do |order, key|
        predecessor = old_order[0...old_order.index(key)].reverse.find { |k| order.include?(k) }
        order.insert(predecessor ? order.index(predecessor) + 1 : 0, key)
      end
    end

    def default_dashboard_section_order
      %w[insights_feed cashflow_sankey outflows_donut net_worth_chart balance_sheet]
    end

    def section_namespace!(namespace)
      namespace = namespace.to_s
      raise ArgumentError, "unknown section namespace #{namespace.inspect}" unless SECTION_DEFAULT_ORDERS.key?(namespace)

      namespace
    end
    def ensure_valid_profile_image
      return unless profile_image.attached?

      unless profile_image.content_type.in?(%w[image/jpeg image/png])
        errors.add(:profile_image, "must be a JPEG or PNG")
        profile_image.purge
      end
    end

    def last_user_in_family?
      family.users.count == 1
    end

    def reassign_owned_accounts!
      account_ids = owned_accounts.pluck(:id)
      return if account_ids.empty?

      new_owner = family.users.where.not(id: id)
                        .find_by(role: %w[admin super_admin]) ||
                  family.users.where.not(id: id)
                        .order(:created_at).first

      return unless new_owner

      Account.where(id: account_ids).update_all(owner_id: new_owner.id)
      # Remove shares the new owner had for these accounts (they now own them)
      AccountShare.where(account_id: account_ids, user_id: new_owner.id).delete_all
    end

    def deactivated_email
      email.gsub(/@/, "-deactivated-#{SecureRandom.uuid}@")
    end

    def profile_image_size
      if profile_image.attached? && profile_image.byte_size > 10.megabytes
        errors.add(:profile_image, :invalid_file_size, max_megabytes: 10)
      end
    end

    def totp
      ROTP::TOTP.new(otp_secret, issuer: "Sure Finances")
    end

    # Two requests carrying the same code can both pass verify before either
    # records it; the conditional update lets only one of them through. The
    # otp_secret match drops a claim verified against a secret that was
    # replaced (disable + re-setup) in the meantime, so it cannot mark a time
    # step as used on the newly enrolled factor.
    def claim_otp_time_step!(time_step)
      used_at = Time.zone.at(time_step)
      claimed = self.class.where(id: id, otp_secret: otp_secret)
        .where("otp_last_used_at IS NULL OR otp_last_used_at < ?", used_at)
        .update_all(otp_last_used_at: used_at) == 1

      if claimed
        # Already written by update_all; keep the record clean so a later
        # with_lock or update! sees it as persisted.
        self.otp_last_used_at = used_at
        clear_attribute_changes([ :otp_last_used_at ])
      end
      claimed
    end

    def consume_backup_code!(normalized_code)
      consumed = false

      transaction do
        lock!

        if otp_backup_codes.present?
          matching_index = otp_backup_codes.index do |stored_code|
            backup_code_matches?(stored_code, normalized_code)
          end

          if matching_index
            remaining_codes = otp_backup_codes.dup
            remaining_codes.delete_at(matching_index)
            update!(otp_backup_codes: remaining_codes)
            consumed = true
          end
        end
      end

      consumed
    end

    def generate_backup_codes
      MFA_BACKUP_CODE_COUNT.times.map { SecureRandom.hex(8) }
    end

    def digest_backup_code(code)
      BCrypt::Password.create(normalize_mfa_code(code), cost: backup_code_digest_cost).to_s
    end

    def backup_code_matches?(stored_code, normalized_code)
      if backup_code_digest?(stored_code)
        return false unless backup_code_input?(normalized_code)

        BCrypt::Password.new(stored_code).is_password?(normalized_code)
      else
        # Legacy plaintext codes are accepted once so existing MFA users are
        # not locked out after backup-code hashing ships.
        ActiveSupport::SecurityUtils.secure_compare(stored_code.to_s, normalized_code)
      end
    rescue BCrypt::Errors::InvalidHash
      false
    end

    def backup_code_digest?(stored_code)
      stored_code.to_s.start_with?("$2a$", "$2b$", "$2y$")
    end

    def normalize_mfa_code(code)
      code.to_s.strip.downcase
    end

    def backup_code_input?(code)
      backup_code_candidate?(code) || legacy_plaintext_backup_code_candidate?(code)
    end

    def backup_code_candidate?(code)
      code.to_s.match?(/\A[0-9a-f]{16}\z/)
    end

    def legacy_plaintext_backup_code_candidate?(code)
      code.to_s.match?(/\A[0-9a-f]{8}\z/)
    end

    def backup_code_digest_cost
      ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
    end
end