Class: Macaroons::BinarySerializer

Inherits:
BaseSerializer show all
Defined in:
lib/macaroons/serializers/binary.rb

Constant Summary collapse

PACKET_PREFIX_LENGTH =
4

Instance Method Summary collapse

Instance Method Details

#deserialize(serialized) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/macaroons/serializers/binary.rb', line 29

def deserialize(serialized)
  caveats = []
  decoded = base64_url_decode(serialized)

  index = 0

  while index < decoded.length
    packet_length = decoded[index..(index + PACKET_PREFIX_LENGTH - 1)].to_i(16)
    stripped_packet = decoded[index + PACKET_PREFIX_LENGTH..(index + packet_length - 2)]

    key, value = depacketize(stripped_packet)

    case key
    when 'location'
      location = value
    when 'identifier'
      identifier = value
    when 'cid'
      caveats << Caveat.new(value)
    when 'vid'
      caveats[-1].verification_id = value
    when 'cl'
      caveats[-1].caveat_location = value
    when 'signature'
      signature = value
    else
      raise KeyError, 'Invalid key in binary macaroon. Macaroon may be corrupted.'
    end

    index = index + packet_length
  end
  macaroon = Macaroons::RawMacaroon.new(key: 'no_key', identifier: identifier, location: location)
  macaroon.caveats = caveats
  macaroon.signature = signature
  macaroon
end

#serialize(macaroon) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/macaroons/serializers/binary.rb', line 9

def serialize(macaroon)
  combined = packetize('location', macaroon.location)
  combined += packetize('identifier', macaroon.identifier)

  for caveat in macaroon.caveats
    combined += packetize('cid', caveat.caveat_id)

    if caveat.verification_id and caveat.caveat_location
      combined += packetize('vid', caveat.verification_id)
      combined += packetize('cl', caveat.caveat_location)
    end
  end

  combined += packetize(
    'signature',
    Utils.unhexlify(macaroon.signature)
  )
  base64_url_encode(combined)
end