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, Error, ExpiredTokenError, VersionError

Constant Summary collapse

VERSION =
'1.0.3'

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



50
51
52
# File 'lib/branca.rb', line 50

def configure
  yield self if block_given?
end

.decode(token, ttl: self.ttl, secret_key: self.secret_key) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/branca.rb', line 27

def decode(token, ttl: self.ttl, secret_key: self.secret_key)
  header, bytes = token_explode(token)
  version, timestamp, nonce = header_explode(header)

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

  cipher = create_cipher(secret_key)
  message = cipher.decrypt(nonce, bytes.pack('C*'), header.pack('C*'))
rescue RbNaCl::CryptoError
  raise DecodeError
else
  Decoder.new(message, Time.at(timestamp).utc)
end

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



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

def encode(message, timestamp = Time.now.utc, secret_key: self.secret_key)
  cipher = create_cipher(secret_key)
  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