Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add plugin hook for extra username validations (#35522)

Gabriel Grubbaad5f57b29cf0
diff --git a/app/models/username_validator.rb b/app/models/username_validator.rb
index 8ba990750a6..08380e99e81 100644
--- a/app/models/username_validator.rb
+++ b/app/models/username_validator.rb
@@ -9,26 +9,24 @@ class UsernameValidator
#
# Example: UsernameValidator.perform_validation(user, 'name')
def self.perform_validation(object, field_name, opts = {})
- validator = UsernameValidator.new(object.public_send(field_name), **opts)
+ validator = UsernameValidator.new(object.public_send(field_name), object:, **opts)
unless validator.valid_format?
validator.errors.each { |e| object.errors.add(field_name.to_sym, e) }
end
end
- def initialize(username, skip_length_validation: false)
+ def initialize(username, skip_length_validation: false, object: nil)
@username = username&.unicode_normalize
@skip_length_validation = skip_length_validation
+ @object = object
@errors = []
end
attr_accessor :errors
attr_reader :username
+ attr_reader :object
attr_reader :skip_length_validation
- def user
- @user ||= User.new(user)
- end
-
def valid_format?
username_present?
username_length_min? if !skip_length_validation
@@ -39,6 +37,7 @@ class UsernameValidator
username_last_char_valid?
username_no_double_special?
username_does_not_end_with_confusing_suffix?
+ username_plugin_validation
errors.empty?
end
@@ -152,6 +151,12 @@ class UsernameValidator
end
end
+ def username_plugin_validation
+ return unless errors.empty?
+
+ DiscoursePluginRegistry.apply_modifier(:username_validation, self.errors, self)
+ end
+
def username_grapheme_clusters
@username_grapheme_clusters ||= username.grapheme_clusters
end
diff --git a/spec/models/username_validator_spec.rb b/spec/models/username_validator_spec.rb
index cd90f1b5b6a..a303715755f 100644
--- a/spec/models/username_validator_spec.rb
+++ b/spec/models/username_validator_spec.rb
@@ -290,4 +290,29 @@ RSpec.describe UsernameValidator do
end
end
end
+
+ describe "#perform_validation" do
+ let!(:invalid_username) { "invalidusername" }
+ let!(:plugin) { Plugin::Instance.new }
+ let!(:modifier) { :username_validation }
+ let!(:add_error_block) do
+ Proc.new do |errors, context|
+ errors << "Plugin validation error message" if context.username == invalid_username
+ end
+ end
+
+ it "applies plugin modifiers for username validation" do
+ expect_valid(invalid_username, failure_reason: "Plugin validations should be called")
+
+ DiscoursePluginRegistry.register_modifier(plugin, modifier, &add_error_block)
+
+ expect_invalid(
+ invalid_username,
+ error_message: "Plugin validation error message",
+ failure_reason: "Plugin validations should be called",
+ )
+ ensure
+ DiscoursePluginRegistry.unregister_modifier(plugin, modifier, &add_error_block)
+ end
+ end
end