Class: Nobi::TimestampSigner

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

Constant Summary collapse

EPOCH =

2011/01/01 in UTC

1293840000

Instance Method Summary collapse

Methods inherited from Signer

#derive_key, #initialize, #signature

Constructor Details

This class inherits a constructor from Nobi::Signer

Instance Method Details

#get_timestampObject



114
115
116
# File 'lib/nobi.rb', line 114

def get_timestamp
  Time.now.utc.to_f - EPOCH
end

#sign(value) ⇒ Object



122
123
124
125
126
127
# File 'lib/nobi.rb', line 122

def sign(value)
  timestamp = Utils.base64_encode(Utils.int_to_bytes(get_timestamp.to_i))
  value = '%s%s%s' % [value, @sep, timestamp]

  '%s%s%s' % [value, @sep, signature(value)]
end

#timestamp_to_datetime(ts) ⇒ Object



118
119
120
# File 'lib/nobi.rb', line 118

def timestamp_to_datetime(ts)
  Time.at(ts + EPOCH).utc
end

#unsign(value, max_age: nil, return_timestamp: nil) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/nobi.rb', line 129

def unsign(value, max_age: nil, return_timestamp: nil)
  sig_error = nil
  result = ''

  begin
    result = super(value)
  rescue BadSignature => e
    sig_error = e
  end

  if not result.include?(@sep)
    if sig_error
      raise sig_error
    else
      raise BadTimeSignature, 'timestamp missing'
    end
  end

  value, timestamp = Utils.rsplit(result, @sep)

  timestamp = Utils.bytes_to_int(Utils.base64_decode(timestamp))

  if max_age
    age = get_timestamp - timestamp

    if age > max_age
      raise SignatureExpired, 'Signature age %s > %s seconds' % [age, max_age]
    end
  end

  if return_timestamp
    return value, timestamp_to_datetime(timestamp)
  else
    return value
  end
end