Module: Branca

Defined in:
lib/branca.rb,
lib/branca/decoder.rb,
lib/branca/version.rb,
lib/branca/exceptions.rb

Defined Under Namespace

Classes: DecodeError, Decoder, ExpiredTokenError, VersionError

Constant Summary collapse

VERSION =
'1.0.1'

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.secret_keyObject

Returns the value of attribute secret_key.



14
15
16
# File 'lib/branca.rb', line 14

def secret_key
  @secret_key
end

.ttlObject

Returns the value of attribute ttl.



14
15
16
# File 'lib/branca.rb', line 14

def ttl
  @ttl
end

Class Method Details

.configure {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:

  • _self (Branca)

    the object that the method was called on



45
46
47
# File 'lib/branca.rb', line 45

def configure
  yield self if block_given?
end

.decode(token) ⇒ Object

Raises:



26
27
28
29
30
31
32
33
34
35
# File 'lib/branca.rb', line 26

def decode(token)
  header, bytes = token_explode(token)
  version, timestamp, nonce = header_explode(header)

  raise VersionError unless version == VERSION
  raise ExpiredTokenError if (timestamp + Branca.ttl) < Time.now.utc.to_i

  message = cipher.decrypt(nonce, bytes.pack('C*'), header.pack('C*'))
  Decoder.new(message, Time.at(timestamp).utc)
end

.encode(message, timestamp = Time.now.utc) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/branca.rb', line 16

def encode(message, timestamp = Time.now.utc)
  nonce = RbNaCl::Random.random_bytes(cipher.nonce_bytes)

  header = [VERSION, timestamp.to_i].pack('C N') + nonce
  ciphertext = cipher.encrypt(nonce, message, header)
  raw_token = header + ciphertext

  BaseX::Base62.encode(raw_token)
end