Sha256: d0fd084c4322017a17c0ea019b14ffb0255bc56b33f85f0654dea078f0474045

Contents?: true

Size: 1.8 KB

Versions: 11

Compression:

Stored size: 1.8 KB

Contents

# frozen_string_literal: true

module QuoVadis
  class Password < ActiveRecord::Base
    belongs_to :account

    has_secure_password

    validates_length_of :password, minimum: QuoVadis.password_minimum_length, allow_blank: true
    validate :password_updated_legitimately, on: :update

    attr_accessor :new_password


    def change(current_plaintext, new_plaintext, new_plaintext_confirmation)
      unless authenticate current_plaintext
        errors.add :password, :incorrect
        return false
      end

      # has_secure_password ignores empty passwords ("") on update so reject them here.
      if new_plaintext.empty?
        errors.add :new_password, :blank
        return false
      end

      self.password = new_plaintext
      self.password_confirmation = new_plaintext_confirmation

      if save
        true
      else
        errors.delete(:password)&.each { |e| errors.add :new_password, e }
        errors.delete(:password_confirmation)&.each { |e| errors.add :new_password_confirmation, e }
        false
      end
    end


    def reset(new_plaintext, new_plaintext_confirmation)
      # has_secure_password ignores empty passwords ("") on update so reject them here.
      if new_plaintext.empty?
        errors.add :password, :blank
        return false
      end

      self.password = new_plaintext
      self.password_confirmation = new_plaintext_confirmation
      save
    end

    private

    def password_updated_legitimately
      return unless password_digest_changed?

      unless change_or_reset_called?
        errors.add :password, 'must be updated via #change or #reset'
      end
    end

    def change_or_reset_called?
      caller_locations.any? { |loc|
        ['change', 'reset'].include?(loc.label) && Pathname.new(loc.path).basename.to_s == 'password.rb'
      }
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
quo_vadis-2.1.11 app/models/quo_vadis/password.rb
quo_vadis-2.1.10 app/models/quo_vadis/password.rb
quo_vadis-2.1.9 app/models/quo_vadis/password.rb
quo_vadis-2.1.8 app/models/quo_vadis/password.rb
quo_vadis-2.1.7 app/models/quo_vadis/password.rb
quo_vadis-2.1.6 app/models/quo_vadis/password.rb
quo_vadis-2.1.5 app/models/quo_vadis/password.rb
quo_vadis-2.1.4 app/models/quo_vadis/password.rb
quo_vadis-2.1.3 app/models/quo_vadis/password.rb
quo_vadis-2.1.2 app/models/quo_vadis/password.rb
quo_vadis-2.1.1 app/models/quo_vadis/password.rb