gpg_key.rb 1.18 KB
Newer Older
Alexis Reigel's avatar
Alexis Reigel committed
1
2
3
4
5
6
7
8
9
class GpgKey < ActiveRecord::Base
  KEY_PREFIX = '-----BEGIN PGP PUBLIC KEY BLOCK-----'.freeze

  belongs_to :user

  validates :key,
    presence: true,
    uniqueness: true,
    format: {
10
11
      with: /\A#{KEY_PREFIX}((?!#{KEY_PREFIX}).)+\Z/m,
      message: "is invalid. A valid public GPG key begins with '#{KEY_PREFIX}'"
Alexis Reigel's avatar
Alexis Reigel committed
12
13
    }

14
15
16
17
18
19
20
  validates :fingerprint,
    presence: true,
    uniqueness: true,
    # only validate when the `key` is valid, as we don't want the user to show
    # the error about the fingerprint
    unless: -> { errors.has_key?(:key) }

Alexis Reigel's avatar
Alexis Reigel committed
21
  before_validation :extract_fingerprint
22
23
  after_create :add_to_keychain
  after_destroy :remove_from_keychain
Alexis Reigel's avatar
Alexis Reigel committed
24
25
26
27
28
29

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

Alexis Reigel's avatar
Alexis Reigel committed
30
  def emails
Alexis Reigel's avatar
Alexis Reigel committed
31
    Gitlab::Gpg::CurrentKeyChain.emails(fingerprint)
Alexis Reigel's avatar
Alexis Reigel committed
32
33
  end

Alexis Reigel's avatar
Alexis Reigel committed
34
35
36
37
38
  private

  def extract_fingerprint
    # we can assume that the result only contains one item as the validation
    # only allows one key
39
    self.fingerprint = Gitlab::Gpg.fingerprints_from_key(key).first
Alexis Reigel's avatar
Alexis Reigel committed
40
  end
41
42
43
44
45
46
47
48

  def add_to_keychain
    Gitlab::Gpg.add_to_keychain(key)
  end

  def remove_from_keychain
    Gitlab::Gpg.remove_from_keychain(fingerprint)
  end
Alexis Reigel's avatar
Alexis Reigel committed
49
end