Class: Slosilo::Adapters::SequelAdapter

Inherits:
AbstractAdapter show all
Defined in:
lib/slosilo/adapters/sequel_adapter.rb

Defined Under Namespace

Modules: Migration

Instance Method Summary collapse

Instance Method Details

#create_modelObject



14
15
16
17
18
19
# File 'lib/slosilo/adapters/sequel_adapter.rb', line 14

def create_model
  model = Sequel::Model(:slosilo_keystore)
  model.unrestrict_primary_key
  model.attr_encrypted(:key, aad: :id) if secure?
  model
end

#eachObject



46
47
48
49
50
# File 'lib/slosilo/adapters/sequel_adapter.rb', line 46

def each
  model.each do |m|
    yield m.id, Slosilo::Key.new(m.key)
  end
end

#get_by_fingerprint(fp) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/slosilo/adapters/sequel_adapter.rb', line 35

def get_by_fingerprint fp
  if fingerprint_in_db?
    stored = model[fingerprint: fp]
    return nil unless stored
    [Slosilo::Key.new(stored.key), stored.id]
  else
    warn "Please migrate to a new database schema using rake slosilo:migrate for efficient fingerprint lookups"
    find_by_fingerprint fp
  end
end

#get_key(id) ⇒ Object



29
30
31
32
33
# File 'lib/slosilo/adapters/sequel_adapter.rb', line 29

def get_key id
  stored = model[id]
  return nil unless stored
  Slosilo::Key.new stored.key
end

#migrate!Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/slosilo/adapters/sequel_adapter.rb', line 63

def migrate!
  unless fingerprint_in_db?
    model.db.transaction do
      model.db.alter_table :slosilo_keystore do
        add_column :fingerprint, String
      end

      # reload the schema
      model.set_dataset model.dataset

      recalculate_fingerprints

      model.db.alter_table :slosilo_keystore do
        set_column_not_null :fingerprint
        add_unique_constraint :fingerprint
      end
    end
  end
end

#modelObject



6
7
8
# File 'lib/slosilo/adapters/sequel_adapter.rb', line 6

def model
  @model ||= create_model
end

#put_key(id, value) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/slosilo/adapters/sequel_adapter.rb', line 21

def put_key id, value
  fail Error::InsecureKeyStorage unless secure? || !value.private?

  attrs = { id: id, key: value.to_der }
  attrs[:fingerprint] = value.fingerprint if fingerprint_in_db?
  model.create attrs
end

#recalculate_fingerprintsObject



52
53
54
55
56
57
58
59
60
# File 'lib/slosilo/adapters/sequel_adapter.rb', line 52

def recalculate_fingerprints
  # Use a transaction to ensure that all fingerprints are updated together. If any update fails,
  # we want to rollback all updates.
  model.db.transaction do
    model.each do |m|
      m.update fingerprint: Slosilo::Key.new(m.key).fingerprint
    end
  end
end

#secure?Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/slosilo/adapters/sequel_adapter.rb', line 10

def secure?
  !Slosilo.encryption_key.nil?
end