Access the UserProfile's new email field rather than using User.

This is preparatory for stopping using the User model.

(imported from commit a1b0808c8cc2ddd19a25163f91c4f18620c9ce90)
This commit is contained in:
Tim Abbott
2013-03-28 15:43:34 -04:00
parent 3a35c5b00c
commit 1443edce00
25 changed files with 94 additions and 94 deletions

View File

@@ -28,7 +28,7 @@ def report(state, short_msg, too_old=None):
too_old_data = "" too_old_data = ""
if too_old: if too_old:
too_old_data = "\nLast call to get_message for recently out of date mirrors:\n" + "\n".join( too_old_data = "\nLast call to get_message for recently out of date mirrors:\n" + "\n".join(
["%16s: %s" % (user.user_profile.user.email, ["%16s: %s" % (user.user_profile.email,
user.last_visit.strftime("%Y-%m-%d %H:%M %Z") user.last_visit.strftime("%Y-%m-%d %H:%M %Z")
) for user in too_old] ) for user in too_old]
) )

View File

@@ -1,6 +1,6 @@
Hi there, Hi there,
{{ referrer.full_name }} ({{ referrer.user.email }}) wants you to join them on Humbug -- the group communication tool you've always wished you had at work. {{ referrer.full_name }} ({{ referrer.email }}) wants you to join them on Humbug -- the group communication tool you've always wished you had at work.
To get started, visit the link below: To get started, visit the link below:
<{{ activate_url }}> <{{ activate_url }}>

View File

@@ -6,7 +6,7 @@
src="https://secure.gravatar.com/avatar/{{ email_hash }}?d=identicon&s=60" /> src="https://secure.gravatar.com/avatar/{{ email_hash }}?d=identicon&s=60" />
<span id="my_information"> <span id="my_information">
<span class="my_fullname">{{ user_profile.full_name }}</span><br /> <span class="my_fullname">{{ user_profile.full_name }}</span><br />
<span class="my_email">{{ user_profile.user.email }}</span> <span class="my_email">{{ user_profile.email }}</span>
</span> </span>
</div> </div>

View File

@@ -7,7 +7,7 @@
</div> </div>
<div class="span7" id="navbar-middle"> <div class="span7" id="navbar-middle">
<a class="brand skinny-user-gravatar visible-phone" href="#" <a class="brand skinny-user-gravatar visible-phone" href="#"
title="{{user_profile.full_name}} - {{user_profile.user.email}}"> title="{{user_profile.full_name}} - {{user_profile.email}}">
<img class="img-rounded gravatar-profile" <img class="img-rounded gravatar-profile"
src="https://secure.gravatar.com/avatar/{{ email_hash }}?d=identicon&s=30" /> src="https://secure.gravatar.com/avatar/{{ email_hash }}?d=identicon&s=30" />
</a> </a>

View File

@@ -145,7 +145,7 @@ def authenticate_log_and_execute_json(request, client, view_func, *args, **kwarg
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 = get_user_profile_by_user_id(request.user.id)
request._email = user_profile.user.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)

View File

@@ -64,7 +64,7 @@ def do_create_user(email, password, realm, full_name, short_name,
user_profile = create_user(email, password, realm, full_name, short_name, active) user_profile = create_user(email, password, realm, full_name, short_name, active)
notice = dict(event=dict(type="realm_user", op="add", notice = dict(event=dict(type="realm_user", op="add",
person=dict(email=user_profile.user.email, person=dict(email=user_profile.email,
full_name=user_profile.full_name)), full_name=user_profile.full_name)),
users=[up.id for up in users=[up.id for up in
UserProfile.objects.select_related().filter(realm=user_profile.realm, UserProfile.objects.select_related().filter(realm=user_profile.realm,
@@ -107,11 +107,11 @@ def do_deactivate(user_profile):
log_event({'type': 'user_deactivated', log_event({'type': 'user_deactivated',
'timestamp': time.time(), 'timestamp': time.time(),
'user': user_profile.user.email, 'user': user_profile.email,
'domain': user_profile.realm.domain}) 'domain': user_profile.realm.domain})
notice = dict(event=dict(type="realm_user", op="remove", notice = dict(event=dict(type="realm_user", op="remove",
person=dict(email=user_profile.user.email, person=dict(email=user_profile.email,
full_name=user_profile.full_name)), full_name=user_profile.full_name)),
users=[up.id for up in users=[up.id for up in
UserProfile.objects.select_related().filter(realm=user_profile.realm, UserProfile.objects.select_related().filter(realm=user_profile.realm,
@@ -120,7 +120,7 @@ def do_deactivate(user_profile):
def do_change_user_email(user_profile, new_email): def do_change_user_email(user_profile, new_email):
old_email = user_profile.user.email old_email = user_profile.email
user_profile.email = new_email user_profile.email = new_email
user_profile.save(update_fields=["email"]) user_profile.save(update_fields=["email"])
@@ -449,7 +449,7 @@ def do_add_subscription(user_profile, stream, no_log=False):
if did_subscribe: if did_subscribe:
if not no_log: if not no_log:
log_event({'type': 'subscription_added', log_event({'type': 'subscription_added',
'user': user_profile.user.email, 'user': user_profile.email,
'name': stream.name, 'name': stream.name,
'domain': stream.realm.domain}) 'domain': stream.realm.domain})
@@ -476,7 +476,7 @@ def do_remove_subscription(user_profile, stream, no_log=False):
if did_remove: if did_remove:
if not no_log: if not no_log:
log_event({'type': 'subscription_removed', log_event({'type': 'subscription_removed',
'user': user_profile.user.email, 'user': user_profile.email,
'name': stream.name, 'name': stream.name,
'domain': stream.realm.domain}) 'domain': stream.realm.domain})
@@ -510,7 +510,7 @@ def do_activate_user(user_profile, log=True, join_date=timezone.now()):
if log: if log:
domain = user_profile.realm.domain domain = user_profile.realm.domain
log_event({'type': 'user_activated', log_event({'type': 'user_activated',
'user': user.email, 'user': user_profile.email,
'domain': domain}) 'domain': domain})
def do_change_password(user_profile, password, log=True, commit=True, def do_change_password(user_profile, password, log=True, commit=True,
@@ -528,15 +528,15 @@ def do_change_password(user_profile, password, log=True, commit=True,
user_profile.save(update_fields=["password"]) user_profile.save(update_fields=["password"])
if log: if log:
log_event({'type': 'user_change_password', log_event({'type': 'user_change_password',
'user': user.email, 'user': user_profile.email,
'pwhash': user.password}) 'pwhash': user_profile.password})
def do_change_full_name(user_profile, full_name, log=True): def do_change_full_name(user_profile, full_name, log=True):
user_profile.full_name = full_name user_profile.full_name = full_name
user_profile.save(update_fields=["full_name"]) user_profile.save(update_fields=["full_name"])
if log: if log:
log_event({'type': 'user_change_full_name', log_event({'type': 'user_change_full_name',
'user': user_profile.user.email, 'user': user_profile.email,
'full_name': full_name}) 'full_name': full_name})
def do_create_realm(domain, replay=False): def do_create_realm(domain, replay=False):
@@ -555,7 +555,7 @@ def do_change_enable_desktop_notifications(user_profile, enable_desktop_notifica
user_profile.save(update_fields=["enable_desktop_notifications"]) user_profile.save(update_fields=["enable_desktop_notifications"])
if log: if log:
log_event({'type': 'enable_desktop_notifications_changed', log_event({'type': 'enable_desktop_notifications_changed',
'user': user_profile.user.email, 'user': user_profile.email,
'enable_desktop_notifications': enable_desktop_notifications}) 'enable_desktop_notifications': enable_desktop_notifications})
def do_change_enter_sends(user_profile, enter_sends): def do_change_enter_sends(user_profile, enter_sends):
@@ -702,7 +702,7 @@ def process_update_message_flags(event):
def update_flags_externally(op, flag, user_profile, until_id): def update_flags_externally(op, flag, user_profile, until_id):
args = ['python', os.path.join(os.path.dirname(__file__), '../..', 'manage.py'), args = ['python', os.path.join(os.path.dirname(__file__), '../..', 'manage.py'),
'set_message_flags', '--for-real', '-o', op, '-f', flag, '-m', user_profile.user.email, 'set_message_flags', '--for-real', '-o', op, '-f', flag, '-m', user_profile.email,
'-u', str(until_id)] '-u', str(until_id)]
subprocess.Popen(args, stdin=subprocess.PIPE, stdout=None, stderr=None) subprocess.Popen(args, stdin=subprocess.PIPE, stdout=None, stderr=None)
@@ -780,7 +780,7 @@ def do_events_register(user_profile, apply_markdown=True, event_types=None):
if event_types is None or "pointer" in event_types: if event_types is None or "pointer" in event_types:
ret['pointer'] = user_profile.pointer ret['pointer'] = user_profile.pointer
if event_types is None or "realm_user" in event_types: if event_types is None or "realm_user" in event_types:
ret['realm_users'] = [{'email' : profile.user.email, ret['realm_users'] = [{'email' : profile.email,
'full_name' : profile.full_name} 'full_name' : profile.full_name}
for profile in for profile in
UserProfile.objects.select_related().filter(realm=user_profile.realm, UserProfile.objects.select_related().filter(realm=user_profile.realm,

View File

@@ -59,7 +59,7 @@ def bulk_create_users(realms, users_raw):
profiles_by_email = {} profiles_by_email = {}
profiles_by_id = {} profiles_by_id = {}
for profile in UserProfile.objects.select_related().all(): for profile in UserProfile.objects.select_related().all():
profiles_by_email[profile.user.email] = profile profiles_by_email[profile.email] = profile
profiles_by_id[profile.id] = profile profiles_by_id[profile.id] = profile
recipients_to_create = [] recipients_to_create = []
@@ -70,7 +70,7 @@ def bulk_create_users(realms, users_raw):
recipients_by_email = {} recipients_by_email = {}
for recipient in Recipient.objects.filter(type=Recipient.PERSONAL): for recipient in Recipient.objects.filter(type=Recipient.PERSONAL):
recipients_by_email[profiles_by_id[recipient.type_id].user.email] = recipient recipients_by_email[profiles_by_id[recipient.type_id].email] = recipient
subscriptions_to_create = [] subscriptions_to_create = []
for (email, _, _, _) in users: for (email, _, _, _) in users:

View File

@@ -76,7 +76,7 @@ def user_by_id_cache_key(user_id):
def update_user_profile_cache(sender, **kwargs): def update_user_profile_cache(sender, **kwargs):
user_profile = kwargs['instance'] user_profile = kwargs['instance']
items_for_memcached = {} items_for_memcached = {}
items_for_memcached[user_profile_by_email_cache_key(user_profile.user.email)] = (user_profile,) items_for_memcached[user_profile_by_email_cache_key(user_profile.email)] = (user_profile,)
items_for_memcached[user_profile_by_user_cache_key(user_profile.user.id)] = (user_profile,) items_for_memcached[user_profile_by_user_cache_key(user_profile.user.id)] = (user_profile,)
items_for_memcached[user_profile_by_id_cache_key(user_profile.id)] = (user_profile,) items_for_memcached[user_profile_by_id_cache_key(user_profile.id)] = (user_profile,)
djcache.set_many(items_for_memcached) djcache.set_many(items_for_memcached)

View File

@@ -23,7 +23,7 @@ def message_cache_items(items_for_memcached, message):
items_for_memcached[message_cache_key(message.id)] = (message,) items_for_memcached[message_cache_key(message.id)] = (message,)
def user_cache_items(items_for_memcached, user_profile): def user_cache_items(items_for_memcached, user_profile):
items_for_memcached[user_profile_by_email_cache_key(user_profile.user.email)] = (user_profile,) items_for_memcached[user_profile_by_email_cache_key(user_profile.email)] = (user_profile,)
items_for_memcached[user_profile_by_user_cache_key(user_profile.user.id)] = (user_profile,) items_for_memcached[user_profile_by_user_cache_key(user_profile.user.id)] = (user_profile,)
items_for_memcached[user_by_id_cache_key(user_profile.user.id)] = (user_profile.user,) items_for_memcached[user_by_id_cache_key(user_profile.user.id)] = (user_profile.user,)
items_for_memcached[user_profile_by_id_cache_key(user_profile.id)] = (user_profile,) items_for_memcached[user_profile_by_id_cache_key(user_profile.id)] = (user_profile,)

View File

@@ -225,7 +225,7 @@ def request_event_queue(user_profile, apply_markdown, event_types=None):
if event_types is not None: if event_types is not None:
req['event_types'] = simplejson.dumps(event_types) req['event_types'] = simplejson.dumps(event_types)
resp = requests.get(settings.TORNADO_SERVER + '/api/v1/events', resp = requests.get(settings.TORNADO_SERVER + '/api/v1/events',
auth=requests.auth.HTTPBasicAuth(user_profile.user.email, auth=requests.auth.HTTPBasicAuth(user_profile.email,
user_profile.api_key), user_profile.api_key),
params=req) params=req)
@@ -238,7 +238,7 @@ def request_event_queue(user_profile, apply_markdown, event_types=None):
def get_user_events(user_profile, queue_id, last_event_id): def get_user_events(user_profile, queue_id, last_event_id):
if settings.TORNADO_SERVER: if settings.TORNADO_SERVER:
resp = requests.get(settings.TORNADO_SERVER + '/api/v1/events', resp = requests.get(settings.TORNADO_SERVER + '/api/v1/events',
auth=requests.auth.HTTPBasicAuth(user_profile.user.email, auth=requests.auth.HTTPBasicAuth(user_profile.email,
user_profile.api_key), user_profile.api_key),
params={'queue_id' : queue_id, params={'queue_id' : queue_id,
'last_event_id': last_event_id, 'last_event_id': last_event_id,

View File

@@ -51,4 +51,4 @@ class Command(BaseCommand):
did_subscribe = do_add_subscription(user_profile, stream) did_subscribe = do_add_subscription(user_profile, stream)
print "%s %s to %s" % ( print "%s %s to %s" % (
"Subscribed" if did_subscribe else "Already subscribed", "Subscribed" if did_subscribe else "Already subscribed",
user_profile.user.email, stream_name) user_profile.email, stream_name)

View File

@@ -16,18 +16,18 @@ def compute_stats(log_level):
recipient__type=Recipient.STREAM, recipient__type=Recipient.STREAM,
pub_date__gt=one_week_ago) pub_date__gt=one_week_ago)
for bot_sender_start in ["imap.", "rcmd.", "sys."]: for bot_sender_start in ["imap.", "rcmd.", "sys."]:
mit_query = mit_query.exclude(sender__user__email__startswith=(bot_sender_start)) mit_query = mit_query.exclude(sender__email__startswith=(bot_sender_start))
# Filtering for "/" covers tabbott/extra@ and all the daemon/foo bots. # Filtering for "/" covers tabbott/extra@ and all the daemon/foo bots.
mit_query = mit_query.exclude(sender__user__email__contains=("/")) mit_query = mit_query.exclude(sender__email__contains=("/"))
mit_query = mit_query.exclude(sender__user__email__contains=("aim.com")) mit_query = mit_query.exclude(sender__email__contains=("aim.com"))
mit_query = mit_query.exclude( mit_query = mit_query.exclude(
sender__user__email__in=["rss@mit.edu", "bash@mit.edu", "apache@mit.edu", sender__email__in=["rss@mit.edu", "bash@mit.edu", "apache@mit.edu",
"bitcoin@mit.edu", "lp@mit.edu", "clocks@mit.edu", "bitcoin@mit.edu", "lp@mit.edu", "clocks@mit.edu",
"root@mit.edu", "nagios@mit.edu", "root@mit.edu", "nagios@mit.edu",
"www-data|local-realm@mit.edu"]) "www-data|local-realm@mit.edu"])
user_counts = {} user_counts = {}
for m in mit_query.select_related("sending_client", "sender", "sender__user"): for m in mit_query.select_related("sending_client", "sender"):
email = m.sender.user.email email = m.sender.email
user_counts.setdefault(email, {}) user_counts.setdefault(email, {})
user_counts[email].setdefault(m.sending_client.name, 0) user_counts[email].setdefault(m.sending_client.name, 0)
user_counts[email][m.sending_client.name] += 1 user_counts[email][m.sending_client.name] += 1

View File

@@ -9,11 +9,11 @@ def banish_busted_users(change=False):
if (u.user.is_active or u.realm.domain != "mit.edu"): if (u.user.is_active or u.realm.domain != "mit.edu"):
continue continue
(banished_realm, _) = Realm.objects.get_or_create(domain="mit.deleted") (banished_realm, _) = Realm.objects.get_or_create(domain="mit.deleted")
if "|mit.edu@mit.edu" in u.user.email.lower(): if "|mit.edu@mit.edu" in u.email.lower():
print u.user.email print u.email
if change: if change:
u.realm = banished_realm u.realm = banished_realm
u.user.email = u.user.email.split("@")[0] + "@" + banished_realm.domain u.email = u.email.split("@")[0] + "@" + banished_realm.domain
u.user.save() u.user.save()
u.save() u.save()

View File

@@ -24,9 +24,9 @@ class Command(BaseCommand):
user_profile = get_user_profile_by_email(args[0]) user_profile = get_user_profile_by_email(args[0])
print "Deactivating %s (%s) - %s" % (user_profile.full_name, print "Deactivating %s (%s) - %s" % (user_profile.full_name,
user_profile.user.email, user_profile.email,
user_profile.realm.domain) user_profile.realm.domain)
print "%s has the following active sessions:" % (user_profile.user.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.user):
print session.expire_date, session.get_decoded() print session.expire_date, session.get_decoded()
print "" print ""

View File

@@ -7,7 +7,7 @@ import simplejson
def dump(): def dump():
passwords = [] passwords = []
for user_profile in UserProfile.objects.all(): for user_profile in UserProfile.objects.all():
passwords.append((user_profile.user.email, user_profile.password)) passwords.append((user_profile.email, user_profile.password))
file("dumped-passwords", "w").write(simplejson.dumps(passwords) + "\n") file("dumped-passwords", "w").write(simplejson.dumps(passwords) + "\n")
def restore(change): def restore(change):

View File

@@ -7,13 +7,13 @@ import simplejson
def dump(): def dump():
pointers = [] pointers = []
for u in UserProfile.objects.select_related("user__email").all(): for u in UserProfile.objects.all():
pointer = u.pointer pointer = u.pointer
if pointer != -1: if pointer != -1:
pub_date = Message.objects.get(id=pointer).pub_date pub_date = Message.objects.get(id=pointer).pub_date
pointers.append((u.user.email, datetime_to_timestamp(pub_date))) pointers.append((u.email, datetime_to_timestamp(pub_date)))
else: else:
pointers.append((u.user.email, -1)) pointers.append((u.email, -1))
file("dumped-pointers", "w").write(simplejson.dumps(pointers) + "\n") file("dumped-pointers", "w").write(simplejson.dumps(pointers) + "\n")
def restore(change): def restore(change):

View File

@@ -7,9 +7,9 @@ from zephyr.lib.timestamp import datetime_to_timestamp, timestamp_to_datetime
def dump(): def dump():
pointers = [] pointers = []
for activity in UserActivity.objects.select_related("user_profile__user__email", for activity in UserActivity.objects.select_related("user_profile__email",
"client__name").all(): "client__name").all():
pointers.append((activity.user_profile.user.email, activity.client.name, pointers.append((activity.user_profile.email, activity.client.name,
activity.query, activity.count, activity.query, activity.count,
datetime_to_timestamp(activity.last_visit))) datetime_to_timestamp(activity.last_visit)))
file("dumped-activity", "w").write(simplejson.dumps(pointers) + "\n") file("dumped-activity", "w").write(simplejson.dumps(pointers) + "\n")

View File

@@ -252,7 +252,7 @@ def restore_saved_messages():
stream_dict = {} stream_dict = {}
user_set = set() user_set = set()
email_set = set([u.email for u in User.objects.all()]) email_set = set([u.email for u in UserProfile.objects.all()])
realm_set = set() realm_set = set()
# Initial client_set is nonempty temporarily because we don't have # Initial client_set is nonempty temporarily because we don't have
# clients in logs at all right now -- later we can start with nothing. # clients in logs at all right now -- later we can start with nothing.
@@ -401,10 +401,10 @@ def restore_saved_messages():
users = {} users = {}
users_by_id = {} users_by_id = {}
for user_profile in UserProfile.objects.select_related().all(): for user_profile in UserProfile.objects.select_related().all():
users[user_profile.user.email] = user_profile users[user_profile.email] = user_profile
users_by_id[user_profile.id] = user_profile users_by_id[user_profile.id] = user_profile
for recipient in Recipient.objects.filter(type=Recipient.PERSONAL): for recipient in Recipient.objects.filter(type=Recipient.PERSONAL):
user_recipients[users_by_id[recipient.type_id].user.email] = recipient user_recipients[users_by_id[recipient.type_id].email] = recipient
print datetime.datetime.now(), "Creating huddles..." print datetime.datetime.now(), "Creating huddles..."
bulk_create_huddles(users, huddle_user_set) bulk_create_huddles(users, huddle_user_set)

View File

@@ -51,4 +51,4 @@ class Command(BaseCommand):
did_remove = do_remove_subscription(user_profile, stream) did_remove = do_remove_subscription(user_profile, stream)
print "%s %s from %s" % ( print "%s %s from %s" % (
"Removed" if did_remove else "Couldn't remove", "Removed" if did_remove else "Couldn't remove",
user_profile.user.email, stream_name) user_profile.email, stream_name)

View File

@@ -55,10 +55,10 @@ class Command(BaseCommand):
if not options["for_real"]: if not options["for_real"]:
for msg in msgs: for msg in msgs:
print "Adding read flag to msg: %s - %s/%s (own msg: %s)" \ print "Adding read flag to msg: %s - %s/%s (own msg: %s)" \
% (user_profile.user.email, % (user_profile.email,
msg.message.id, msg.message.id,
msg.id, msg.id,
msg.message.sender.user.email == user_profile.user.email) msg.message.sender.email == user_profile.email)
else: else:
def do_update(batch): def do_update(batch):
with transaction.commit_on_success(): with transaction.commit_on_success():

View File

@@ -12,9 +12,9 @@ def update_mit_fullnames(change=False):
# actually have an account (is_active) and thus have # actually have an account (is_active) and thus have
# presumably set their fullname how they like it. # presumably set their fullname how they like it.
continue continue
computed_name = compute_mit_user_fullname(u.user.email) computed_name = compute_mit_user_fullname(u.email)
if u.full_name != computed_name: if u.full_name != computed_name:
print "%s: %s => %s" % (u.user.email, u.full_name, computed_name) print "%s: %s => %s" % (u.email, u.full_name, computed_name)
if change: if change:
u.full_name = computed_name u.full_name = computed_name
u.save() u.save()

View File

@@ -29,7 +29,7 @@ class Command(BaseCommand):
print "%d streams" % (len(Stream.objects.filter(realm=realm)),) print "%d streams" % (len(Stream.objects.filter(realm=realm)),)
for user_profile in user_profiles: for user_profile in user_profiles:
print "%35s" % (user_profile.user.email,), print "%35s" % (user_profile.email,),
for week in range(10): for week in range(10):
print "%5d" % (self.messages_sent_by(user_profile, week)), print "%5d" % (self.messages_sent_by(user_profile, week)),
print "" print ""

View File

@@ -38,8 +38,8 @@ def get_display_recipient(recipient):
# We don't really care what the ordering is, just that it's deterministic. # We don't really care what the ordering is, just that it's deterministic.
user_profile_list = (UserProfile.objects.filter(subscription__recipient=recipient) user_profile_list = (UserProfile.objects.filter(subscription__recipient=recipient)
.select_related() .select_related()
.order_by('user__email')) .order_by('email'))
return [{'email': user_profile.user.email, return [{'email': user_profile.email,
'full_name': user_profile.full_name, 'full_name': user_profile.full_name,
'short_name': user_profile.short_name} for user_profile in user_profile_list] 'short_name': user_profile.short_name} for user_profile in user_profile_list]
@@ -99,7 +99,7 @@ class UserProfile(AbstractBaseUser):
return profile return profile
def __repr__(self): def __repr__(self):
return (u"<UserProfile: %s %s>" % (self.user.email, self.realm)).encode("utf-8") return (u"<UserProfile: %s %s>" % (self.email, self.realm)).encode("utf-8")
def __str__(self): def __str__(self):
return self.__repr__() return self.__repr__()
@@ -266,7 +266,7 @@ class Message(models.Model):
if len(display_recipient) == 1: if len(display_recipient) == 1:
# add the sender in if this isn't a message between # add the sender in if this isn't a message between
# someone and his self, preserving ordering # someone and his self, preserving ordering
recip = {'email': self.sender.user.email, recip = {'email': self.sender.email,
'full_name': self.sender.full_name, 'full_name': self.sender.full_name,
'short_name': self.sender.short_name}; 'short_name': self.sender.short_name};
if recip['email'] < display_recipient[0]['email']: if recip['email'] < display_recipient[0]['email']:
@@ -278,7 +278,7 @@ class Message(models.Model):
obj = dict( obj = dict(
id = self.id, id = self.id,
sender_email = self.sender.user.email, sender_email = self.sender.email,
sender_full_name = self.sender.full_name, sender_full_name = self.sender.full_name,
sender_short_name = self.sender.short_name, sender_short_name = self.sender.short_name,
type = display_type, type = display_type,
@@ -286,7 +286,7 @@ class Message(models.Model):
recipient_id = self.recipient.id, recipient_id = self.recipient.id,
subject = self.subject, subject = self.subject,
timestamp = datetime_to_timestamp(self.pub_date), timestamp = datetime_to_timestamp(self.pub_date),
gravatar_hash = gravatar_hash(self.sender.user.email), gravatar_hash = gravatar_hash(self.sender.email),
client = self.sending_client.name) client = self.sending_client.name)
if apply_markdown and self.rendered_content_version is not None: if apply_markdown and self.rendered_content_version is not None:
@@ -313,7 +313,7 @@ class Message(models.Model):
def to_log_dict(self): def to_log_dict(self):
return dict( return dict(
id = self.id, id = self.id,
sender_email = self.sender.user.email, sender_email = self.sender.email,
sender_full_name = self.sender.full_name, sender_full_name = self.sender.full_name,
sender_short_name = self.sender.short_name, sender_short_name = self.sender.short_name,
sending_client = self.sending_client.name, sending_client = self.sending_client.name,
@@ -342,7 +342,7 @@ class UserMessage(models.Model):
def __repr__(self): def __repr__(self):
display_recipient = get_display_recipient(self.message.recipient) display_recipient = get_display_recipient(self.message.recipient)
return (u"<UserMessage: %s / %s (%s)>" % (display_recipient, self.user_profile.user.email, self.flags_dict())).encode("utf-8") return (u"<UserMessage: %s / %s (%s)>" % (display_recipient, self.user_profile.email, self.flags_dict())).encode("utf-8")
def flags_dict(self): def flags_dict(self):
return dict(flags = [flag for flag in self.flags.keys() if getattr(self.flags, flag).is_set]) return dict(flags = [flag for flag in self.flags.keys() if getattr(self.flags, flag).is_set])
@@ -368,7 +368,7 @@ def get_user_profile_by_id(uid):
@cache_with_key(user_profile_by_email_cache_key, timeout=3600*24*7) @cache_with_key(user_profile_by_email_cache_key, timeout=3600*24*7)
def get_user_profile_by_email(email): def get_user_profile_by_email(email):
return UserProfile.objects.select_related().get(user__email__iexact=email) return UserProfile.objects.select_related().get(email__iexact=email)
class Huddle(models.Model): class Huddle(models.Model):
# TODO: We should consider whether using # TODO: We should consider whether using

View File

@@ -85,7 +85,7 @@ class AuthedTestCase(TestCase):
""" """
# Usernames are unique, even across Realms. # Usernames are unique, even across Realms.
# We use this rather than get_user_profile_by_email to circumvent memcached (I think?) # We use this rather than get_user_profile_by_email to circumvent memcached (I think?)
return UserProfile.objects.get(user__email__iexact=email) return UserProfile.objects.get(email__iexact=email)
def get_streams(self, email): def get_streams(self, email):
""" """
@@ -317,8 +317,8 @@ class PersonalMessagesTest(AuthedTestCase):
sender_messages = len(self.message_stream(sender)) sender_messages = len(self.message_stream(sender))
receiver_messages = len(self.message_stream(receiver)) receiver_messages = len(self.message_stream(receiver))
other_user_profiles = UserProfile.objects.filter(~Q(user__email=sender_email) & other_user_profiles = UserProfile.objects.filter(~Q(email=sender_email) &
~Q(user__email=receiver_email)) ~Q(email=receiver_email))
old_other_messages = [] old_other_messages = []
for user_profile in other_user_profiles: for user_profile in other_user_profiles:
old_other_messages.append(len(self.message_stream(user_profile))) old_other_messages.append(len(self.message_stream(user_profile)))
@@ -375,7 +375,7 @@ class StreamMessagesTest(AuthedTestCase):
for non_subscriber in non_subscribers: for non_subscriber in non_subscribers:
old_non_subscriber_messages.append(len(self.message_stream(non_subscriber))) old_non_subscriber_messages.append(len(self.message_stream(non_subscriber)))
a_subscriber_email = subscribers[0].user.email a_subscriber_email = subscribers[0].email
self.login(a_subscriber_email) self.login(a_subscriber_email)
self.send_message(a_subscriber_email, stream_name, Recipient.STREAM, self.send_message(a_subscriber_email, stream_name, Recipient.STREAM,
subject, content) subject, content)
@@ -1676,7 +1676,7 @@ class GetSubscribersTest(AuthedTestCase):
""" """
self.assertIn("subscribers", result) self.assertIn("subscribers", result)
self.assertIsInstance(result["subscribers"], list) self.assertIsInstance(result["subscribers"], list)
true_subscribers = [user_profile.user.email for user_profile in self.users_subscribed_to_stream( true_subscribers = [user_profile.email for user_profile in self.users_subscribed_to_stream(
stream_name, domain)] stream_name, domain)]
self.assertItemsEqual(result["subscribers"], true_subscribers) self.assertItemsEqual(result["subscribers"], true_subscribers)
@@ -2297,7 +2297,7 @@ class UnreadCountTests(AuthedTestCase):
self.assertEqual(last.content, "Test message for unset read bit") self.assertEqual(last.content, "Test message for unset read bit")
for um in UserMessage.objects.filter(message=last): for um in UserMessage.objects.filter(message=last):
self.assertEqual(um.message.content, content) self.assertEqual(um.message.content, content)
if um.user_profile.user.email != "hamlet@humbughq.com": if um.user_profile.email != "hamlet@humbughq.com":
self.assertFalse(um.flags.read) self.assertFalse(um.flags.read)
def test_update_flags(self): def test_update_flags(self):
@@ -2407,7 +2407,7 @@ class JiraHookTests(AuthedTestCase):
api_key = self.get_api_key(email) api_key = self.get_api_key(email)
stream, _ = create_stream_if_needed(Realm.objects.get(domain="humbughq.com"), 'jira') stream, _ = create_stream_if_needed(Realm.objects.get(domain="humbughq.com"), 'jira')
user_profile = UserProfile.objects.get(user__email=email) user_profile = self.get_user_profile(email)
do_add_subscription(user_profile, stream, no_log=True) do_add_subscription(user_profile, stream, no_log=True)
result = self.client.post("/api/v1/external/jira/%s/" % api_key, self.fixture_data(action), result = self.client.post("/api/v1/external/jira/%s/" % api_key, self.fixture_data(action),
@@ -2416,7 +2416,7 @@ class JiraHookTests(AuthedTestCase):
# Check the correct message was sent # Check the correct message was sent
msg = Message.objects.filter().order_by('-id')[0] msg = Message.objects.filter().order_by('-id')[0]
self.assertEqual(msg.sender.user.email, email) self.assertEqual(msg.sender.email, email)
self.assertEqual(get_display_recipient(msg.recipient), 'jira') self.assertEqual(get_display_recipient(msg.recipient), 'jira')
return msg return msg

View File

@@ -117,7 +117,7 @@ def send_signup_message(sender, signups_stream, user_profile, internal=False):
"stream", signups_stream, user_profile.realm.domain, "stream", signups_stream, user_profile.realm.domain,
"%s <`%s`> just signed up for Humbug!%s(total: **%i**)" % ( "%s <`%s`> just signed up for Humbug!%s(total: **%i**)" % (
user_profile.full_name, user_profile.full_name,
user_profile.user.email, user_profile.email,
internal_blurb, internal_blurb,
UserProfile.objects.filter(realm=user_profile.realm, UserProfile.objects.filter(realm=user_profile.realm,
user__is_active=True).count(), user__is_active=True).count(),
@@ -224,10 +224,10 @@ def accounts_register(request):
if prereg_user.referred_by is not None: if prereg_user.referred_by is not None:
# This is a cross-realm private message. # This is a cross-realm private message.
internal_send_message("humbug+signups@humbughq.com", internal_send_message("humbug+signups@humbughq.com",
"private", prereg_user.referred_by.user.email, user_profile.realm.domain, "private", prereg_user.referred_by.email, user_profile.realm.domain,
"%s <`%s`> accepted your invitation to join Humbug!" % ( "%s <`%s`> accepted your invitation to join Humbug!" % (
user_profile.full_name, user_profile.full_name,
user_profile.user.email, user_profile.email,
) )
) )
@@ -242,7 +242,7 @@ def accounts_register(request):
@login_required(login_url = settings.HOME_NOT_LOGGED_IN) @login_required(login_url = settings.HOME_NOT_LOGGED_IN)
def accounts_accept_terms(request): def accounts_accept_terms(request):
email = request.user.email email = request.email
company_name = email.split('@')[-1] company_name = email.split('@')[-1]
if request.method == "POST": if request.method == "POST":
form = ToSForm(request.POST) form = ToSForm(request.POST)
@@ -271,7 +271,7 @@ def json_invite_users(request, user_profile, invitee_emails=POST):
# Validation # Validation
if settings.ALLOW_REGISTER == False: if settings.ALLOW_REGISTER == False:
try: try:
isnt_mit(user_profile.user.email) isnt_mit(user_profile.email)
except ValidationError: except ValidationError:
return json_error("Invitations are not enabled for MIT at this time.") return json_error("Invitations are not enabled for MIT at this time.")
@@ -427,7 +427,7 @@ def home(request):
people_list = register_ret['realm_users'], people_list = register_ret['realm_users'],
initial_pointer = register_ret['pointer'], initial_pointer = register_ret['pointer'],
fullname = user_profile.full_name, fullname = user_profile.full_name,
email = user_profile.user.email, email = user_profile.email,
domain = user_profile.realm.domain, domain = user_profile.realm.domain,
enter_sends = user_profile.enter_sends, enter_sends = user_profile.enter_sends,
needs_tutorial = needs_tutorial, needs_tutorial = needs_tutorial,
@@ -439,7 +439,7 @@ def home(request):
)) ))
try: try:
isnt_mit(user_profile.user.email) isnt_mit(user_profile.email)
show_invites = True show_invites = True
except ValidationError: except ValidationError:
show_invites = settings.ALLOW_REGISTER show_invites = settings.ALLOW_REGISTER
@@ -447,7 +447,7 @@ def home(request):
return render_to_response('zephyr/index.html', return render_to_response('zephyr/index.html',
{'user_profile': user_profile, {'user_profile': user_profile,
'page_params' : page_params, 'page_params' : page_params,
'email_hash' : gravatar_hash(user_profile.user.email), 'email_hash' : gravatar_hash(user_profile.email),
'show_debug': 'show_debug':
settings.DEBUG and ('show_debug' in request.GET), settings.DEBUG and ('show_debug' in request.GET),
'show_invites': show_invites 'show_invites': show_invites
@@ -547,7 +547,7 @@ class NarrowBuilder(object):
return Q(message__subject__iexact=operand) return Q(message__subject__iexact=operand)
def by_sender(self, operand): def by_sender(self, operand):
return Q(message__sender__user__email__iexact=operand) return Q(message__sender__email__iexact=operand)
def by_pm_with(self, operand): def by_pm_with(self, operand):
if ',' in operand: if ',' in operand:
@@ -562,7 +562,7 @@ class NarrowBuilder(object):
else: else:
# Personal message # Personal message
self_recipient = get_recipient(Recipient.PERSONAL, type_id=self.user_profile.id) self_recipient = get_recipient(Recipient.PERSONAL, type_id=self.user_profile.id)
if operand == self.user_profile.user.email: if operand == self.user_profile.email:
# Personals with self # Personals with self
return Q(message__recipient__type=Recipient.PERSONAL, return Q(message__recipient__type=Recipient.PERSONAL,
message__sender=self.user_profile, message__recipient=self_recipient) message__sender=self.user_profile, message__recipient=self_recipient)
@@ -762,13 +762,13 @@ def json_tutorial_send_message(request, user_profile,
# can only send to you. # can only send to you.
internal_send_message(sender_name, internal_send_message(sender_name,
"private", "private",
user_profile.user.email, user_profile.email,
"", "",
message_content, message_content,
realm=user_profile.realm) realm=user_profile.realm)
return json_success() return json_success()
elif message_type_name == 'stream': elif message_type_name == 'stream':
tutorial_stream_name = 'tutorial-%s' % user_profile.user.email.split('@')[0] tutorial_stream_name = 'tutorial-%s' % user_profile.email.split('@')[0]
tutorial_stream_name = tutorial_stream_name[:Stream.MAX_NAME_LENGTH] tutorial_stream_name = tutorial_stream_name[:Stream.MAX_NAME_LENGTH]
## TODO: For open realms, we need to use the full name here, ## TODO: For open realms, we need to use the full name here,
## so that me@gmail.com and me@hotmail.com don't get the same stream. ## so that me@gmail.com and me@hotmail.com don't get the same stream.
@@ -942,15 +942,15 @@ def add_subscriptions_backend(request, user_profile,
for subscriber in subscribers: for subscriber in subscribers:
did_subscribe = do_add_subscription(subscriber, stream) did_subscribe = do_add_subscription(subscriber, stream)
if did_subscribe: if did_subscribe:
result["subscribed"][subscriber.user.email].append(stream.name) result["subscribed"][subscriber.email].append(stream.name)
else: else:
result["already_subscribed"][subscriber.user.email].append(stream.name) result["already_subscribed"][subscriber.email].append(stream.name)
private_streams[stream.name] = stream.invite_only private_streams[stream.name] = stream.invite_only
# Inform the user if someone else subscribed them to stuff # Inform the user if someone else subscribed them to stuff
if principals and result["subscribed"]: if principals and result["subscribed"]:
for email, subscriptions in result["subscribed"].iteritems(): for email, subscriptions in result["subscribed"].iteritems():
if email == user_profile.user.email: if email == user_profile.email:
# Don't send a Humbug if you invited yourself. # Don't send a Humbug if you invited yourself.
continue continue
@@ -984,7 +984,7 @@ def json_get_members(request, user_profile):
return get_members_backend(request, user_profile) return get_members_backend(request, user_profile)
def get_members_backend(request, user_profile): def get_members_backend(request, user_profile):
members = [(profile.full_name, profile.user.email) for profile in \ members = [(profile.full_name, profile.email) for profile in \
UserProfile.objects.select_related().filter(realm=user_profile.realm)] UserProfile.objects.select_related().filter(realm=user_profile.realm)]
return json_success({'members': members}) return json_success({'members': members})
@@ -1012,7 +1012,7 @@ def get_subscribers_backend(request, user_profile, stream_name=POST('stream')):
recipient__type_id=stream.id, recipient__type_id=stream.id,
active=True).select_related() active=True).select_related()
return json_success({'subscribers': [subscription.user_profile.user.email return json_success({'subscribers': [subscription.user_profile.email
for subscription in subscriptions]}) for subscription in subscriptions]})
@authenticated_json_post_view @authenticated_json_post_view
@@ -1027,7 +1027,7 @@ def json_change_settings(request, user_profile, full_name=POST,
if new_password != "" or confirm_password != "": if new_password != "" or confirm_password != "":
if new_password != confirm_password: if new_password != confirm_password:
return json_error("New password must match confirmation password!") return json_error("New password must match confirmation password!")
if not authenticate(username=user_profile.user.email, password=old_password): if not authenticate(username=user_profile.email, password=old_password):
return json_error("Wrong password!") return json_error("Wrong password!")
do_change_password(user_profile, new_password) do_change_password(user_profile, new_password)
@@ -1111,7 +1111,7 @@ class SubscriptionProperties(object):
color = self.request_property(request.POST, "color") color = self.request_property(request.POST, "color")
set_stream_color(user_profile, stream_name, color) set_stream_color(user_profile, stream_name, color)
log_subscription_property_change(user_profile.user.email, "stream_color", log_subscription_property_change(user_profile.email, "stream_color",
{"stream_name": stream_name, "color": color}) {"stream_name": stream_name, "color": color})
return json_success() return json_success()
@@ -1190,10 +1190,10 @@ class ActivityTable(object):
for record in UserActivity.objects.filter( for record in UserActivity.objects.filter(
query=url, query=url,
client__name__startswith=client_name).select_related(): client__name__startswith=client_name).select_related():
row = self.rows.setdefault(record.user_profile.user.email, {}) row = self.rows.setdefault(record.user_profile.email, {})
row['realm'] = record.user_profile.realm.domain row['realm'] = record.user_profile.realm.domain
row['full_name'] = record.user_profile.full_name row['full_name'] = record.user_profile.full_name
row['email'] = record.user_profile.user.email row['email'] = record.user_profile.email
row[query_name + '_count'] = record.count row[query_name + '_count'] = record.count
row[query_name + '_last' ] = record.last_visit row[query_name + '_last' ] = record.last_visit
@@ -1399,7 +1399,7 @@ def get_status_list(requesting_user_profile):
user_profile__realm=requesting_user_profile.realm).select_related( user_profile__realm=requesting_user_profile.realm).select_related(
'user_profile', 'user_profile__user', 'client'): 'user_profile', 'user_profile__user', 'client'):
user_statuses[presence.user_profile.user.email][presence.client.name] = \ user_statuses[presence.user_profile.email][presence.client.name] = \
presence_to_dict(presence) presence_to_dict(presence)
return {'presences': user_statuses} return {'presences': user_statuses}
@@ -1445,7 +1445,7 @@ if not (settings.DEBUG or settings.TEST_SUITE):
@has_request_variables @has_request_variables
def json_report_error(request, user_profile, message=POST, stacktrace=POST, def json_report_error(request, user_profile, message=POST, stacktrace=POST,
ui_message=POST(converter=json_to_bool), user_agent=POST): ui_message=POST(converter=json_to_bool), user_agent=POST):
subject = "error for %s" % (user_profile.user.email,) subject = "error for %s" % (user_profile.email,)
if ui_message: if ui_message:
subject = "User-visible browser " + subject subject = "User-visible browser " + subject
else: else: