aboutsummaryrefslogtreecommitdiffstats
path: root/backend/authentication
diff options
context:
space:
mode:
authorGravatar Joe Banks <[email protected]>2024-07-08 15:09:17 +0100
committerGravatar GitHub <[email protected]>2024-07-08 15:09:17 +0100
commit642c0795c8738bf8b9ae39b9cf0180f7cdbac650 (patch)
tree4a075255d00d9f8a2f369567bdb79f6eefa4be9a /backend/authentication
parentMigration to official Sentry release CI action (#275) (diff)
parentStop using gunicorn and use uvicorn directly to run application (diff)
Merge pull request #276 from python-discord/jb3/environ/python-3.12
3.12 + Updates
Diffstat (limited to 'backend/authentication')
-rw-r--r--backend/authentication/backend.py41
-rw-r--r--backend/authentication/user.py14
2 files changed, 28 insertions, 27 deletions
diff --git a/backend/authentication/backend.py b/backend/authentication/backend.py
index 54385e2..2512761 100644
--- a/backend/authentication/backend.py
+++ b/backend/authentication/backend.py
@@ -1,11 +1,9 @@
-import typing as t
-
import jwt
from starlette import authentication
from starlette.requests import Request
-from backend import constants
-from backend import discord
+from backend import constants, discord
+
# We must import user such way here to avoid circular imports
from .user import User
@@ -19,20 +17,19 @@ class JWTAuthenticationBackend(authentication.AuthenticationBackend):
try:
prefix, token = cookie.split()
except ValueError:
- raise authentication.AuthenticationError(
- "Unable to split prefix and token from authorization cookie."
- )
+ msg = "Unable to split prefix and token from authorization cookie."
+ raise authentication.AuthenticationError(msg)
if prefix.upper() != "JWT":
- raise authentication.AuthenticationError(
- f"Invalid authorization cookie prefix '{prefix}'."
- )
+ msg = f"Invalid authorization cookie prefix '{prefix}'."
+ raise authentication.AuthenticationError(msg)
return token
async def authenticate(
- self, request: Request
- ) -> t.Optional[tuple[authentication.AuthCredentials, authentication.BaseUser]]:
+ self,
+ request: Request,
+ ) -> tuple[authentication.AuthCredentials, authentication.BaseUser] | None:
"""Handles JWT authentication process."""
cookie = request.cookies.get("token")
if not cookie:
@@ -48,21 +45,25 @@ class JWTAuthenticationBackend(authentication.AuthenticationBackend):
scopes = ["authenticated"]
if not payload.get("token"):
- raise authentication.AuthenticationError("Token is missing from JWT.")
+ msg = "Token is missing from JWT."
+ raise authentication.AuthenticationError(msg)
if not payload.get("refresh"):
- raise authentication.AuthenticationError(
- "Refresh token is missing from JWT."
- )
+ msg = "Refresh token is missing from JWT."
+ raise authentication.AuthenticationError(msg)
try:
user_details = payload.get("user_details")
if not user_details or not user_details.get("id"):
- raise authentication.AuthenticationError("Improper user details.")
- except Exception:
- raise authentication.AuthenticationError("Could not parse user details.")
+ msg = "Improper user details."
+ raise authentication.AuthenticationError(msg) # noqa: TRY301
+ except Exception: # noqa: BLE001
+ msg = "Could not parse user details."
+ raise authentication.AuthenticationError(msg)
user = User(
- token, user_details, await discord.get_member(request.state.db, user_details["id"])
+ token,
+ user_details,
+ await discord.get_member(request.state.db, user_details["id"]),
)
if await user.fetch_admin_status(request.state.db):
scopes.append("admin")
diff --git a/backend/authentication/user.py b/backend/authentication/user.py
index cd5a249..c81b7a9 100644
--- a/backend/authentication/user.py
+++ b/backend/authentication/user.py
@@ -1,4 +1,3 @@
-import typing
import typing as t
import jwt
@@ -16,7 +15,7 @@ class User(BaseUser):
self,
token: str,
payload: dict[str, t.Any],
- member: typing.Optional[models.DiscordMember],
+ member: models.DiscordMember | None,
) -> None:
self.token = token
self.payload = payload
@@ -31,11 +30,11 @@ class User(BaseUser):
@property
def display_name(self) -> str:
"""Return username and discriminator as display name."""
- return f"{self.payload['username']}#{self.payload['discriminator']}"
+ return f"{self.payload["username"]}#{self.payload["discriminator"]}"
@property
def discord_mention(self) -> str:
- return f"<@{self.payload['id']}>"
+ return f"<@{self.payload["id"]}>"
@property
def user_id(self) -> str:
@@ -61,9 +60,10 @@ class User(BaseUser):
return roles
async def fetch_admin_status(self, database: Database) -> bool:
- self.admin = await database.admins.find_one(
- {"_id": self.payload["id"]}
- ) is not None
+ query = {"_id": self.payload["id"]}
+ found_admin = await database.admins.find_one(query)
+
+ self.admin = found_admin is not None
return self.admin