rosa-build/app/models/ssh_key.rb

64 lines
1.7 KiB
Ruby
Raw Normal View History

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:34:52 +00:00
SHELL_KEY_COMMAND = "sudo -i -u #{APP_CONFIG['shell_user']} ~#{APP_CONFIG['shell_user']}/gitlab-shell/bin/gitlab-keys"
2013-02-28 17:02:14 +00:00
belongs_to :user
before_validation -> { self.key = key.strip if key.present? }
2013-02-28 17:02:14 +00:00
before_validation :set_fingerprint
2014-03-11 12:40:44 +00:00
validates :name, length: { maximum: 255 }
validates :key, length: { maximum: 5000 }, format: { with: /ssh-.{3} / } # Public key?
2014-01-21 04:51:49 +00:00
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
file = Tempfile.new('key_file', '/tmp')
2013-03-01 19:33:48 +00:00
filename = file.path
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.
exitstatus = $?.exitstatus
2013-02-28 17:02:14 +00:00
ensure
file.close
file.unlink # deletes the temp file
end
if exitstatus != 0
self.fingerprint = nil
2013-02-28 17:02:14 +00:00
else
self.fingerprint = fingerprint_output.split.try :[], 1
if name.blank?
s = fingerprint_output.split.try :[], 2
2013-03-01 19:33:48 +00:00
if filename == 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