|
| 1 | +"""Custom authentication for the forms backend.""" |
| 2 | + |
| 3 | +import typing |
| 4 | + |
| 5 | +import jwt |
| 6 | +from django.conf import settings |
| 7 | +from django.http import HttpRequest |
| 8 | +from rest_framework.authentication import BaseAuthentication |
| 9 | +from rest_framework.exceptions import AuthenticationFailed |
| 10 | + |
| 11 | +from . import discord |
| 12 | +from . import models |
| 13 | + |
| 14 | + |
| 15 | +def encode_jwt(info: dict, *, signing_secret_key: str = settings.SECRET_KEY): |
| 16 | + return jwt.encode(info, signing_secret_key, algorithm="HS256") |
| 17 | + |
| 18 | + |
| 19 | +class FormsUser: |
| 20 | + """Stores authentication information for a forms user.""" |
| 21 | + |
| 22 | + # This allows us to safely use the same checks that we could use on a Django user. |
| 23 | + is_authenticated: bool = True |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + token: str, |
| 28 | + payload: dict[str, typing.Any], |
| 29 | + member: models.DiscordMember | None, |
| 30 | + ) -> None: |
| 31 | + self.token = token |
| 32 | + self.payload = payload |
| 33 | + self.admin = False |
| 34 | + self.member = member |
| 35 | + |
| 36 | + @property |
| 37 | + def display_name(self) -> str: |
| 38 | + """Return username and discriminator as display name.""" |
| 39 | + return f"{self.payload['username']}#{self.payload['discriminator']}" |
| 40 | + |
| 41 | + @property |
| 42 | + def discord_mention(self) -> str: |
| 43 | + return f"<@{self.payload['id']}>" |
| 44 | + |
| 45 | + @property |
| 46 | + def user_id(self) -> str: |
| 47 | + return str(self.payload["id"]) |
| 48 | + |
| 49 | + @property |
| 50 | + def decoded_token(self) -> dict[str, any]: |
| 51 | + return jwt.decode(self.token, SECRET_KEY, algorithms=["HS256"]) |
| 52 | + |
| 53 | + def get_roles(self) -> tuple[str, ...]: |
| 54 | + """Get a tuple of the user's discord roles by name.""" |
| 55 | + if not self.member: |
| 56 | + return [] |
| 57 | + |
| 58 | + server_roles = discord.get_roles() |
| 59 | + roles = [role.name for role in server_roles if role.id in self.member.roles] |
| 60 | + |
| 61 | + if "admin" in roles: |
| 62 | + # Protect against collision with the forms admin role |
| 63 | + roles.remove("admin") |
| 64 | + roles.append("discord admin") |
| 65 | + |
| 66 | + return tuple(roles) |
| 67 | + |
| 68 | + def is_admin(self) -> bool: |
| 69 | + self.admin = models.Admin.objects.filter(id=self.payload["id"]).exists() |
| 70 | + return self.admin |
| 71 | + |
| 72 | + def refresh_data(self) -> None: |
| 73 | + """Fetches user data from discord, and updates the instance.""" |
| 74 | + self.member = discord.get_member(self.payload["id"]) |
| 75 | + |
| 76 | + if self.member: |
| 77 | + self.payload = self.member.user.dict() |
| 78 | + else: |
| 79 | + self.payload = discord.fetch_user_details(self.decoded_token.get("token")) |
| 80 | + |
| 81 | + updated_info = self.decoded_token |
| 82 | + updated_info["user_details"] = self.payload |
| 83 | + |
| 84 | + self.token = encode_jwt(updated_info) |
| 85 | + |
| 86 | + |
| 87 | +class AuthenticationResult(typing.NamedTuple): |
| 88 | + scopes: tuple[str, ...] |
| 89 | + |
| 90 | + |
| 91 | +# See https://www.django-rest-framework.org/api-guide/authentication/#custom-authentication |
| 92 | +class JWTAuthentication(BaseAuthentication): |
| 93 | + """Custom DRF authentication backend for JWT.""" |
| 94 | + |
| 95 | + @staticmethod |
| 96 | + def get_token_from_cookie(cookie: str) -> str: |
| 97 | + """Parse JWT token from cookie.""" |
| 98 | + |
| 99 | + try: |
| 100 | + prefix, token = cookie.split() |
| 101 | + except ValueError: |
| 102 | + msg = "Unable to split prefix and token from authorization cookie." |
| 103 | + raise AuthenticationFailed(msg) |
| 104 | + |
| 105 | + if prefix.upper() != "JWT": |
| 106 | + msg = f"Invalid authorization cookie prefix '{prefix}'." |
| 107 | + raise AuthenticationFailed(msg) |
| 108 | + |
| 109 | + return token |
| 110 | + |
| 111 | + def authenticate( |
| 112 | + self, |
| 113 | + request: HttpRequest, |
| 114 | + ) -> tuple[FormsUser, None] | None: |
| 115 | + """Handles JWT authentication process.""" |
| 116 | + |
| 117 | + cookie = request.COOKIES.get("token") |
| 118 | + if not cookie: |
| 119 | + return None |
| 120 | + |
| 121 | + token = self.get_token_from_cookie(cookie) |
| 122 | + |
| 123 | + try: |
| 124 | + # New key. |
| 125 | + payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) |
| 126 | + except jwt.InvalidTokenError as e: |
| 127 | + try: |
| 128 | + # Old key. Should be removed at a certain point. |
| 129 | + payload = jwt.decode(token, settings.FORMS_SECRET_KEY, algorithms=["HS256"]) |
| 130 | + except jwt.InvalidTokenError as e: |
| 131 | + raise AuthenticationFailed(str(e)) |
| 132 | + |
| 133 | + scopes = ["authenticated"] |
| 134 | + |
| 135 | + if not payload.get("token"): |
| 136 | + msg = "Token is missing from JWT." |
| 137 | + raise AuthenticationFailed(msg) |
| 138 | + if not payload.get("refresh"): |
| 139 | + msg = "Refresh token is missing from JWT." |
| 140 | + raise AuthenticationFailed(msg) |
| 141 | + |
| 142 | + try: |
| 143 | + user_details = payload.get("user_details") |
| 144 | + if not user_details or not user_details.get("id"): |
| 145 | + msg = "Improper user details." |
| 146 | + raise AuthenticationFailed(msg) # noqa: TRY301 |
| 147 | + except Exception: # noqa: BLE001 |
| 148 | + msg = "Could not parse user details." |
| 149 | + raise AuthenticationFailed(msg) |
| 150 | + |
| 151 | + user = FormsUser( |
| 152 | + token, |
| 153 | + user_details, |
| 154 | + discord.get_member(user_details["id"]), |
| 155 | + ) |
| 156 | + if user.is_admin(): |
| 157 | + scopes.append("admin") |
| 158 | + |
| 159 | + scopes.extend(user.get_roles()) |
| 160 | + |
| 161 | + return user, AuthenticationResult(scopes=tuple(scopes)) |
0 commit comments