From 74a25f205bf398c5913728f61e7e6caaf03849b7 Mon Sep 17 00:00:00 2001 From: Mouse Reeve Date: Mon, 28 Dec 2020 14:14:22 -0800 Subject: [PATCH] Validator for username field --- bookwyrm/models/fields.py | 14 ++++++++++++-- bookwyrm/tests/models/test_fields.py | 14 ++++++++++---- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/bookwyrm/models/fields.py b/bookwyrm/models/fields.py index 2649bb59..beddb291 100644 --- a/bookwyrm/models/fields.py +++ b/bookwyrm/models/fields.py @@ -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.'), }, diff --git a/bookwyrm/tests/models/test_fields.py b/bookwyrm/tests/models/test_fields.py index 6e91cbc8..7935301e 100644 --- a/bookwyrm/tests/models/test_fields.py +++ b/bookwyrm/tests/models/test_fields.py @@ -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')