Module: Waylon::Storage

Defined in:
lib/waylon/storage.rb

Overview

Used for working with the Moneta store

Constant Summary collapse

DefaultStorage =
Moneta.new(
  :Redis,
  url: "redis://#{ENV.fetch("REDIS", "localhost:6379")}/2"
)

Class Method Summary collapse

Class Method Details

.adapterObject



11
12
13
# File 'lib/waylon/storage.rb', line 11

def self.adapter
  storage.adapter
end

.cipherObject



15
16
17
18
# File 'lib/waylon/storage.rb', line 15

def self.cipher
  key_bytes = RbNaCl::Hash.sha256(encryption_key)[0..31]
  RbNaCl::SimpleBox.from_secret_key(key_bytes)
end

.clearObject



20
21
22
# File 'lib/waylon/storage.rb', line 20

def self.clear
  storage.clear
end

.delete(key) ⇒ Object



24
25
26
# File 'lib/waylon/storage.rb', line 24

def self.delete(key)
  storage.delete(key)
end

.each_keyObject



28
29
30
# File 'lib/waylon/storage.rb', line 28

def self.each_key(&)
  storage.each_key(&)
end

.encryption_keyObject



32
33
34
# File 'lib/waylon/storage.rb', line 32

def self.encryption_key
  ENV.fetch("ENCRYPTION_KEY", "thisisVeryUnsafe4U")
end

.encryption_key_fingerprintObject



36
37
38
39
# File 'lib/waylon/storage.rb', line 36

def self.encryption_key_fingerprint
  base = RbNaCl::Hash.sha256(encryption_key)[0..15]
  Base64.urlsafe_encode64(RbNaCl::Hash.sha256(base)[0..7])
end

.key?(name) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/waylon/storage.rb', line 41

def self.key?(name)
  storage.key?(name)
end

.load(key) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/waylon/storage.rb', line 45

def self.load(key)
  this_cipher = cipher
  raw = storage.load(key)
  return nil unless raw

  wrapper = JSON.parse(raw)
  value = wrapper["data"]
  return nil unless value

  decoded = Base64.decode64(value)
  plain = this_cipher.decrypt(decoded)
  JSON.parse(plain)
end

.storageObject



59
60
61
# File 'lib/waylon/storage.rb', line 59

def self.storage
  @storage ||= DefaultStorage
end

.storage=(storage) ⇒ Object



63
64
65
# File 'lib/waylon/storage.rb', line 63

def self.storage=(storage)
  @storage = storage
end

.store(key, value) ⇒ Object



67
68
69
70
71
72
73
# File 'lib/waylon/storage.rb', line 67

def self.store(key, value)
  this_cipher = cipher
  encrypted = this_cipher.encrypt(value.to_json)
  encoded = Base64.encode64(encrypted)
  wrapper = { cipher: cipher.class.name, data: encoded, key: encryption_key_fingerprint }
  storage.store(key, wrapper.to_json)
end