gitlab-org--gitlab-foss/app/models/gpg_key.rb

56 lines
1.2 KiB
Ruby
Raw Normal View History

2017-02-22 11:49:17 +00:00
class GpgKey < ActiveRecord::Base
2017-02-28 09:49:59 +00:00
include AfterCommitQueue
2017-02-22 11:49:17 +00:00
KEY_PREFIX = '-----BEGIN PGP PUBLIC KEY BLOCK-----'.freeze
belongs_to :user
validates :key,
presence: true,
uniqueness: true,
format: {
with: /\A#{KEY_PREFIX}((?!#{KEY_PREFIX}).)+\Z/m,
message: "is invalid. A valid public GPG key begins with '#{KEY_PREFIX}'"
2017-02-22 11:49:17 +00:00
}
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) }
2017-02-22 11:49:17 +00:00
before_validation :extract_fingerprint
2017-02-28 09:49:59 +00:00
after_create :notify_user
2017-02-22 11:49:17 +00:00
def key=(value)
value.strip! unless value.blank?
write_attribute(:key, value)
end
2017-02-22 14:37:49 +00:00
def emails
@emails ||= Gitlab::Gpg.emails_from_key(key)
2017-02-22 14:37:49 +00:00
end
def emails_with_verified_status
emails.map do |email|
2017-02-24 20:28:26 +00:00
[
email,
2017-06-12 14:16:33 +00:00
email == user.email
2017-02-24 20:28:26 +00:00
]
end
end
2017-02-22 11:49:17 +00:00
private
def extract_fingerprint
# we can assume that the result only contains one item as the validation
# only allows one key
2017-02-22 16:20:42 +00:00
self.fingerprint = Gitlab::Gpg.fingerprints_from_key(key).first
2017-02-22 11:49:17 +00:00
end
2017-02-28 09:49:59 +00:00
def notify_user
run_after_commit { NotificationService.new.new_gpg_key(self) }
end
2017-02-22 11:49:17 +00:00
end