token_authenticatable.rb 1.5 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5
module TokenAuthenticatable
  extend ActiveSupport::Concern

6 7
  private

8
  class_methods do
9
    private # rubocop:disable Lint/UselessAccessModifier
10

11
    def add_authentication_token_field(token_field, options = {})
12
      @token_fields = [] unless @token_fields
13 14 15 16 17

      if @token_fields.include?(token_field)
        raise ArgumentError.new("#{token_field} already configured via add_authentication_token_field")
      end

18
      @token_fields << token_field
19

20 21 22 23 24 25 26 27
      attr_accessor :cleartext_tokens

      strategy = if options[:digest]
                   TokenAuthenticatableStrategies::Digest.new(self, token_field, options)
                 else
                   TokenAuthenticatableStrategies::Insecure.new(self, token_field, options)
                 end

28
      define_singleton_method("find_by_#{token_field}") do |token|
29
        strategy.find_token_authenticatable(token)
30 31
      end

32 33
      define_method(token_field) do
        strategy.get_token(self)
34 35
      end

36
      define_method("set_#{token_field}") do |token|
37 38 39 40 41
        strategy.set_token(self, token)
      end

      define_method("ensure_#{token_field}") do
        strategy.ensure_token(self)
42 43
      end

T
Toon Claes 已提交
44
      # Returns a token, but only saves when the database is in read & write mode
45
      define_method("ensure_#{token_field}!") do
46
        strategy.ensure_token!(self)
47 48
      end

T
Toon Claes 已提交
49
      # Resets the token, but only saves when the database is in read & write mode
50
      define_method("reset_#{token_field}!") do
51
        strategy.reset_token!(self)
52 53
      end
    end
54 55
  end
end