Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

2fa: Refactor is_2fa_verified to require type narrowing.

Zixuan James Li06d3f3cf649d
diff --git a/zerver/decorator.py b/zerver/decorator.py
index 1c89f9c33d5..ef0374f2003 100644
--- a/zerver/decorator.py
+++ b/zerver/decorator.py
@@ -1046,15 +1046,15 @@ def zulip_otp_required_if_logged_in(
if not if_configured:
return True
- # User has completed 2FA verification
- if is_2fa_verified(user):
- return True
-
# This request is unauthenticated (logged-out) access; 2FA is
# not required or possible.
if not user.is_authenticated:
return True
+ # User has completed 2FA verification
+ if is_2fa_verified(user):
+ return True
+
# If the user doesn't have 2FA set up, we can't enforce 2FA.
if not user_has_device(user):
return True
diff --git a/zerver/lib/users.py b/zerver/lib/users.py
index 8a81d4f792a..92075ec1937 100644
--- a/zerver/lib/users.py
+++ b/zerver/lib/users.py
@@ -1,11 +1,10 @@
import re
import unicodedata
from collections import defaultdict
-from typing import Any, Dict, Iterable, List, Optional, Sequence, TypedDict, Union
+from typing import Any, Dict, Iterable, List, Optional, Sequence, TypedDict
import dateutil.parser as date_parser
from django.conf import settings
-from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ValidationError
from django.db.models.query import QuerySet
from django.forms.models import model_to_dict
@@ -622,7 +621,7 @@ def get_active_bots_owned_by_user(user_profile: UserProfile) -> QuerySet[UserPro
return UserProfile.objects.filter(is_bot=True, is_active=True, bot_owner=user_profile)
-def is_2fa_verified(user: Union[UserProfile, AnonymousUser]) -> bool:
+def is_2fa_verified(user: UserProfile) -> bool:
"""
It is generally unsafe to call is_verified directly on `request.user` since
the attribute `otp_device` does not exist on an `AnonymousUser`, and `is_verified`
@@ -633,4 +632,4 @@ def is_2fa_verified(user: Union[UserProfile, AnonymousUser]) -> bool:
# Explicitly require the caller to ensure that settings.TWO_FACTOR_AUTHENTICATION_ENABLED
# is True before calling `is_2fa_verified`.
assert settings.TWO_FACTOR_AUTHENTICATION_ENABLED
- return user.is_authenticated and is_verified(user)
+ return is_verified(user)
diff --git a/zerver/views/auth.py b/zerver/views/auth.py
index 61921c2e546..5f6f95fa067 100644
--- a/zerver/views/auth.py
+++ b/zerver/views/auth.py
@@ -764,7 +764,7 @@ def login_page(
# logged-in app.
is_preview = "preview" in request.GET
if settings.TWO_FACTOR_AUTHENTICATION_ENABLED:
- if request.user and is_2fa_verified(request.user):
+ if request.user.is_authenticated and is_2fa_verified(request.user):
return HttpResponseRedirect(request.user.realm.uri)
elif request.user.is_authenticated and not is_preview:
return HttpResponseRedirect(request.user.realm.uri)