mirror of
https://github.com/zulip/zulip.git
synced 2025-11-09 08:26:11 +00:00
[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:
@@ -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 django.conf import settings
|
||||||
|
|
||||||
from openid.consumer.consumer import SUCCESS
|
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):
|
class EmailAuthBackend(object):
|
||||||
"""
|
"""
|
||||||
Email Authentication Backend
|
Email Authentication Backend
|
||||||
@@ -30,19 +21,22 @@ class EmailAuthBackend(object):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
user = User.objects.get(email__iexact=username)
|
user_profile = UserProfile.objects.get(email__iexact=username)
|
||||||
if user.check_password(password):
|
if user_profile.check_password(password):
|
||||||
return user
|
return user_profile
|
||||||
except User.DoesNotExist:
|
except UserProfile.DoesNotExist:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def get_user(self, user_id):
|
def get_user(self, user_profile_id):
|
||||||
""" Get a User object from the user_id. """
|
""" Get a UserProfile object from the user_profile_id. """
|
||||||
return get_user_by_id(user_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)
|
# Adapted from http://djangosnippets.org/snippets/2183/ by user Hangya (September 1, 2010)
|
||||||
|
|
||||||
class GoogleBackend:
|
class GoogleBackend(object):
|
||||||
def authenticate(self, openid_response):
|
def authenticate(self, openid_response):
|
||||||
if openid_response is None:
|
if openid_response is None:
|
||||||
return None
|
return None
|
||||||
@@ -52,15 +46,16 @@ class GoogleBackend:
|
|||||||
google_email = openid_response.getSigned('http://openid.net/srv/ax/1.0', 'value.email')
|
google_email = openid_response.getSigned('http://openid.net/srv/ax/1.0', 'value.email')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
user = User.objects.get(email__iexact=google_email)
|
user_profile = get_user_profile_by_email(google_email)
|
||||||
except User.DoesNotExist:
|
except UserProfile.DoesNotExist:
|
||||||
# create a new user, or send a message to admins, etc.
|
# create a new user, or send a message to admins, etc.
|
||||||
return None
|
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:
|
try:
|
||||||
return User.objects.get(id=user_id)
|
return get_user_profile_by_id(user_profile_id)
|
||||||
except User.DoesNotExist:
|
except UserProfile.DoesNotExist:
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ def authenticate_log_and_execute_json(request, client, view_func, *args, **kwarg
|
|||||||
if not request.user.is_authenticated():
|
if not request.user.is_authenticated():
|
||||||
return json_error("Not logged in", status=401)
|
return json_error("Not logged in", status=401)
|
||||||
request.client = client
|
request.client = client
|
||||||
user_profile = get_user_profile_by_user_id(request.user.id)
|
user_profile = request.user
|
||||||
request._email = user_profile.email
|
request._email = user_profile.email
|
||||||
update_user_activity(request, user_profile)
|
update_user_activity(request, user_profile)
|
||||||
return view_func(request, user_profile, *args, **kwargs)
|
return view_func(request, user_profile, *args, **kwargs)
|
||||||
|
|||||||
@@ -52,6 +52,6 @@ class HomepageForm(forms.Form):
|
|||||||
|
|
||||||
class LoggingSetPasswordForm(SetPasswordForm):
|
class LoggingSetPasswordForm(SetPasswordForm):
|
||||||
def save(self, commit=True):
|
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)
|
log=True, commit=commit)
|
||||||
return self.user
|
return self.user
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ def format_record(record):
|
|||||||
stack_trace = 'No stack trace available'
|
stack_trace = 'No stack trace available'
|
||||||
|
|
||||||
try:
|
try:
|
||||||
user = record.request.user
|
user_profile = record.request.user
|
||||||
user_info = "%s (%s)" % (user.userprofile.full_name, user.email)
|
user_info = "%s (%s)" % (user_profile.full_name, user_profile.email)
|
||||||
except Exception:
|
except Exception:
|
||||||
# Error was triggered by an anonymous user.
|
# Error was triggered by an anonymous user.
|
||||||
user_info = "Anonymous user (not logged in)"
|
user_info = "Anonymous user (not logged in)"
|
||||||
|
|||||||
@@ -72,19 +72,20 @@ def do_create_user(email, password, realm, full_name, short_name,
|
|||||||
tornado_callbacks.send_notification(notice)
|
tornado_callbacks.send_notification(notice)
|
||||||
return user_profile
|
return user_profile
|
||||||
|
|
||||||
def user_sessions(user):
|
def user_sessions(user_profile):
|
||||||
return [s for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]
|
return [s for s in Session.objects.all()
|
||||||
|
if s.get_decoded().get('_auth_user_id') == user_profile.id]
|
||||||
|
|
||||||
def delete_session(session):
|
def delete_session(session):
|
||||||
return session_engine.SessionStore(session.session_key).delete()
|
return session_engine.SessionStore(session.session_key).delete()
|
||||||
|
|
||||||
def delete_user_sessions(user_profile):
|
def delete_user_sessions(user_profile):
|
||||||
for session in Session.objects.all():
|
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)
|
delete_session(session)
|
||||||
|
|
||||||
def delete_realm_user_sessions(realm):
|
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)]
|
UserProfile.objects.filter(realm=realm)]
|
||||||
for session in Session.objects.all():
|
for session in Session.objects.all():
|
||||||
if session.get_decoded().get('_auth_user_id') in realm_user_ids:
|
if session.get_decoded().get('_auth_user_id') in realm_user_ids:
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ class Command(BaseCommand):
|
|||||||
user_profile.email,
|
user_profile.email,
|
||||||
user_profile.realm.domain)
|
user_profile.realm.domain)
|
||||||
print "%s has the following active sessions:" % (user_profile.email,)
|
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 session.expire_date, session.get_decoded()
|
||||||
print ""
|
print ""
|
||||||
|
|
||||||
|
|||||||
@@ -228,8 +228,8 @@ class LoginTest(AuthedTestCase):
|
|||||||
|
|
||||||
def test_login(self):
|
def test_login(self):
|
||||||
self.login("hamlet@humbughq.com")
|
self.login("hamlet@humbughq.com")
|
||||||
user = User.objects.get(email='hamlet@humbughq.com')
|
user_profile = self.get_user_profile('hamlet@humbughq.com')
|
||||||
self.assertEqual(self.client.session['_auth_user_id'], user.id)
|
self.assertEqual(self.client.session['_auth_user_id'], user_profile.id)
|
||||||
|
|
||||||
def test_login_bad_password(self):
|
def test_login_bad_password(self):
|
||||||
self.login("hamlet@humbughq.com", "wrongpassword")
|
self.login("hamlet@humbughq.com", "wrongpassword")
|
||||||
@@ -237,8 +237,8 @@ class LoginTest(AuthedTestCase):
|
|||||||
|
|
||||||
def test_register(self):
|
def test_register(self):
|
||||||
self.register("test", "test")
|
self.register("test", "test")
|
||||||
user = User.objects.get(email='test@humbughq.com')
|
user_profile = self.get_user_profile('test@humbughq.com')
|
||||||
self.assertEqual(self.client.session['_auth_user_id'], user.id)
|
self.assertEqual(self.client.session['_auth_user_id'], user_profile.id)
|
||||||
|
|
||||||
def test_logout(self):
|
def test_logout(self):
|
||||||
self.login("hamlet@humbughq.com")
|
self.login("hamlet@humbughq.com")
|
||||||
@@ -254,15 +254,15 @@ class LoginTest(AuthedTestCase):
|
|||||||
|
|
||||||
# Registering succeeds.
|
# Registering succeeds.
|
||||||
self.register("test", password)
|
self.register("test", password)
|
||||||
user = User.objects.get(email=email)
|
user_profile = self.get_user_profile(email)
|
||||||
self.assertEqual(self.client.session['_auth_user_id'], user.id)
|
self.assertEqual(self.client.session['_auth_user_id'], user_profile.id)
|
||||||
self.client.post('/accounts/logout/')
|
self.client.post('/accounts/logout/')
|
||||||
self.assertIsNone(self.client.session.get('_auth_user_id', None))
|
self.assertIsNone(self.client.session.get('_auth_user_id', None))
|
||||||
|
|
||||||
# Logging in succeeds.
|
# Logging in succeeds.
|
||||||
self.client.post('/accounts/logout/')
|
self.client.post('/accounts/logout/')
|
||||||
self.login(email, password)
|
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):
|
class PersonalMessagesTest(AuthedTestCase):
|
||||||
fixtures = ['messages.json']
|
fixtures = ['messages.json']
|
||||||
@@ -1392,8 +1392,8 @@ class ChangeSettingsTest(AuthedTestCase):
|
|||||||
enable_desktop_notifications, False)
|
enable_desktop_notifications, False)
|
||||||
self.client.post('/accounts/logout/')
|
self.client.post('/accounts/logout/')
|
||||||
self.login("hamlet@humbughq.com", "foobar1")
|
self.login("hamlet@humbughq.com", "foobar1")
|
||||||
user = User.objects.get(email='hamlet@humbughq.com')
|
user_profile = self.get_user_profile('hamlet@humbughq.com')
|
||||||
self.assertEqual(self.client.session['_auth_user_id'], user.id)
|
self.assertEqual(self.client.session['_auth_user_id'], user_profile.id)
|
||||||
|
|
||||||
def test_missing_params(self):
|
def test_missing_params(self):
|
||||||
"""
|
"""
|
||||||
@@ -1452,9 +1452,9 @@ class DummySession(object):
|
|||||||
class POSTRequestMock(object):
|
class POSTRequestMock(object):
|
||||||
method = "POST"
|
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.REQUEST = self.POST = post_data
|
||||||
self.user = user
|
self.user = user_profile
|
||||||
self._tornado_handler = DummyHandler(assert_callback)
|
self._tornado_handler = DummyHandler(assert_callback)
|
||||||
self.session = DummySession()
|
self.session = DummySession()
|
||||||
self.META = {'PATH_INFO': 'test'}
|
self.META = {'PATH_INFO': 'test'}
|
||||||
@@ -1474,7 +1474,7 @@ class GetUpdatesTest(AuthedTestCase):
|
|||||||
|
|
||||||
post_data = {}
|
post_data = {}
|
||||||
post_data.update(extra_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)
|
self.assertEqual(view_func(request), RespondAsynchronously)
|
||||||
|
|
||||||
def test_json_get_updates(self):
|
def test_json_get_updates(self):
|
||||||
@@ -1498,9 +1498,9 @@ class GetUpdatesTest(AuthedTestCase):
|
|||||||
Calling json_get_updates without any arguments should work
|
Calling json_get_updates without any arguments should work
|
||||||
"""
|
"""
|
||||||
self.login("hamlet@humbughq.com")
|
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)
|
self.assertEqual(json_get_updates(request), RespondAsynchronously)
|
||||||
|
|
||||||
def test_bad_input(self):
|
def test_bad_input(self):
|
||||||
@@ -1508,9 +1508,9 @@ class GetUpdatesTest(AuthedTestCase):
|
|||||||
Specifying a bad value for 'pointer' should return an error
|
Specifying a bad value for 'pointer' should return an error
|
||||||
"""
|
"""
|
||||||
self.login("hamlet@humbughq.com")
|
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)
|
self.assertRaises(RequestVariableConversionError, json_get_updates, request)
|
||||||
|
|
||||||
class GetProfileTest(AuthedTestCase):
|
class GetProfileTest(AuthedTestCase):
|
||||||
|
|||||||
@@ -206,8 +206,7 @@ def accounts_register(request):
|
|||||||
|
|
||||||
# FIXME: sanitize email addresses and fullname
|
# FIXME: sanitize email addresses and fullname
|
||||||
if mit_beta_user:
|
if mit_beta_user:
|
||||||
user = User.objects.get(email=email)
|
user_profile = get_user_profile_by_email(email)
|
||||||
user_profile = user.userprofile
|
|
||||||
do_activate_user(user_profile)
|
do_activate_user(user_profile)
|
||||||
do_change_password(user_profile, password)
|
do_change_password(user_profile, password)
|
||||||
do_change_full_name(user_profile, full_name)
|
do_change_full_name(user_profile, full_name)
|
||||||
@@ -256,7 +255,7 @@ def accounts_accept_terms(request):
|
|||||||
'browser': request.META['HTTP_USER_AGENT']}),
|
'browser': request.META['HTTP_USER_AGENT']}),
|
||||||
"humbug@humbughq.com",
|
"humbug@humbughq.com",
|
||||||
["all@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)
|
return redirect(home)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
@@ -397,7 +396,7 @@ def home(request):
|
|||||||
# session alive.
|
# session alive.
|
||||||
request.session.modified = True
|
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)
|
register_ret = do_events_register(user_profile, apply_markdown=True)
|
||||||
user_has_messages = (register_ret['max_message_id'] != -1)
|
user_has_messages = (register_ret['max_message_id'] != -1)
|
||||||
@@ -1165,17 +1164,17 @@ def json_subscription_property(request, user_profile):
|
|||||||
@require_post
|
@require_post
|
||||||
@has_request_variables
|
@has_request_variables
|
||||||
def api_fetch_api_key(request, username=POST, password=POST):
|
def api_fetch_api_key(request, username=POST, password=POST):
|
||||||
user = authenticate(username=username, password=password)
|
user_profile = authenticate(username=username, password=password)
|
||||||
if user is None:
|
if user_profile is None:
|
||||||
return json_error("Your username or password is incorrect.", status=403)
|
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_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
|
@authenticated_json_post_view
|
||||||
@has_request_variables
|
@has_request_variables
|
||||||
def json_fetch_api_key(request, user_profile, password=POST):
|
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_error("Your username or password is incorrect.")
|
||||||
return json_success({"api_key": user_profile.api_key})
|
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'])
|
return sorted(self.rows.iteritems(), key=lambda (k,r): r['age'])
|
||||||
|
|
||||||
def can_view_activity(request):
|
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)
|
@login_required(login_url = settings.HOME_NOT_LOGGED_IN)
|
||||||
def get_activity(request):
|
def get_activity(request):
|
||||||
|
|||||||
Reference in New Issue
Block a user