BigW Consortium Gitlab

key.rb 2.02 KB
Newer Older
1 2 3 4
# == Schema Information
#
# Table name: keys
#
Dmitriy Zaporozhets committed
5 6
#  id          :integer          not null, primary key
#  user_id     :integer
Dmitriy Zaporozhets committed
7 8
#  created_at  :datetime
#  updated_at  :datetime
Dmitriy Zaporozhets committed
9 10 11 12
#  key         :text
#  title       :string(255)
#  type        :string(255)
#  fingerprint :string(255)
13 14
#

miks committed
15 16
require 'digest/md5'

gitlabhq committed
17
class Key < ActiveRecord::Base
18
  include Sortable
19 20
  include Gitlab::Popen

gitlabhq committed
21 22
  belongs_to :user

Steven Burgart committed
23
  before_validation :strip_white_space, :generate_fingerprint
Andrey Kumanyaev committed
24

25
  validates :title, presence: true, length: { within: 0..255 }
Akiva Levy committed
26
  validates :key, presence: true, length: { within: 0..5000 }, format: { with: /\A(ssh|ecdsa)-.*\Z/ }, uniqueness: true
27
  validates :fingerprint, uniqueness: true, presence: { message: 'cannot be generated' }
gitlabhq committed
28

29
  delegate :name, :email, to: :user, prefix: true
miks committed
30

31 32
  after_create :add_to_shell
  after_create :notify_user
33
  after_create :post_create_hook
34
  after_destroy :remove_from_shell
35
  after_destroy :post_destroy_hook
36

miks committed
37
  def strip_white_space
38
    self.key = key.strip unless key.blank?
miks committed
39 40
  end

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

46
  def shell_id
47
    "key-#{id}"
48
  end
49

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

  def notify_user
    NotificationService.new.new_key(self)
  end

62 63 64 65
  def post_create_hook
    SystemHooksService.new.execute_hooks_for(self, :create)
  end

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

74 75 76 77
  def post_destroy_hook
    SystemHooksService.new.execute_hooks_for(self, :destroy)
  end

78 79
  private

Steven Burgart committed
80
  def generate_fingerprint
81 82 83
    self.fingerprint = nil
    return unless key.present?

84 85
    cmd_status = 0
    cmd_output = ''
86
    Tempfile.open('gitlab_key_file') do |file|
87 88
      file.puts key
      file.rewind
89
      cmd_output, cmd_status = popen(%W(ssh-keygen -lf #{file.path}), '/tmp')
90 91 92
    end

    if cmd_status.zero?
93
      cmd_output.gsub /(\h{2}:)+\h{2}/ do |match|
94 95 96 97
        self.fingerprint = match
      end
    end
  end
gitlabhq committed
98
end