Skip to content

Commit 419e70c

Browse files
committed
Add username checker
1 parent 3da1bc7 commit 419e70c

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed
Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
class UsernameConventionValidator < ActiveModel::EachValidator
22
def validate_each(record, field, value)
33
unless value.blank?
4-
unless Rails.configuration.x.settings.dig(:unicode_username)
5-
record.errors.add field, "is not alphanumeric (letters, numbers, underscores or periods)" unless value =~ /^[[:alnum:]._-]+$/
6-
record.errors.add field, "should start with a letter" unless value[0] =~ /[A-Za-z]/
7-
record.errors.add field, "contains illegal characters" unless value.ascii_only?
4+
if Rails.configuration.x.settings.dig(:unicode_username)
5+
record.errors.add field, "contains illegal characters" if /[\/]/.match(value)
6+
else
7+
record.errors.add field, "is not alphanumeric (letters, numbers, underscores or periods)" unless /^[a-zA-Z0-9._\-]+$/.match(value)
8+
record.errors.add field, "should start with a letter" unless /^[A-Za-z]/.match(value)
89
end
910
record.errors.add field, "is forbidden" if ['sign_in', 'sign_up'].include? value
10-
record.errors.add field, "should not be purely numeric" if value =~ /^[0-9]+$/
11+
record.errors.add field, "should not be purely numeric" if /^[0-9]+$/.match(value)
1112
end
1213
end
1314
end
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
namespace :user do
2+
desc "Check if there are accounts with invalid usernames"
3+
task :check_invalid_username => :environment do
4+
lst = User.where.not('username REGEXP ?', '^[A-Za-z][a-zA-Z0-9._\-]*$')
5+
unless lst
6+
puts 'There are no accounts with invalid usernames.'
7+
return
8+
end
9+
breaking, lst = lst.partition{|x| /[\/]/.match(x.username) }
10+
pure_numeric, lst = lst.partition{|x| /^[0-9]+$/.match(x.username) }
11+
overriden, lst = lst.partition{|x| ['sign_in', 'sign_up'].include? x.username }
12+
unless breaking.empty?
13+
puts "Accounts that can cause crash when rendering (username containing /):"
14+
breaking.each {|x| puts "User ID #{x.id}: #{x.username}" }
15+
end
16+
unless overriden.empty?
17+
puts "Accounts whose user page will be unreachable (username colliding with existing endpoints):"
18+
overriden.each {|x| puts "User ID #{x.id}: #{x.username}" }
19+
end
20+
unless pure_numeric.empty?
21+
puts "Accounts that normally don't cause issues, but may override other's user page when visiting by /users/[user-id] (purely numeric usernames):"
22+
pure_numeric.each {|x| puts "User ID #{x.id}: #{x.username}" }
23+
end
24+
unless lst.empty?
25+
puts "Accounts that don't cause issues, but violates the default username policy:"
26+
lst.each {|x| puts "User ID #{x.id}: #{x.username}" }
27+
end
28+
end
29+
end

0 commit comments

Comments
 (0)