Class: ExpirableToken

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, extra, expire_on = nil) ⇒ ExpirableToken

Returns a new instance of ExpirableToken.



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/expirable_token.rb', line 12

def initialize(id, extra, expire_on = nil)
  @id = id
  @extra = extra
  @created_on = Time.now.to_i
  if expire_on.nil?
    @expire_on = @created_on + 86400
  else
    @expire_on = expire_on
  end
  @diff = @expire_on - @created_on
end

Instance Attribute Details

#expire_onObject (readonly)

Returns the value of attribute expire_on.



10
11
12
# File 'lib/expirable_token.rb', line 10

def expire_on
  @expire_on
end

#extraObject (readonly)

Returns the value of attribute extra.



8
9
10
# File 'lib/expirable_token.rb', line 8

def extra
  @extra
end

#idObject (readonly)

Returns the value of attribute id.



9
10
11
# File 'lib/expirable_token.rb', line 9

def id
  @id
end

Class Method Details

.from_token(token) ⇒ Object



53
54
55
56
57
# File 'lib/expirable_token.rb', line 53

def self.from_token(token)
  instance = ExpirableToken.new(nil, nil)
  instance.decode(token)
  return instance
end

Instance Method Details

#decode(token) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/expirable_token.rb', line 43

def decode(token)
  a = JSON.parse(Base64.decode64(URI::decode(token)+"==\n"))
  @id = a['0']
  @extra = a['1']
  @diff = a['2']
  @created_on = a['3']
  @expire_on = a['4']
  is_valid
end

#encodeObject



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/expirable_token.rb', line 29

def encode
  URI::encode(Base64.encode64(
    JSON.generate(
      {
        0 => @id,
        1 => @extra,
        2 => @diff,
        3 => @created_on,
        4 => @expire_on
      }
    )
  ).chomp.chomp('=').chomp('='))
end

#is_validObject



24
25
26
27
# File 'lib/expirable_token.rb', line 24

def is_valid
  today = Time.now.to_i
  !@id.nil? && (@diff = (@expire_on - @created_on)) && (@expire_on > today)
end