BigW Consortium Gitlab

key.rb 2.03 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
#  key         :text
10 11 12
#  title       :string
#  type        :string
#  fingerprint :string
Stan Hu committed
13
#  public      :boolean          default(FALSE), not null
14 15
#

miks committed
16 17
require 'digest/md5'

gitlabhq committed
18
class Key < ActiveRecord::Base
19
  include AfterCommitQueue
20
  include Sortable
21

gitlabhq committed
22 23
  belongs_to :user

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

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

31
  delegate :name, :email, to: :user, prefix: true
miks committed
32

33 34
  after_create :add_to_shell
  after_create :notify_user
35
  after_create :post_create_hook
36
  after_destroy :remove_from_shell
37
  after_destroy :post_destroy_hook
38

miks committed
39
  def strip_white_space
40
    self.key = key.strip unless key.blank?
miks committed
41 42
  end

43 44 45 46 47
  def publishable_key
    #Removes anything beyond the keytype and key itself
    self.key.split[0..1].join(' ')
  end

48
  # projects that has this key
gitlabhq committed
49
  def projects
50
    user.authorized_projects
gitlabhq committed
51
  end
52

53
  def shell_id
54
    "key-#{id}"
55
  end
56

57 58 59 60 61 62 63 64 65
  def add_to_shell
    GitlabShellWorker.perform_async(
      :add_key,
      shell_id,
      key
    )
  end

  def notify_user
66
    run_after_commit { NotificationService.new.new_key(self) }
67 68
  end

69 70 71 72
  def post_create_hook
    SystemHooksService.new.execute_hooks_for(self, :create)
  end

73 74 75 76 77 78 79 80
  def remove_from_shell
    GitlabShellWorker.perform_async(
      :remove_key,
      shell_id,
      key,
    )
  end

81 82 83 84
  def post_destroy_hook
    SystemHooksService.new.execute_hooks_for(self, :destroy)
  end

85 86
  private

Steven Burgart committed
87
  def generate_fingerprint
88
    self.fingerprint = nil
89 90 91 92

    return unless self.key.present?

    self.fingerprint = Gitlab::KeyFingerprint.new(self.key).fingerprint
93
  end
gitlabhq committed
94
end