Class: MortalToken::Token

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

Overview

Create a token and check if it’s still valid:

token = MortalToken.create(300) # 5 min
give_to_client token.to_s
token_str = get_from_client
MoralToken.valid? token_str

Create a message token. The client will be able to read the message, but they *won’t* be able to tamper with it. If your message must aslo be read-proof, you’ll have to encrypt it and decrypt it yourself.

token = MortalToken.create(300, "message")
give_to_client token.to_s
token_str = get_from_client
token, digest = MortalToken.recover token_str
if token == digest
  # It's valid
  do_stuff_with token.message
else
  # The token was invalid or expired
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expires, salt, message = nil) ⇒ Token

Initialize an existing token



32
33
34
35
36
# File 'lib/mortal-token/token.rb', line 32

def initialize(expires, salt, message = nil)
  @expires = expires.to_i
  @salt = salt
  @message = message ? message.to_s : nil
end

Instance Attribute Details

#expiresObject (readonly)

The expiry time as a Unix timestamp



25
26
27
# File 'lib/mortal-token/token.rb', line 25

def expires
  @expires
end

#messageObject (readonly)

String content of token (optional)



27
28
29
# File 'lib/mortal-token/token.rb', line 27

def message
  @message
end

#saltObject (readonly)

The salt value



29
30
31
# File 'lib/mortal-token/token.rb', line 29

def salt
  @salt
end

Instance Method Details

#==(other_token_or_digest) ⇒ Object Also known as: ===

Tests this token against another token or token hash. Even if it matches, returns false if the expire time is past.



57
58
59
60
# File 'lib/mortal-token/token.rb', line 57

def ==(other_token_or_digest)
  other = other_token_or_digest.respond_to?(:digest) ? other_token_or_digest.digest : other_token_or_digest
  self.digest == other && self.ttl > 0
end

#digestObject

Returns HMAC hexdigest of the token



46
47
48
49
# File 'lib/mortal-token/token.rb', line 46

def digest
  raise "MortalToken: you must set a secret!" if MortalToken.secret.nil?
  @digest ||= OpenSSL::HMAC.hexdigest(MortalToken.digest, MortalToken.secret, to_h.to_json)
end

#to_sObject

Returns a URL-safe encoding of the token and its digest. Hand it out to users and check it with MoralToken.valid?



39
40
41
42
43
# File 'lib/mortal-token/token.rb', line 39

def to_s
  h = to_h
  h[:digest] = digest
  Base64.urlsafe_encode64 h.to_json
end

#ttlObject

Number of seconds remaining



52
53
54
# File 'lib/mortal-token/token.rb', line 52

def ttl
  expires - Time.now.utc.to_i
end