2013-02-28 17:02:14 +00:00
|
|
|
# This class is based on
|
|
|
|
# https://github.com/gitlabhq/gitlabhq/blob/15c0e58a49d623a0f8747e1d7e74364324eeb79f/app/models/key.rb
|
|
|
|
|
2013-03-01 11:33:02 +00:00
|
|
|
class SshKey < ActiveRecord::Base
|
2013-03-01 19:33:11 +00:00
|
|
|
SHELL_KEY_COMMAND = "sudo -i -u git ~#{APP_CONFIG['shell_user']}/gitlab-shell/bin/gitlab-keys"
|
2013-02-28 17:02:14 +00:00
|
|
|
|
|
|
|
belongs_to :user
|
|
|
|
attr_accessible :key, :name
|
|
|
|
|
|
|
|
before_validation lambda { self.key = key.strip if key.present? }
|
|
|
|
before_validation :set_fingerprint
|
|
|
|
|
2013-03-01 17:35:33 +00:00
|
|
|
validates :name, :length => {:maximum => 255}
|
|
|
|
validates :key, :length => {:maximum => 5000}, format: { :with => /ssh-.{3} / } # Public key?
|
|
|
|
validates :fingerprint, uniqueness: true, :presence => { :message => I18n.t('activerecord.errors.ssh_key.wrong_key') }
|
2013-02-28 17:02:14 +00:00
|
|
|
|
2013-03-01 11:33:02 +00:00
|
|
|
after_create :add_key
|
|
|
|
before_destroy :remove_key
|
2013-02-28 17:02:14 +00:00
|
|
|
|
|
|
|
protected
|
|
|
|
|
|
|
|
def set_fingerprint
|
|
|
|
return false unless key
|
|
|
|
|
2013-03-01 17:35:33 +00:00
|
|
|
file = Tempfile.new('key_file', "#{APP_CONFIG['root_path']}/tmp")
|
2013-02-28 17:02:14 +00:00
|
|
|
begin
|
|
|
|
file.puts key
|
|
|
|
file.rewind
|
|
|
|
fingerprint_output = `ssh-keygen -lf #{file.path} 2>&1` # Catch stderr.
|
2013-03-01 17:35:33 +00:00
|
|
|
exitstatus = $?.exitstatus
|
2013-02-28 17:02:14 +00:00
|
|
|
ensure
|
|
|
|
file.close
|
|
|
|
file.unlink # deletes the temp file
|
|
|
|
end
|
2013-03-01 17:35:33 +00:00
|
|
|
if exitstatus != 0
|
|
|
|
self.fingerprint = nil
|
2013-02-28 17:02:14 +00:00
|
|
|
else
|
2013-03-01 17:35:33 +00:00
|
|
|
self.fingerprint = fingerprint_output.split.try :[], 1
|
|
|
|
if name.blank?
|
|
|
|
s = fingerprint_output.split.try :[], 2
|
|
|
|
if File.exist? s # no identificator
|
|
|
|
start = key =~ /ssh-.{3} /
|
|
|
|
self.name = key[start..start+26] # taken first 26 characters
|
|
|
|
else
|
|
|
|
self.name = s
|
|
|
|
end
|
|
|
|
end
|
2013-02-28 17:02:14 +00:00
|
|
|
end
|
|
|
|
end
|
2013-03-01 11:33:02 +00:00
|
|
|
|
|
|
|
def key_id
|
|
|
|
"key-#{id}"
|
|
|
|
end
|
|
|
|
|
|
|
|
def add_key
|
|
|
|
system "#{SHELL_KEY_COMMAND} add-key #{key_id} \"#{key}\"" # Safety?
|
|
|
|
end
|
|
|
|
|
|
|
|
def remove_key
|
|
|
|
system "#{SHELL_KEY_COMMAND} rm-key #{key_id}"# \"#{key}\""
|
|
|
|
end
|
|
|
|
|
2013-02-28 17:02:14 +00:00
|
|
|
end
|