Validator for username field

This commit is contained in:
Mouse Reeve 2020-12-28 14:14:22 -08:00
parent 7e987fc446
commit 74a25f205b
2 changed files with 22 additions and 6 deletions

View file

@ -27,8 +27,17 @@ def validate_remote_id(value):
def validate_localname(value):
''' make sure localnames look okay '''
if not re.match(r'^[A-Za-z\-_\.0-9]+$', value):
raise ValidationError(
_('%(value)s is not a valid username'),
params={'value': value},
)
def validate_username(value):
''' make sure usernames look okay '''
if not re.match(r'^[A-Za-z\-_\.]+$', value):
if not re.match(r'^[A-Za-z\-_\.0-9]+@[A-Za-z\-_\.0-9]+\.[a-z]{2,}$', value):
raise ValidationError(
_('%(value)s is not a valid username'),
params={'value': value},
@ -147,7 +156,7 @@ class RemoteIdField(ActivitypubFieldMixin, models.CharField):
class UsernameField(ActivitypubFieldMixin, models.CharField):
''' activitypub-aware username field '''
def __init__(self, activitypub_field='preferredUsername'):
def __init__(self, activitypub_field='preferredUsername', **kwargs):
self.activitypub_field = activitypub_field
# I don't totally know why pylint is mad at this, but it makes it work
super( #pylint: disable=bad-super-call
@ -156,6 +165,7 @@ class UsernameField(ActivitypubFieldMixin, models.CharField):
_('username'),
max_length=150,
unique=True,
validators=[validate_username],
error_messages={
'unique': _('A user with that username already exists.'),
},

View file

@ -111,10 +111,16 @@ class ActivitypubFields(TestCase):
self.assertEqual(instance.max_length, 150)
self.assertEqual(instance.unique, True)
with self.assertRaises(ValidationError):
instance.run_validators('one two')
instance.run_validators('a*&')
instance.run_validators('trailingwhite ')
self.assertIsNone(instance.run_validators('aksdhf'))
instance.run_validators('mouseexample.com')
instance.run_validators('mouse@example.c')
instance.run_validators('@example.com')
instance.run_validators('mouse@examplecom')
instance.run_validators('one two@fish.aaaa')
instance.run_validators('a*&@exampke.com')
instance.run_validators('trailingwhite@example.com ')
self.assertIsNone(instance.run_validators('mouse@example.com'))
self.assertIsNone(instance.run_validators('mo-2use@ex3ample.com'))
self.assertIsNone(instance.run_validators('aksdhf@sdkjf-df.cm'))
self.assertEqual(instance.field_to_activity('test@example.com'), 'test')