mypy: Fix most AnonymousUser type errors.

This commit fixes several mypy errors with Django stubs, by telling
mypy that we know in a given code path that the user is authenticated.
This commit is contained in:
Tim Abbott 2021-07-24 11:37:35 -07:00
parent 4713f78d2e
commit 01ce58319d
10 changed files with 23 additions and 4 deletions

View File

@ -64,6 +64,8 @@ def payment_method_string(stripe_customer: stripe.Customer) -> str:
@zulip_login_required
def billing_home(request: HttpRequest) -> HttpResponse:
user = request.user
assert user.is_authenticated
customer = get_customer_by_realm(user.realm)
context: Dict[str, Any] = {
"admin_access": user.has_billing_access,

View File

@ -143,6 +143,7 @@ def upgrade(
@zulip_login_required
def initial_upgrade(request: HttpRequest) -> HttpResponse:
user = request.user
assert user.is_authenticated
if not settings.BILLING_ENABLED or user.is_guest:
return render(request, "404.html", status=404)

View File

@ -176,7 +176,7 @@ def require_billing_access(func: ViewFuncT) -> ViewFuncT:
def process_client(
request: HttpRequest,
user_profile: UserProfile,
user: Union[UserProfile, AnonymousUser],
*,
is_browser_view: bool = False,
client_name: Optional[str] = None,
@ -198,8 +198,8 @@ def process_client(
client_name = "website"
request_notes.client = get_client(client_name)
if not skip_update_user_activity and user_profile.is_authenticated:
update_user_activity(request, user_profile, query)
if not skip_update_user_activity and user.is_authenticated:
update_user_activity(request, user, query)
class InvalidZulipServerError(JsonableError):
@ -466,6 +466,7 @@ def add_logging_data(view_func: ViewFuncT) -> ViewFuncT:
def human_users_only(view_func: ViewFuncT) -> ViewFuncT:
@wraps(view_func)
def _wrapped_view_func(request: HttpRequest, *args: object, **kwargs: object) -> HttpResponse:
assert request.user.is_authenticated
if request.user.is_bot:
raise JsonableError(_("This endpoint does not accept bot requests."))
return view_func(request, *args, **kwargs)

View File

@ -164,6 +164,8 @@ def standardize_headers(input_headers: Union[None, Dict[str, Any]]) -> Dict[str,
def validate_extract_webhook_http_header(
request: HttpRequest, header: str, integration_name: str, fatal: bool = True
) -> Optional[str]:
assert request.user.is_authenticated
extracted_header = request.META.get(DJANGO_HTTP_PREFIX + header)
if extracted_header is None and fatal:
message_body = MISSING_EVENT_HEADER_MESSAGE.format(

View File

@ -397,6 +397,8 @@ class LogRequests(MiddlewareMixin):
request_notes = get_request_notes(request)
requestor_for_logs = request_notes.requestor_for_logs
if requestor_for_logs is None:
# Note that request.user is a Union[RemoteZulipServer, UserProfile, AnonymousUser],
# if it is present.
if hasattr(request, "user") and hasattr(request.user, "format_requestor_for_logs"):
requestor_for_logs = request.user.format_requestor_for_logs()
else:

View File

@ -851,6 +851,8 @@ def api_fetch_api_key(
if user_profile is None:
raise AuthenticationFailedError()
assert user_profile.is_authenticated
# Maybe sending 'user_logged_in' signal is the better approach:
# user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile)
# Not doing this only because over here we don't add the user information

View File

@ -13,6 +13,7 @@ from zerver.lib.digest import DIGEST_CUTOFF, get_digest_context
@zulip_login_required
def digest_page(request: HttpRequest) -> HttpResponse:
user_profile = request.user
assert user_profile.is_authenticated
cutoff = time.mktime((timezone_now() - timedelta(days=DIGEST_CUTOFF)).timetuple())
context = get_digest_context(user_profile, cutoff)

View File

@ -37,6 +37,8 @@ def need_accept_tos(user_profile: Optional[UserProfile]) -> bool:
@zulip_login_required
def accounts_accept_terms(request: HttpRequest) -> HttpResponse:
assert request.user.is_authenticated
if request.method == "POST":
form = ToSForm(request.POST)
if form.is_valid():

View File

@ -226,7 +226,7 @@ def send_message_backend(
client = get_request_notes(request).client
assert client is not None
can_forge_sender = request.user.can_forge_sender
can_forge_sender = user_profile.can_forge_sender
if forged and not can_forge_sender:
raise JsonableError(_("User not authorized for this query"))

View File

@ -77,6 +77,8 @@ def get_zoom_sid(request: HttpRequest) -> str:
@zulip_login_required
@never_cache
def register_zoom_user(request: HttpRequest) -> HttpResponse:
assert request.user.is_authenticated
oauth = get_zoom_session(request.user)
authorization_url, state = oauth.authorization_url(
"https://zoom.us/oauth/authorize",
@ -109,6 +111,8 @@ def complete_zoom_user_in_realm(
json_validator=check_dict([("sid", check_string)], value_validator=check_string)
),
) -> HttpResponse:
assert request.user.is_authenticated
if not constant_time_compare(state["sid"], get_zoom_sid(request)):
raise JsonableError(_("Invalid Zoom session identifier"))
@ -212,6 +216,8 @@ def join_bigbluebutton(
password: str = REQ(),
checksum: str = REQ(),
) -> HttpResponse:
assert request.user.is_authenticated
if settings.BIG_BLUE_BUTTON_URL is None or settings.BIG_BLUE_BUTTON_SECRET is None:
raise JsonableError(_("BigBlueButton is not configured."))
else: