BigW Consortium Gitlab

token_authenticatable.rb 1.01 KB
Newer Older
1 2 3
module TokenAuthenticatable
  extend ActiveSupport::Concern

4 5 6
  class_methods do
    def authentication_token_fields
      @token_fields || []
7 8
    end

9 10 11 12 13
    private

    def add_authentication_token_field(token_field)
      @token_fields = [] unless @token_fields
      @token_fields << token_field
14

15
      define_singleton_method("find_by_#{token_field}") do |token|
16
        find_by(token_field => token) if token
17 18 19
      end

      define_method("ensure_#{token_field}") do
20 21 22 23 24 25
        current_token = read_attribute(token_field)
        if current_token.blank?
          write_attribute(token_field, generate_token_for(token_field))
        else
          current_token
        end
26 27 28 29
      end

      define_method("reset_#{token_field}!") do
        write_attribute(token_field, generate_token_for(token_field))
30
        save!
31 32
      end
    end
33 34 35 36
  end

  private

37
  def generate_token_for(token_field)
38 39
    loop do
      token = Devise.friendly_token
40
      break token unless self.class.unscoped.find_by(token_field => token)
41 42 43
    end
  end
end