class OpenSesame::Token

Used for generating time-sensitive, cryptographically secure authorization tokens.

Public Class Methods

generate(secret = @@default_secret, timestamp = Time.now.utc.to_datetime) click to toggle source

Generate a token, which will automatically expire after one hour.

@param [String] secret The shared secret, which should only be known by the

sender and the receiver.

@param [DateTime] timestamp Expire the token automatically one hour from this time.

Defaults to now.

@return [String] The token.

# File lib/open-sesame.rb, line 18
def self.generate(secret = @@default_secret, timestamp = Time.now.utc.to_datetime)
  timestamp_string = timestamp.strftime('%Y%m%dT%H%M')
  hash = (Digest::SHA1.new << secret + timestamp_string).to_s
  timestamp_string + '-' + hash
end
verify(token, secret = @@default_secret) click to toggle source

Verify a token.

@param [String] token The token. @param [String] secret The shared secret.

# File lib/open-sesame.rb, line 28
def self.verify(token, secret = @@default_secret)
  string = token.split /-/
  timestamp = DateTime.strptime string.first, '%Y%m%dT%H%M'
  one_hour_ago = (Time.now.utc - 3600).to_datetime
  (timestamp >= one_hour_ago) && token.eql?(generate(secret, timestamp))
end