gpg_key.rb 737 Bytes
Newer Older
Alexis Reigel's avatar
Alexis Reigel committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class GpgKey < ActiveRecord::Base
  KEY_PREFIX = '-----BEGIN PGP PUBLIC KEY BLOCK-----'.freeze

  belongs_to :user

  validates :fingerprint,
    presence: true,
    uniqueness: true

  validates :key,
    presence: true,
    uniqueness: true,
    format: {
      with: /\A#{KEY_PREFIX}((?!#{KEY_PREFIX}).)+\Z/m
    }

  before_validation :extract_fingerprint

  def key=(value)
    value.strip! unless value.blank?
    write_attribute(:key, value)
  end

  private

  def extract_fingerprint
    import = GPGME::Key.import(key)

    return if import.considered == 0

    # we can assume that the result only contains one item as the validation
    # only allows one key
    self.fingerprint = import.imports.first.fingerprint
  end
end