Class: MultiPass

Inherits:
Object
  • Object
show all
Defined in:
lib/multipass.rb

Defined Under Namespace

Classes: DecryptError, ExpiredError, Invalid, JSONError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(site_key, api_key) ⇒ MultiPass

Returns a new instance of MultiPass.



33
34
35
36
37
# File 'lib/multipass.rb', line 33

def initialize(site_key, api_key)
  @site_key   = site_key
  @api_key    = api_key
  @crypto_key = EzCrypto::Key.with_password(@site_key, @api_key)
end

Class Method Details

.decode(site_key, api_key, data) ⇒ Object



29
30
31
# File 'lib/multipass.rb', line 29

def self.decode(site_key, api_key, data)
  new(site_key, api_key).decode(data)
end

.encode(site_key, api_key, options = {}) ⇒ Object



25
26
27
# File 'lib/multipass.rb', line 25

def self.encode(site_key, api_key, options = {})
  new(site_key, api_key).encode(options)
end

Instance Method Details

#decode(data) ⇒ Object

Decrypts the given multipass string and parses it as JSON. Then, it checks for a valid expiration date.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/multipass.rb', line 51

def decode(data)
  json = @crypto_key.decrypt64(data)
  
  if json.nil?
    raise MultiPass::DecryptError
  end

  options = decode_json(json)
  
  if !options.is_a?(Hash)
    raise MultiPass::JSONError
  end

  options.keys.each do |key|
    options[key.to_sym] = options.delete(key)
  end

  if options[:expires].nil? || Time.now.utc > Time.parse(options[:expires])
    raise MultiPass::ExpiredError
  end

  options
rescue OpenSSL::CipherError
  raise MultiPass::DecryptError
end

#encode(options = {}) ⇒ Object

Encrypts the given hash into a multipass string.



40
41
42
43
44
45
46
47
# File 'lib/multipass.rb', line 40

def encode(options = {})
  options[:expires] = case options[:expires]
    when Fixnum               then Time.at(options[:expires]).to_s
    when Time, DateTime, Date then options[:expires].to_s
    else options[:expires].to_s
  end
  @crypto_key.encrypt64(options.to_json)
end