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

Steven Burgart committed
9
  before_validation :strip_white_space, :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

miks committed
24
  def strip_white_space
25
    self.key = key.strip unless key.blank?
miks committed
26 27
  end

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

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

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

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

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

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

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

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

71 72
  private

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

    return unless self.key.present?

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