Browse files

Support email addresses in user authentication

  • Loading branch information...
1 parent 6883f0a commit 92950165bd511e9e3b3324c7effeec9de8068ac7 @dcramer dcramer committed Oct 7, 2012
View
2 src/sentry/conf/server.py
@@ -198,7 +198,7 @@
'social_auth.backends.contrib.mixcloud.MixcloudBackend',
'social_auth.backends.contrib.live.LiveBackend',
'django_social_auth_trello.backend.TrelloBackend',
- 'django.contrib.auth.backends.ModelBackend',
+ 'sentry.utils.auth.EmailAuthBackend',
)
TWITTER_CONSUMER_KEY = ''
View
26 src/sentry/utils/auth.py
@@ -8,6 +8,8 @@
import hashlib
import hmac
from django.conf import settings as dj_settings
+from django.contrib.auth.models import User
+from django.contrib.auth.backends import ModelBackend
from sentry.conf import settings
@@ -38,3 +40,27 @@ def get_auth_providers():
for key, cfg_names
in settings.AUTH_PROVIDERS.iteritems()
if all(getattr(dj_settings, c, None) for c in cfg_names)]
+
+
+class EmailAuthBackend(ModelBackend):
+ """
+ Authenticate against django.contrib.auth.models.User.
+
+ Supports authenticating via an email address or a username.
+ """
+ def authenticate(self, username=None, password=None):
+ try:
+ # Assume username is a login and attempt to login.
+ if '@' not in username:
+ user = User.objects.get(username__iexact=username)
+
+ # Treat username as an e-mail address and attempt to login.
+ elif '@' in username:
+ user = User.objects.get(email__iexact=username)
+ except User.DoesNotExist:
+ return None
+
+ if user.check_password(password):
+ return user
+
+ return None
View
0 tests/sentry/utils/auth/__init__.py
No changes.
View
28 tests/sentry/utils/auth/tests.py
@@ -0,0 +1,28 @@
+from __future__ import absolute_import
+
+from sentry.utils.auth import EmailAuthBackend
+from django.contrib.auth.models import User
+from tests.base import TestCase
+
+
+class EmailAuthBackendTest(TestCase):
+ def setUp(self):
+ self.user = User(username="foo", email="baz@example.com")
+ self.user.set_password("bar")
+ self.user.save()
+
+ @property
+ def backend(self):
+ return EmailAuthBackend()
+
+ def test_can_authenticate_with_username(self):
+ result = self.backend.authenticate(username='foo', password='bar')
+ self.assertEquals(result, self.user)
+
+ def test_can_authenticate_with_email(self):
+ result = self.backend.authenticate(username='baz@example.com', password='bar')
+ self.assertEquals(result, self.user)
+
+ def test_does_not_authenticate_with_invalid_password(self):
+ result = self.backend.authenticate(username='foo', password='pizza')
+ self.assertEquals(result, None)

0 comments on commit 9295016

Please sign in to comment.