BigW Consortium Gitlab

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

4 5 6
  private

  def write_new_token(token_field)
7
    new_token = generate_available_token(token_field)
8 9 10
    write_attribute(token_field, new_token)
  end

11
  def generate_available_token(token_field)
12
    loop do
13
      token = generate_token(token_field)
14 15 16 17
      break token unless self.class.unscoped.find_by(token_field => token)
    end
  end

18 19 20 21
  def generate_token(token_field)
    Devise.friendly_token
  end

22 23 24
  class_methods do
    def authentication_token_fields
      @token_fields || []
25 26
    end

27
    private # rubocop:disable Lint/UselessAccessModifier
28 29 30 31

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

33
      define_singleton_method("find_by_#{token_field}") do |token|
34
        find_by(token_field => token) if token
35 36 37
      end

      define_method("ensure_#{token_field}") do
38 39 40 41 42
        current_token = read_attribute(token_field)
        current_token.blank? ? write_new_token(token_field) : current_token
      end

      define_method("ensure_#{token_field}!") do
43 44
        send("reset_#{token_field}!") if read_attribute(token_field).blank?
        read_attribute(token_field)
45 46 47
      end

      define_method("reset_#{token_field}!") do
48
        write_new_token(token_field)
49
        save!
50 51
      end
    end
52 53
  end
end