Commit d7c887fe authored by Raphaël Hertzog's avatar Raphaël Hertzog

django_email_accounts: validate email on UserEmail.save()

The goal is to never accept invalid data in the database. It will
raise ValidationError but any code creating UserEmail should either
check emails validity before or be ready to handle those errors.

The validation also applies to the user field, so that's why we must
add the blank=True, otherwise validation does not pass.
parent e3a4d88b
# Generated by Django 2.2.4 on 2019-08-30 20:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('django_email_accounts', '0002_django18_compat'),
]
operations = [
migrations.AlterField(
model_name='useremail',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='emails', to='django_email_accounts.User'),
),
]
......@@ -202,7 +202,7 @@ class UserEmailManager(models.Manager):
class UserEmail(models.Model):
email = models.EmailField(max_length=244, unique=True)
user = models.ForeignKey(User, related_name='emails', null=True,
user = models.ForeignKey(User, related_name='emails', blank=True, null=True,
on_delete=models.CASCADE)
objects = UserEmailManager()
......@@ -211,6 +211,10 @@ class UserEmail(models.Model):
def __str__(self):
return self.email
def save(self, *args, **kwargs):
self.full_clean()
super(UserEmail, self).save(*args, **kwargs)
class UserRegistrationConfirmation(Confirmation):
"""
......
......@@ -9,6 +9,7 @@
# except according to the terms contained in the LICENSE file.
"""Unit tests for django_email_accounts."""
from django.core.exceptions import ValidationError
from django.test import TestCase
from django.urls import reverse
......@@ -24,6 +25,19 @@ class UserEmailTests(TestCase):
self.assertFalse(created)
self.assertEqual(orig_user_email.pk, user_email.pk)
def test_user_email_save_does_validation(self):
user_email = UserEmail(email='foobar')
with self.assertRaises(ValidationError):
user_email.save()
def test_user_email_create_does_validation(self):
with self.assertRaises(ValidationError):
UserEmail.objects.create(email='foobar')
def test_user_email_get_or_create_does_validation(self):
with self.assertRaises(ValidationError):
UserEmail.objects.get_or_create(email='foobar')
class LoginViewTests(TestCase):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment