diff --git a/zerver/lib/validator.py b/zerver/lib/validator.py index 4fb618ba77..3fd6a3abaa 100644 --- a/zerver/lib/validator.py +++ b/zerver/lib/validator.py @@ -27,8 +27,12 @@ for any particular type of object. ''' from __future__ import absolute_import from django.utils.translation import ugettext as _ +from django.core.exceptions import ValidationError +from django.core.validators import validate_email import six -from typing import Any, Callable, Iterable, Optional, Tuple, TypeVar +from typing import Any, Callable, Iterable, Optional, Tuple, TypeVar, Text + +from zerver.lib.request import JsonableError Validator = Callable[[str, Any], Optional[str]] @@ -144,3 +148,10 @@ def equals(expected_val): 'value': val}) return None return f + +def validate_login_email(email): + # type: (Text) -> None + try: + validate_email(email) + except ValidationError as err: + raise JsonableError(str(err.message)) diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py index efd963e9f4..72efc20562 100644 --- a/zerver/tests/test_auth_backends.py +++ b/zerver/tests/test_auth_backends.py @@ -22,6 +22,8 @@ from zerver.lib.actions import ( do_reactivate_user, do_set_realm_authentication_methods, ) +from zerver.lib.validator import validate_login_email +from zerver.lib.request import JsonableError from zerver.lib.initial_password import initial_password from zerver.lib.sessions import get_session_dict_user from zerver.lib.test_classes import ( @@ -1834,3 +1836,13 @@ class TestAdminSetBackends(ZulipTestCase): self.assertFalse(github_auth_enabled(realm)) self.assertTrue(dev_auth_enabled(realm)) self.assertFalse(password_auth_enabled(realm)) + +class LoginEmailValidatorTestCase(TestCase): + def test_valid_email(self): + # type: () -> None + validate_login_email(u'hamlet@zulip.com') + + def test_invalid_email(self): + # type: () -> None + with self.assertRaises(JsonableError): + validate_login_email(u'hamlet')