BigW Consortium Gitlab

key.rb 1.84 KB
Newer Older
miks committed
1 2
require 'digest/md5'

gitlabhq committed
3
class Key < ActiveRecord::Base
4
  include AfterCommitQueue
5
  include Sortable
6

gitlabhq committed
7 8
  belongs_to :user

9
  before_validation :generate_fingerprint
Andrey Kumanyaev committed
10

11 12 13 14 15 16 17 18 19 20 21 22
  validates :title,
    presence: true,
    length: { maximum: 255 }
  validates :key,
    presence: true,
    length: { maximum: 5000 },
    format: { with: /\A(ssh|ecdsa)-.*\Z/ }
  validates :key,
    format: { without: /\n|\r/, message: 'should be a single line' }
  validates :fingerprint,
    uniqueness: true,
    presence: { message: 'cannot be generated' }
gitlabhq committed
23

24
  delegate :name, :email, to: :user, prefix: true
miks committed
25

26 27
  after_create :add_to_shell
  after_create :notify_user
28
  after_create :post_create_hook
29
  after_destroy :remove_from_shell
30
  after_destroy :post_destroy_hook
31

32 33 34
  def key=(value)
    value.strip! unless value.blank?
    write_attribute(:key, value)
miks committed
35 36
  end

37
  def publishable_key
38 39 40
    # Strip out the keys comment so we don't leak email addresses
    # Replace with simple ident of user_name (hostname)
    self.key.split[0..1].push("#{self.user_name} (#{Gitlab.config.gitlab.host})").join(' ')
41 42
  end

43
  # projects that has this key
gitlabhq committed
44
  def projects
45
    user.authorized_projects
gitlabhq committed
46
  end
47

48
  def shell_id
49
    "key-#{id}"
50
  end
51

52 53 54 55 56 57 58 59 60
  def add_to_shell
    GitlabShellWorker.perform_async(
      :add_key,
      shell_id,
      key
    )
  end

  def notify_user
61
    run_after_commit { NotificationService.new.new_key(self) }
62 63
  end

64 65 66 67
  def post_create_hook
    SystemHooksService.new.execute_hooks_for(self, :create)
  end

68 69 70 71 72 73 74 75
  def remove_from_shell
    GitlabShellWorker.perform_async(
      :remove_key,
      shell_id,
      key,
    )
  end

76 77 78 79
  def post_destroy_hook
    SystemHooksService.new.execute_hooks_for(self, :destroy)
  end

80 81
  private

Steven Burgart committed
82
  def generate_fingerprint
83
    self.fingerprint = nil
84 85 86 87

    return unless self.key.present?

    self.fingerprint = Gitlab::KeyFingerprint.new(self.key).fingerprint
88
  end
gitlabhq committed
89
end