Commit 5b4382e12e060528c42bd3e19f61df88d6316785

Authored by miks
1 parent c973fce6

Validate key uniqueness across Key and DeployKey tables

app/models/deploy_key.rb
  1 +require 'unique_public_key_validator'
  2 +
1 class DeployKey < ActiveRecord::Base 3 class DeployKey < ActiveRecord::Base
2 belongs_to :project 4 belongs_to :project
3 5
@@ -10,6 +12,8 @@ class DeployKey &lt; ActiveRecord::Base @@ -10,6 +12,8 @@ class DeployKey &lt; ActiveRecord::Base
10 :uniqueness => true, 12 :uniqueness => true,
11 :length => { :within => 0..5000 } 13 :length => { :within => 0..5000 }
12 14
  15 + validates_with UniquePublicKeyValidator
  16 +
13 before_save :set_identifier 17 before_save :set_identifier
14 after_save :update_repository 18 after_save :update_repository
15 after_destroy :repository_delete_key 19 after_destroy :repository_delete_key
app/models/key.rb
  1 +require 'unique_public_key_validator'
  2 +
1 class Key < ActiveRecord::Base 3 class Key < ActiveRecord::Base
2 belongs_to :user 4 belongs_to :user
3 5
@@ -10,6 +12,8 @@ class Key &lt; ActiveRecord::Base @@ -10,6 +12,8 @@ class Key &lt; ActiveRecord::Base
10 :uniqueness => true, 12 :uniqueness => true,
11 :length => { :within => 0..5000 } 13 :length => { :within => 0..5000 }
12 14
  15 + validates_with UniquePublicKeyValidator
  16 +
13 before_save :set_identifier 17 before_save :set_identifier
14 after_save :update_repository 18 after_save :update_repository
15 after_destroy :repository_delete_key 19 after_destroy :repository_delete_key
lib/unique_public_key_validator.rb 0 → 100644
@@ -0,0 +1,7 @@ @@ -0,0 +1,7 @@
  1 +class UniquePublicKeyValidator < ActiveModel::Validator
  2 + def validate(record)
  3 + if (DeployKey.where('key = ? AND id !=?', record.key , record.id).count > 0 || Key.where('key = ? AND id !=?', record.key , record.id).count > 0)
  4 + record.errors.add :key, 'already exist.'
  5 + end
  6 + end
  7 +end