Class: TokenDie
- Inherits:
-
Object
- Object
- TokenDie
- Defined in:
- lib/token-die.rb,
lib/token-die/version.rb
Constant Summary collapse
- TIMESTAMP_KEY =
'___timestamp____'.freeze
- VERSION =
'0.0.3'.freeze
Instance Attribute Summary collapse
-
#encryptor ⇒ Object
readonly
Set the encryptor strategy.
-
#secret ⇒ Object
readonly
Set the encryption secret.
-
#ttl ⇒ Object
readonly
Set the token TTL Defaults 300 (5 minutes).
Instance Method Summary collapse
- #expired?(timestamp) ⇒ Boolean
- #fresh?(timestamp) ⇒ Boolean
- #generate(data = {}) ⇒ Object
-
#initialize(secret, ttl = 300, encryptor = Parsel::JSON) ⇒ TokenDie
constructor
A new instance of TokenDie.
- #recover(token) ⇒ Object
- #timestamp ⇒ Object
- #valid?(token) ⇒ Boolean
Constructor Details
#initialize(secret, ttl = 300, encryptor = Parsel::JSON) ⇒ TokenDie
Returns a new instance of TokenDie.
16 17 18 19 20 |
# File 'lib/token-die.rb', line 16 def initialize(secret, ttl = 300, encryptor = Parsel::JSON) @secret = secret @ttl = ttl @encryptor = encryptor end |
Instance Attribute Details
#encryptor ⇒ Object (readonly)
Set the encryptor strategy. Defaults Parsel::JSON
14 15 16 |
# File 'lib/token-die.rb', line 14 def encryptor @encryptor end |
#secret ⇒ Object (readonly)
Set the encryption secret
6 7 8 |
# File 'lib/token-die.rb', line 6 def secret @secret end |
#ttl ⇒ Object (readonly)
Set the token TTL Defaults 300 (5 minutes)
10 11 12 |
# File 'lib/token-die.rb', line 10 def ttl @ttl end |
Instance Method Details
#expired?(timestamp) ⇒ Boolean
46 47 48 |
# File 'lib/token-die.rb', line 46 def expired?() .to_i < (self. - ttl) end |
#fresh?(timestamp) ⇒ Boolean
50 51 52 |
# File 'lib/token-die.rb', line 50 def fresh?() !expired?() end |
#generate(data = {}) ⇒ Object
26 27 28 29 30 31 |
# File 'lib/token-die.rb', line 26 def generate(data = {}) = self. data.merge!(TIMESTAMP_KEY => ) encryptor.encrypt(secret, data) end |
#recover(token) ⇒ Object
33 34 35 36 37 38 39 40 |
# File 'lib/token-die.rb', line 33 def recover(token) data = encryptor.decrypt(secret, token) return unless data return unless fresh?(data[TIMESTAMP_KEY]) data.delete(TIMESTAMP_KEY) data end |
#timestamp ⇒ Object
22 23 24 |
# File 'lib/token-die.rb', line 22 def Time.now.utc.to_i end |
#valid?(token) ⇒ Boolean
42 43 44 |
# File 'lib/token-die.rb', line 42 def valid?(token) !recover(token).nil? end |