BigW Consortium Gitlab

key.rb 2 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)
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 Sortable
20

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 :key, format: { without: /\n|\r/, message: 'should be a single line' }
28
  validates :fingerprint, uniqueness: true, presence: { message: 'cannot be generated' }
gitlabhq committed
29

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

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

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

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

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

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

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

  def notify_user
    NotificationService.new.new_key(self)
  end

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

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

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

84 85
  private

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

    return unless self.key.present?

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