message: Reorder checks in has_message_access.

This refactor makes this function easier to read and understand.
This commit is contained in:
Tim Abbott
2021-05-11 15:21:24 -07:00
committed by Tim Abbott
parent 237efdee6c
commit 44fddcc9c1

View File

@@ -679,43 +679,31 @@ def access_message(
def has_message_access( def has_message_access(
user_profile: UserProfile, message: Message, user_message: Optional[UserMessage] user_profile: UserProfile, message: Message, user_message: Optional[UserMessage]
) -> bool: ) -> bool:
if user_message is None: # If you have a user_message object, you have access.
if message.recipient.type != Recipient.STREAM: if user_message is not None:
# You can't access private messages you didn't receive return True
return False
stream = Stream.objects.get(id=message.recipient.type_id) if message.recipient.type != Recipient.STREAM:
if stream.realm != user_profile.realm: # You can't access private messages you didn't receive
# You can't access public stream messages in other realms return False
return False
if not stream.is_history_public_to_subscribers(): stream = Stream.objects.get(id=message.recipient.type_id)
# You can't access messages you didn't directly receive if stream.realm != user_profile.realm:
# unless history is public to subscribers. # You can't access public stream messages in other realms
return False return False
if not stream.is_public(): if not stream.is_history_public_to_subscribers():
# This stream is an invite-only stream where message # You can't access messages you didn't directly receive
# history is available to subscribers. So we check if # unless history is public to subscribers.
# you're subscribed. return False
if not Subscription.objects.filter(
user_profile=user_profile, active=True, recipient=message.recipient
).exists():
return False
# You are subscribed, so let this fall through to the public stream case. if stream.is_public() and user_profile.can_access_public_streams():
elif user_profile.is_guest: return True
# Guest users don't get automatic access to public stream messages
if not Subscription.objects.filter(
user_profile=user_profile, active=True, recipient=message.recipient
).exists():
return False
else:
# Otherwise, the message was sent to a public stream in
# your realm, so return the message, user_message pair
pass
return True # is_history_public_to_subscribers, so check if you're subscribed
return Subscription.objects.filter(
user_profile=user_profile, active=True, recipient=message.recipient
).exists()
def bulk_access_messages(user_profile: UserProfile, messages: Sequence[Message]) -> List[Message]: def bulk_access_messages(user_profile: UserProfile, messages: Sequence[Message]) -> List[Message]: