key.rb 1.51 KB
Newer Older
miks's avatar
miks committed
1 2
require 'digest/md5'

gitlabhq's avatar
gitlabhq committed
3 4
class Key < ActiveRecord::Base
  belongs_to :user
miks's avatar
miks committed
5
  belongs_to :project
gitlabhq's avatar
gitlabhq committed
6

7
  attr_accessible :key, :title
8

gitlabhq's avatar
gitlabhq committed
9
  validates :title,
10 11
            presence: true,
            length: { within: 0..255 }
gitlabhq's avatar
gitlabhq committed
12 13

  validates :key,
14
            presence: true,
15
            format: { :with => /ssh-.{3} / },
16
            length: { within: 0..5000 }
gitlabhq's avatar
gitlabhq committed
17 18

  before_save :set_identifier
miks's avatar
miks committed
19
  before_validation :strip_white_space
20
  delegate :name, :email, to: :user, prefix: true
miks's avatar
miks committed
21 22
  validate :unique_key

miks's avatar
miks committed
23
  def strip_white_space
24
    self.key = self.key.strip unless self.key.blank?
miks's avatar
miks committed
25 26
  end

miks's avatar
miks committed
27
  def unique_key
28
    query = Key.where(key: key)
miks's avatar
miks committed
29 30
    query = query.where('(project_id IS NULL OR project_id = ?)', project_id) if project_id
    if (query.count > 0)
miks's avatar
miks committed
31 32 33
      errors.add :key, 'already exist.'
    end
  end
gitlabhq's avatar
gitlabhq committed
34 35

  def set_identifier
miks's avatar
miks committed
36
    if is_deploy_key
miks's avatar
miks committed
37
      self.identifier = "deploy_" + Digest::MD5.hexdigest(key)
miks's avatar
miks committed
38 39 40
    else
      self.identifier = "#{user.identifier}_#{Time.now.to_i}"
    end
gitlabhq's avatar
gitlabhq committed
41
  end
Nihad Abbasov's avatar
Nihad Abbasov committed
42

miks's avatar
miks committed
43 44 45
  def is_deploy_key
    true if project_id
  end
gitlabhq's avatar
gitlabhq committed
46

47
  # projects that has this key
gitlabhq's avatar
gitlabhq committed
48
  def projects
miks's avatar
miks committed
49 50 51 52 53
    if is_deploy_key
      [project]
    else
      user.projects
    end
gitlabhq's avatar
gitlabhq committed
54
  end
55 56 57 58

  def last_deploy?
    Key.where(identifier: identifier).count == 0
  end
gitlabhq's avatar
gitlabhq committed
59 60 61 62 63
end
# == Schema Information
#
# Table name: keys
#
randx's avatar
randx committed
64 65 66 67
#  id         :integer(4)      not null, primary key
#  user_id    :integer(4)
#  created_at :datetime        not null
#  updated_at :datetime        not null
gitlabhq's avatar
gitlabhq committed
68 69 70
#  key        :text
#  title      :string(255)
#  identifier :string(255)
randx's avatar
randx committed
71
#  project_id :integer(4)
gitlabhq's avatar
gitlabhq committed
72 73
#