response: Replace json_unauthorized with UnauthorizedError.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
This commit is contained in:
Zixuan James Li
2022-07-12 21:29:39 -04:00
committed by Tim Abbott
parent 31c7344979
commit 159449b448
3 changed files with 32 additions and 27 deletions

View File

@@ -36,6 +36,7 @@ class ErrorCode(Enum):
PASSWORD_AUTH_DISABLED = auto()
PASSWORD_RESET_REQUIRED = auto()
AUTHENTICATION_FAILED = auto()
UNAUTHORIZED = auto()
class JsonableError(Exception):
@@ -124,6 +125,28 @@ class JsonableError(Exception):
return self.msg
class UnauthorizedError(JsonableError):
code: ErrorCode = ErrorCode.UNAUTHORIZED
http_status_code: int = 401
def __init__(self, msg: Optional[str] = None, www_authenticate: Optional[str] = None) -> None:
if msg is None:
msg = _("Not logged in: API authentication or user session required")
super().__init__(msg)
if www_authenticate is None:
self.www_authenticate = 'Basic realm="zulip"'
elif www_authenticate == "session":
self.www_authenticate = 'Session realm="zulip"'
else:
raise AssertionError("Invalid www_authenticate value!")
@property
def extra_headers(self) -> Dict[str, Any]:
extra_headers_dict = super().extra_headers
extra_headers_dict["WWW-Authenticate"] = self.www_authenticate
return extra_headers_dict
class StreamDoesNotExistError(JsonableError):
code = ErrorCode.STREAM_DOES_NOT_EXIST
data_fields = ["stream"]