Class: XSignature::RedisNonceValidator

Inherits:
NonceValidator show all
Defined in:
lib/x-signature/redis_nonce_validator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(redis_connection: nil, keys_prefix: 'XSignature:LastNonce:') ⇒ RedisNonceValidator

Returns a new instance of RedisNonceValidator.



8
9
10
11
# File 'lib/x-signature/redis_nonce_validator.rb', line 8

def initialize(redis_connection: nil, keys_prefix: 'XSignature:LastNonce:')
  @redis_connection = redis_connection || Redis.current
  @keys_prefix      = keys_prefix
end

Instance Attribute Details

#keys_prefixObject

Returns the value of attribute keys_prefix.



6
7
8
# File 'lib/x-signature/redis_nonce_validator.rb', line 6

def keys_prefix
  @keys_prefix
end

#redis_connectionObject

Returns the value of attribute redis_connection.



6
7
8
# File 'lib/x-signature/redis_nonce_validator.rb', line 6

def redis_connection
  @redis_connection
end

Instance Method Details

#valid?(data) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/x-signature/redis_nonce_validator.rb', line 13

def valid?(data)
  key = "#{keys_prefix}#{data.client}"
  loop do
    redis_connection.watch key do
      last_nonce = redis_connection.get(key).to_i
      if last_nonce < data.nonce
        result = redis_connection.multi do |multi|
          multi.set key, data.nonce
        end
        return true if result[0] == 'OK'
      else
        redis_connection.unwatch
        return false
      end
    end
  end
end