Module: SafeToken

Defined in:
lib/vex/base/safe_token.rb

Defined Under Namespace

Modules: Etest Classes: InvalidToken, TokenExpired, TokenTooLong

Constant Summary collapse

CipherError =
if defined?(OpenSSL::Cipher::CipherError)
  OpenSSL::Cipher::CipherError
else
  OpenSSL::CipherError
end

Class Method Summary collapse

Class Method Details

.generate(data, opts = {}) ⇒ Object


67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/vex/base/safe_token.rb', line 67

def self.generate(data, opts = {})
  opts = DEFAULTS.dup.update(opts)
  expires = opts[:expires].to_i if opts[:expires]
  
  data = data.to_json
  
  hash = hash!(opts, "#{opts[:secret]}-#{expires}:#{data}")
  s = "sha1:#{hash}:#{expires}:#{data}"

  s = aes(:encrypt, s, opts)
  s = encode64(s)
  limit!(s, opts)
end

.validate(s, opts = {}) ⇒ Object

Raises:


81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/vex/base/safe_token.rb', line 81

def self.validate(s, opts = {})
  opts = DEFAULTS.dup.update(opts)

  begin
    s = decode64(s)
    s = aes(:decrypt, s, opts)
  rescue SafeToken::CipherError
    raise InvalidToken, "Invalid token encryption: #{$!}"
  end

  raise InvalidToken, "Invalid token syntax" unless s =~ /^([^:]*):([^:]*):([^:]*):(.*)/

  method, hash, expires, data = $1, $2, $3, $4

  unless hash!(opts, "#{opts[:secret]}-#{expires}:#{data}") == hash
    raise InvalidToken, "Invalid token #{s}"
  end
  
  if !expires.empty?
    expires = Time.at(expires.to_i)
    raise TokenExpired, expires if expires < Time.now      
  end
  
  JSON.parse(data)
end