Read about our upcoming Code of Conduct on this issue

This instance was upgraded to Heptapod 0.28.0 today

base.rb 2.13 KB
Newer Older
1
2
3
4
# frozen_string_literal: true

module TokenAuthenticatableStrategies
  class Base
5
6
    attr_reader :klass, :token_field, :options

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    def initialize(klass, token_field, options)
      @klass = klass
      @token_field = token_field
      @options = options
    end

    def find_token_authenticatable(instance, unscoped = false)
      raise NotImplementedError
    end

    def get_token(instance)
      raise NotImplementedError
    end

    def set_token(instance)
      raise NotImplementedError
    end

    def ensure_token(instance)
      write_new_token(instance) unless token_set?(instance)
27
      get_token(instance)
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    end

    # Returns a token, but only saves when the database is in read & write mode
    def ensure_token!(instance)
      reset_token!(instance) unless token_set?(instance)
      get_token(instance)
    end

    # Resets the token, but only saves when the database is in read & write mode
    def reset_token!(instance)
      write_new_token(instance)
      instance.save! if Gitlab::Database.read_write?
    end

42
    def self.fabricate(model, field, options)
43
      if options[:digest] && options[:encrypted]
44
        raise ArgumentError, _('Incompatible options set!')
45
46
      end

47
      if options[:digest]
48
        TokenAuthenticatableStrategies::Digest.new(model, field, options)
49
      elsif options[:encrypted]
50
        TokenAuthenticatableStrategies::Encrypted.new(model, field, options)
51
      else
52
        TokenAuthenticatableStrategies::Insecure.new(model, field, options)
53
54
55
      end
    end

56
57
58
59
60
61
62
    protected

    def write_new_token(instance)
      new_token = generate_available_token
      set_token(instance, new_token)
    end

63
64
65
66
    def unique
      @options.fetch(:unique, true)
    end

67
68
69
    def generate_available_token
      loop do
        token = generate_token
70
        break token unless unique && find_token_authenticatable(token, true)
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
      end
    end

    def generate_token
      @options[:token_generator] ? @options[:token_generator].call : Devise.friendly_token
    end

    def relation(unscoped)
      unscoped ? @klass.unscoped : @klass
    end

    def token_set?(instance)
      raise NotImplementedError
    end
  end
end