Skip to content

Commit

Permalink
Validate fingerprint uniqueness
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobvosmaer committed Jul 17, 2013
1 parent 656d800 commit aa0473d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 15 deletions.
19 changes: 5 additions & 14 deletions app/models/key.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,18 @@ class Key < ActiveRecord::Base

attr_accessible :key, :title

before_validation :strip_white_space
before_validation :strip_white_space, :generate_fingerpint

validates :title, presence: true, length: { within: 0..255 }
validates :key, presence: true, length: { within: 0..5000 }, format: { with: /\A(ssh|ecdsa)-.*\Z/ }, uniqueness: true
validate :fingerprintable_key
validates :fingerprint, uniqueness: true, presence: { message: 'cannot be generated' }

delegate :name, :email, to: :user, prefix: true

def strip_white_space
self.key = key.strip unless key.blank?
end

def fingerprintable_key
return true unless key # Don't test if there is no key.

unless generate_fingerpint
errors.add(:key, "can't be fingerprinted")
false
end
end

# projects that has this key
def projects
user.authorized_projects
Expand All @@ -54,6 +45,9 @@ def shell_id
private

def generate_fingerpint
self.fingerprint = nil
return unless key.present?

cmd_status = 0
cmd_output = ''
Tempfile.open('gitlab_key_file') do |file|
Expand All @@ -66,9 +60,6 @@ def generate_fingerpint
cmd_output.gsub /([\d\h]{2}:)+[\d\h]{2}/ do |match|
self.fingerprint = match
end
true
else
false
end
end
end
9 changes: 8 additions & 1 deletion spec/models/key_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,17 @@
build(:key, user: user).should be_valid
end

it "does not accepts the key twice" do
it "does not accept the exact same key twice" do
create(:key, user: user)
build(:key, user: user).should_not be_valid
end

it "does not accept a duplicate key with a different comment" do
create(:key, user: user)
duplicate = build(:key, user: user)
duplicate.key << ' extra comment'
duplicate.should_not be_valid
end
end

context "validate it is a fingerprintable key" do
Expand Down

0 comments on commit aa0473d

Please sign in to comment.