[manual] Authenticate using a user_profile as request.user.

When this is deployed to staging, we need to run

./manage.py logout_all_users --realm=humbughq.com

When this is deployed to prod, we need to run

./manage.py logout_all_users

(imported from commit d6c6ea4b1c347f3d9122742db23c7b67767a7349)
This commit is contained in:
Tim Abbott
2013-03-29 12:39:53 -04:00
parent 712d931350
commit 5dbe8b4c17
8 changed files with 55 additions and 60 deletions

View File

@@ -1,18 +1,9 @@
from django.contrib.auth.models import User
from zephyr.models import UserProfile, get_user_profile_by_id, \
get_user_profile_by_email
from django.conf import settings
from openid.consumer.consumer import SUCCESS
from zephyr.lib.cache import cache_with_key
from zephyr.lib.cache import user_by_id_cache_key
@cache_with_key(user_by_id_cache_key, timeout=3600*24*7)
def get_user_by_id(user_id):
try:
return User.objects.select_related().get(id=user_id)
except User.DoesNotExist:
return None
class EmailAuthBackend(object):
"""
Email Authentication Backend
@@ -30,19 +21,22 @@ class EmailAuthBackend(object):
return None
try:
user = User.objects.get(email__iexact=username)
if user.check_password(password):
return user
except User.DoesNotExist:
user_profile = UserProfile.objects.get(email__iexact=username)
if user_profile.check_password(password):
return user_profile
except UserProfile.DoesNotExist:
return None
def get_user(self, user_id):
""" Get a User object from the user_id. """
return get_user_by_id(user_id)
def get_user(self, user_profile_id):
""" Get a UserProfile object from the user_profile_id. """
try:
return get_user_profile_by_id(user_profile_id)
except UserProfile.DoesNotExist:
return None
# Adapted from http://djangosnippets.org/snippets/2183/ by user Hangya (September 1, 2010)
class GoogleBackend:
class GoogleBackend(object):
def authenticate(self, openid_response):
if openid_response is None:
return None
@@ -52,15 +46,16 @@ class GoogleBackend:
google_email = openid_response.getSigned('http://openid.net/srv/ax/1.0', 'value.email')
try:
user = User.objects.get(email__iexact=google_email)
except User.DoesNotExist:
user_profile = get_user_profile_by_email(google_email)
except UserProfile.DoesNotExist:
# create a new user, or send a message to admins, etc.
return None
return user
return user_profile
def get_user(self, user_id):
def get_user(self, user_profile_id):
""" Get a UserProfile object from the user_profile_id. """
try:
return User.objects.get(id=user_id)
except User.DoesNotExist:
return get_user_profile_by_id(user_profile_id)
except UserProfile.DoesNotExist:
return None

View File

@@ -144,7 +144,7 @@ def authenticate_log_and_execute_json(request, client, view_func, *args, **kwarg
if not request.user.is_authenticated():
return json_error("Not logged in", status=401)
request.client = client
user_profile = get_user_profile_by_user_id(request.user.id)
user_profile = request.user
request._email = user_profile.email
update_user_activity(request, user_profile)
return view_func(request, user_profile, *args, **kwargs)

View File

@@ -52,6 +52,6 @@ class HomepageForm(forms.Form):
class LoggingSetPasswordForm(SetPasswordForm):
def save(self, commit=True):
do_change_password(self.user.userprofile, self.cleaned_data['new_password1'],
do_change_password(self.user, self.cleaned_data['new_password1'],
log=True, commit=commit)
return self.user

View File

@@ -20,8 +20,8 @@ def format_record(record):
stack_trace = 'No stack trace available'
try:
user = record.request.user
user_info = "%s (%s)" % (user.userprofile.full_name, user.email)
user_profile = record.request.user
user_info = "%s (%s)" % (user_profile.full_name, user_profile.email)
except Exception:
# Error was triggered by an anonymous user.
user_info = "Anonymous user (not logged in)"

View File

@@ -72,19 +72,20 @@ def do_create_user(email, password, realm, full_name, short_name,
tornado_callbacks.send_notification(notice)
return user_profile
def user_sessions(user):
return [s for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]
def user_sessions(user_profile):
return [s for s in Session.objects.all()
if s.get_decoded().get('_auth_user_id') == user_profile.id]
def delete_session(session):
return session_engine.SessionStore(session.session_key).delete()
def delete_user_sessions(user_profile):
for session in Session.objects.all():
if session.get_decoded().get('_auth_user_id') == user_profile.user.id:
if session.get_decoded().get('_auth_user_id') == user_profile.id:
delete_session(session)
def delete_realm_user_sessions(realm):
realm_user_ids = [u.user.id for u in
realm_user_ids = [user_profile.id for user_profile in
UserProfile.objects.filter(realm=realm)]
for session in Session.objects.all():
if session.get_decoded().get('_auth_user_id') in realm_user_ids:

View File

@@ -27,7 +27,7 @@ class Command(BaseCommand):
user_profile.email,
user_profile.realm.domain)
print "%s has the following active sessions:" % (user_profile.email,)
for session in user_sessions(user_profile.user):
for session in user_sessions(user_profile):
print session.expire_date, session.get_decoded()
print ""

View File

@@ -228,8 +228,8 @@ class LoginTest(AuthedTestCase):
def test_login(self):
self.login("hamlet@humbughq.com")
user = User.objects.get(email='hamlet@humbughq.com')
self.assertEqual(self.client.session['_auth_user_id'], user.id)
user_profile = self.get_user_profile('hamlet@humbughq.com')
self.assertEqual(self.client.session['_auth_user_id'], user_profile.id)
def test_login_bad_password(self):
self.login("hamlet@humbughq.com", "wrongpassword")
@@ -237,8 +237,8 @@ class LoginTest(AuthedTestCase):
def test_register(self):
self.register("test", "test")
user = User.objects.get(email='test@humbughq.com')
self.assertEqual(self.client.session['_auth_user_id'], user.id)
user_profile = self.get_user_profile('test@humbughq.com')
self.assertEqual(self.client.session['_auth_user_id'], user_profile.id)
def test_logout(self):
self.login("hamlet@humbughq.com")
@@ -254,15 +254,15 @@ class LoginTest(AuthedTestCase):
# Registering succeeds.
self.register("test", password)
user = User.objects.get(email=email)
self.assertEqual(self.client.session['_auth_user_id'], user.id)
user_profile = self.get_user_profile(email)
self.assertEqual(self.client.session['_auth_user_id'], user_profile.id)
self.client.post('/accounts/logout/')
self.assertIsNone(self.client.session.get('_auth_user_id', None))
# Logging in succeeds.
self.client.post('/accounts/logout/')
self.login(email, password)
self.assertEqual(self.client.session['_auth_user_id'], user.id)
self.assertEqual(self.client.session['_auth_user_id'], user_profile.id)
class PersonalMessagesTest(AuthedTestCase):
fixtures = ['messages.json']
@@ -1392,8 +1392,8 @@ class ChangeSettingsTest(AuthedTestCase):
enable_desktop_notifications, False)
self.client.post('/accounts/logout/')
self.login("hamlet@humbughq.com", "foobar1")
user = User.objects.get(email='hamlet@humbughq.com')
self.assertEqual(self.client.session['_auth_user_id'], user.id)
user_profile = self.get_user_profile('hamlet@humbughq.com')
self.assertEqual(self.client.session['_auth_user_id'], user_profile.id)
def test_missing_params(self):
"""
@@ -1452,9 +1452,9 @@ class DummySession(object):
class POSTRequestMock(object):
method = "POST"
def __init__(self, post_data, user, assert_callback=None):
def __init__(self, post_data, user_profile, assert_callback=None):
self.REQUEST = self.POST = post_data
self.user = user
self.user = user_profile
self._tornado_handler = DummyHandler(assert_callback)
self.session = DummySession()
self.META = {'PATH_INFO': 'test'}
@@ -1474,7 +1474,7 @@ class GetUpdatesTest(AuthedTestCase):
post_data = {}
post_data.update(extra_post_data)
request = POSTRequestMock(post_data, user_profile.user, callback)
request = POSTRequestMock(post_data, user_profile, callback)
self.assertEqual(view_func(request), RespondAsynchronously)
def test_json_get_updates(self):
@@ -1498,9 +1498,9 @@ class GetUpdatesTest(AuthedTestCase):
Calling json_get_updates without any arguments should work
"""
self.login("hamlet@humbughq.com")
user = User.objects.get(email="hamlet@humbughq.com")
user_profile = self.get_user_profile("hamlet@humbughq.com")
request = POSTRequestMock({}, user)
request = POSTRequestMock({}, user_profile)
self.assertEqual(json_get_updates(request), RespondAsynchronously)
def test_bad_input(self):
@@ -1508,9 +1508,9 @@ class GetUpdatesTest(AuthedTestCase):
Specifying a bad value for 'pointer' should return an error
"""
self.login("hamlet@humbughq.com")
user = User.objects.get(email="hamlet@humbughq.com")
user_profile = self.get_user_profile("hamlet@humbughq.com")
request = POSTRequestMock({'pointer': 'foo'}, user)
request = POSTRequestMock({'pointer': 'foo'}, user_profile)
self.assertRaises(RequestVariableConversionError, json_get_updates, request)
class GetProfileTest(AuthedTestCase):

View File

@@ -206,8 +206,7 @@ def accounts_register(request):
# FIXME: sanitize email addresses and fullname
if mit_beta_user:
user = User.objects.get(email=email)
user_profile = user.userprofile
user_profile = get_user_profile_by_email(email)
do_activate_user(user_profile)
do_change_password(user_profile, password)
do_change_full_name(user_profile, full_name)
@@ -256,7 +255,7 @@ def accounts_accept_terms(request):
'browser': request.META['HTTP_USER_AGENT']}),
"humbug@humbughq.com",
["all@humbughq.com"])
do_change_full_name(request.user.userprofile, full_name)
do_change_full_name(request.user, full_name)
return redirect(home)
else:
@@ -397,7 +396,7 @@ def home(request):
# session alive.
request.session.modified = True
user_profile = get_user_profile_by_user_id(request.user.id)
user_profile = request.user
register_ret = do_events_register(user_profile, apply_markdown=True)
user_has_messages = (register_ret['max_message_id'] != -1)
@@ -1165,17 +1164,17 @@ def json_subscription_property(request, user_profile):
@require_post
@has_request_variables
def api_fetch_api_key(request, username=POST, password=POST):
user = authenticate(username=username, password=password)
if user is None:
user_profile = authenticate(username=username, password=password)
if user_profile is None:
return json_error("Your username or password is incorrect.", status=403)
if not user.is_active:
if not user_profile.is_active:
return json_error("Your account has been disabled.", status=403)
return json_success({"api_key": user.userprofile.api_key})
return json_success({"api_key": user_profile.api_key})
@authenticated_json_post_view
@has_request_variables
def json_fetch_api_key(request, user_profile, password=POST):
if not request.user.check_password(password):
if not user_profile.check_password(password):
return json_error("Your username or password is incorrect.")
return json_success({"api_key": user_profile.api_key})
@@ -1211,7 +1210,7 @@ class ActivityTable(object):
return sorted(self.rows.iteritems(), key=lambda (k,r): r['age'])
def can_view_activity(request):
return request.user.userprofile.realm.domain == 'humbughq.com'
return request.user.realm.domain == 'humbughq.com'
@login_required(login_url = settings.HOME_NOT_LOGGED_IN)
def get_activity(request):