diff --git a/app/models/deploy_key.rb b/app/models/deploy_key.rb index 254e766c..c720f09b 100644 --- a/app/models/deploy_key.rb +++ b/app/models/deploy_key.rb @@ -1,3 +1,5 @@ +require 'unique_public_key_validator' + class DeployKey < ActiveRecord::Base belongs_to :project @@ -10,6 +12,8 @@ class DeployKey < ActiveRecord::Base :uniqueness => true, :length => { :within => 0..5000 } + validates_with UniquePublicKeyValidator + before_save :set_identifier after_save :update_repository after_destroy :repository_delete_key diff --git a/app/models/key.rb b/app/models/key.rb index 359538d2..0e4088e4 100644 --- a/app/models/key.rb +++ b/app/models/key.rb @@ -1,3 +1,5 @@ +require 'unique_public_key_validator' + class Key < ActiveRecord::Base belongs_to :user @@ -10,6 +12,8 @@ class Key < ActiveRecord::Base :uniqueness => true, :length => { :within => 0..5000 } + validates_with UniquePublicKeyValidator + before_save :set_identifier after_save :update_repository after_destroy :repository_delete_key diff --git a/lib/unique_public_key_validator.rb b/lib/unique_public_key_validator.rb new file mode 100644 index 00000000..b2306bda --- /dev/null +++ b/lib/unique_public_key_validator.rb @@ -0,0 +1,7 @@ +class UniquePublicKeyValidator < ActiveModel::Validator + def validate(record) + if (DeployKey.where('key = ? AND id !=?', record.key , record.id).count > 0 || Key.where('key = ? AND id !=?', record.key , record.id).count > 0) + record.errors.add :key, 'already exist.' + end + end +end