gpg_key.rb 1.24 KB
Newer Older
Alexis Reigel's avatar
Alexis Reigel committed
1
class GpgKey < ActiveRecord::Base
2
3
  include AfterCommitQueue

Alexis Reigel's avatar
Alexis Reigel committed
4
5
6
7
8
9
10
11
  KEY_PREFIX = '-----BEGIN PGP PUBLIC KEY BLOCK-----'.freeze

  belongs_to :user

  validates :key,
    presence: true,
    uniqueness: true,
    format: {
12
13
      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
14
15
    }

16
17
18
19
20
21
22
  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
23
  before_validation :extract_fingerprint
24
  after_create :notify_user
Alexis Reigel's avatar
Alexis Reigel committed
25
26
27
28
29
30

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

Alexis Reigel's avatar
Alexis Reigel committed
31
  def emails
32
    @emails ||= Gitlab::Gpg.emails_from_key(key)
Alexis Reigel's avatar
Alexis Reigel committed
33
34
  end

35
36
  def emails_with_verified_status
    emails.map do |email|
Alexis Reigel's avatar
Alexis Reigel committed
37
38
      [
        email,
Alexis Reigel's avatar
Alexis Reigel committed
39
        email == user.email
Alexis Reigel's avatar
Alexis Reigel committed
40
41
42
43
      ]
    end
  end

Alexis Reigel's avatar
Alexis Reigel committed
44
45
46
47
48
  private

  def extract_fingerprint
    # we can assume that the result only contains one item as the validation
    # only allows one key
49
    self.fingerprint = Gitlab::Gpg.fingerprints_from_key(key).first
Alexis Reigel's avatar
Alexis Reigel committed
50
  end
51

52
53
54
  def notify_user
    run_after_commit { NotificationService.new.new_gpg_key(self) }
  end
Alexis Reigel's avatar
Alexis Reigel committed
55
end