BigW Consortium Gitlab

key.rb 1.81 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
  validates :title, presence: true, length: { within: 0..255 }
12
  validates :key, presence: true, length: { within: 0..5000 }, format: { with: /\A(ssh|ecdsa)-.*\Z/ }
13
  validates :key, format: { without: /\n|\r/, message: 'should be a single line' }
14
  validates :fingerprint, uniqueness: true, presence: { message: 'cannot be generated' }
gitlabhq committed
15

16
  delegate :name, :email, to: :user, prefix: true
miks committed
17

18 19
  after_create :add_to_shell
  after_create :notify_user
20
  after_create :post_create_hook
21
  after_destroy :remove_from_shell
22
  after_destroy :post_destroy_hook
23

24 25 26
  def key=(value)
    value.strip! unless value.blank?
    write_attribute(:key, value)
miks committed
27 28
  end

29
  def publishable_key
30 31 32
    # 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(' ')
33 34
  end

35
  # projects that has this key
gitlabhq committed
36
  def projects
37
    user.authorized_projects
gitlabhq committed
38
  end
39

40
  def shell_id
41
    "key-#{id}"
42
  end
43

44 45 46 47 48 49 50 51 52
  def add_to_shell
    GitlabShellWorker.perform_async(
      :add_key,
      shell_id,
      key
    )
  end

  def notify_user
53
    run_after_commit { NotificationService.new.new_key(self) }
54 55
  end

56 57 58 59
  def post_create_hook
    SystemHooksService.new.execute_hooks_for(self, :create)
  end

60 61 62 63 64 65 66 67
  def remove_from_shell
    GitlabShellWorker.perform_async(
      :remove_key,
      shell_id,
      key,
    )
  end

68 69 70 71
  def post_destroy_hook
    SystemHooksService.new.execute_hooks_for(self, :destroy)
  end

72 73
  private

Steven Burgart committed
74
  def generate_fingerprint
75
    self.fingerprint = nil
76 77 78 79

    return unless self.key.present?

    self.fingerprint = Gitlab::KeyFingerprint.new(self.key).fingerprint
80
  end
gitlabhq committed
81
end