class MortalToken::Token

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

Attributes

expires[R]

The expiry time as a Unix timestamp

message[R]

String content of token (optional)

salt[R]

The salt value

Public Class Methods

new(expires, salt, message = nil) click to toggle source

Initialize an existing token

# 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

Public Instance Methods

==(other_token_or_digest) click to toggle source

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

# 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
Also aliased as: ===
===(other_token_or_digest)
Alias for: ==
digest() click to toggle source

Returns HMAC hexdigest of the token

# 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_s() click to toggle source

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

# File lib/mortal-token/token.rb, line 39
def to_s
  h = to_h
  h[:digest] = digest
  Base64.urlsafe_encode64 h.to_json
end
ttl() click to toggle source

Number of seconds remaining

# File lib/mortal-token/token.rb, line 52
def ttl
  expires - Time.now.utc.to_i
end

Private Instance Methods

to_h() click to toggle source
# File lib/mortal-token/token.rb, line 66
def to_h
  {salt: salt, expires: expires, message: message}
end