Class: OnetimeToken::Token

Inherits:
Object
  • Object
show all
Defined in:
lib/onetime_token/token.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model_class, name, secret) ⇒ Token

Returns a new instance of Token.



28
29
30
31
32
# File 'lib/onetime_token/token.rb', line 28

def initialize(model_class, name, secret)
  @model_class = model_class
  @name        = name
  @secret      = secret
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/onetime_token/token.rb', line 3

def name
  @name
end

#secretObject (readonly)

Returns the value of attribute secret.



3
4
5
# File 'lib/onetime_token/token.rb', line 3

def secret
  @secret
end

Class Method Details

.generate_for(model, name, options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/onetime_token/token.rb', line 6

def generate_for(model, name, options={})
  redis = OnetimeToken.redis_pool

  token = nil
  while token.nil? || redis.exists(token.key)
    secret = SecureRandom.urlsafe_base64(15)
    token = new(model.class, name, secret)
  end

  properties = (options[:properties] || {})
  properties[:id] = model.id

  redis.pipelined do
    redis.set token.key, JSON.dump(properties)
    expires_in = (options[:expires_in] || 3600 * 24 * 60)
    redis.expire token.key, expires_in
  end

  token
end

Instance Method Details

#expireObject



34
35
36
# File 'lib/onetime_token/token.rb', line 34

def expire
  OnetimeToken.redis_pool.del key
end

#keyObject



51
52
53
# File 'lib/onetime_token/token.rb', line 51

def key
  @key ||= "#{@model_class.name.downcase}_#{@name}/#{@secret}"
end

#model_idObject



47
48
49
# File 'lib/onetime_token/token.rb', line 47

def model_id
  properties[:id]
end

#propertiesObject



38
39
40
41
42
43
44
45
# File 'lib/onetime_token/token.rb', line 38

def properties
  @properties ||=
    if serialized_value = OnetimeToken.redis_pool.get(key)
      JSON.parse(serialized_value, symbolize_names: true)
    else
      {}
    end
end