Class: OpenSesame::Token

Inherits:
Object
  • Object
show all
Defined in:
lib/open-sesame.rb

Overview

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

Constant Summary collapse

@@default_secret =

For really lazy people. You really should set your own secret phrase.

"OPEN SESAME"

Class Method Summary collapse

Class Method Details

.generate(secret = @@default_secret, timestamp = Time.now.utc.to_datetime) ⇒ String

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

Parameters:

  • secret (String) (defaults to: @@default_secret)

    The shared secret, which should only be known by the sender and the receiver.

  • timestamp (DateTime) (defaults to: Time.now.utc.to_datetime)

    Expire the token automatically one hour from this time. Defaults to now.

Returns:

  • (String)

    The token.



18
19
20
21
22
# 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) ⇒ Object

Verify a token.

Parameters:

  • token (String)

    The token.

  • secret (String) (defaults to: @@default_secret)

    The shared secret.



28
29
30
31
32
33
# 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