Skip to content

Commit 6525554

Browse files
committed
Set up forms app with authentication
This begins the work of integrating the forms backend into the site. Changes, until complete, will be merged into the `forms` tracking branch.
1 parent 0014e90 commit 6525554

19 files changed

+1110
-0
lines changed

.coveragerc

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ omit =
1717
pydis_site/settings.py
1818
pydis_site/utils/resources.py
1919
pydis_site/apps/home/views.py
20+
# XXX: Will be covered later when FormsUser is used properly.
21+
pydis_site/apps/forms/authentication.py
22+
pydis_site/apps/forms/discord.py
23+
# XXX: Will be tested later
24+
pydis_site/apps/forms/permissions.py
2025

2126
[report]
2227
fail_under = 100

pydis_site/apps/forms/__init__.py

Whitespace-only changes.

pydis_site/apps/forms/admin.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
2+
# Register your models here.

pydis_site/apps/forms/apps.py

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

pydis_site/apps/forms/discord.py

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
"""API functions for Discord access."""
2+
3+
import httpx
4+
from django.conf import settings
5+
6+
from . import models
7+
from . import util
8+
9+
10+
__all__ = ("get_member", "get_roles")
11+
12+
13+
def fetch_and_update_roles() -> tuple[models.DiscordRole, ...]:
14+
"""Get information about roles from Discord."""
15+
with httpx.Client() as client:
16+
r = client.get(
17+
f"{settings.DISCORD_API_BASE_URL}/guilds/{settings.DISCORD_GUILD_ID}/roles",
18+
headers={"Authorization": f"Bot {settings.DISCORD_BOT_TOKEN}"},
19+
)
20+
21+
r.raise_for_status()
22+
return tuple(models.DiscordRole(**role) for role in r.json())
23+
24+
25+
def fetch_member_details(member_id: int) -> models.DiscordMember | None:
26+
"""Get a member by ID from the configured guild using the discord API."""
27+
with httpx.Client() as client:
28+
r = client.get(
29+
f"{settings.DISCORD_API_BASE_URL}/guilds/{settings.DISCORD_GUILD_ID}/members/{member_id}",
30+
headers={"Authorization": f"Bot {settings.DISCORD_BOT_TOKEN}"},
31+
)
32+
33+
if r.status_code == 404:
34+
return None
35+
36+
r.raise_for_status()
37+
return models.DiscordMember(**r.json())
38+
39+
40+
def fetch_user_details(bearer_token: str) -> dict:
41+
"""Fetch information about the Discord user associated with the given ``bearer_token``."""
42+
with httpx.Client() as client:
43+
r = client.get(
44+
f"{settings.DISCORD_API_BASE_URL}/users/@me",
45+
headers={
46+
"Authorization": f"Bearer {bearer_token}",
47+
},
48+
)
49+
50+
r.raise_for_status()
51+
52+
return r.json()
53+
54+
55+
def fetch_bearer_token(code: str, redirect: str, *, refresh: bool) -> dict:
56+
"""
57+
Fetch an OAuth2 bearer token.
58+
59+
## Arguments
60+
61+
- ``code``: The code or refresh token for the operation. Usually provided by Discord.
62+
- ``redirect``: Where to redirect the client after successful login.
63+
64+
## Keyword arguments
65+
66+
- ``refresh``: Whether to fetch a refresh token.
67+
"""
68+
with httpx.Client() as client:
69+
data = {
70+
"client_id": settings.DISCORD_OAUTH2_CLIENT_ID,
71+
"client_secret": settings.DISCORD_OAUTH2_CLIENT_SECRET,
72+
"redirect_uri": f"{redirect}/callback",
73+
}
74+
75+
if refresh:
76+
data["grant_type"] = "refresh_token"
77+
data["refresh_token"] = code
78+
else:
79+
data["grant_type"] = "authorization_code"
80+
data["code"] = code
81+
82+
r = client.post(
83+
f"{settings.DISCORD_API_BASE_URL}/oauth2/token",
84+
headers={
85+
"Content-Type": "application/x-www-form-urlencoded",
86+
},
87+
data=data,
88+
)
89+
90+
r.raise_for_status()
91+
92+
return r.json()
93+
94+
95+
def get_roles(*, force_refresh: bool = False, stale_after: int = 60 * 60 * 24) -> tuple[models.DiscordRole, ...]:
96+
"""
97+
Get a tuple of all roles from the cache, or discord API if not available.
98+
99+
## Keyword arguments
100+
101+
- `force_refresh` (`bool`): Skip the cache and always update the roles from
102+
Discord.
103+
- `stale_after` (`int`): Seconds after which to consider the stored roles
104+
as stale and to refresh them.
105+
"""
106+
if not force_refresh:
107+
roles = models.DiscordRole.objects.all()
108+
oldest = min(role.last_update for role in roles)
109+
if not util.is_stale(oldest, 60 * 60 * 24): # 1 day
110+
return tuple(roles)
111+
112+
return fetch_and_update_roles()
113+
114+
115+
def get_member(
116+
user_id: int,
117+
*,
118+
force_refresh: bool = False,
119+
) -> models.DiscordMember | None:
120+
"""
121+
Get a member from the cache, or from the discord API.
122+
123+
## Keyword arguments
124+
125+
- `force_refresh` (`bool`): Skip the cache and always update the roles from
126+
Discord.
127+
- `stale_after` (`int`): Seconds after which to consider the stored roles
128+
as stale and to refresh them.
129+
130+
## Return value
131+
132+
Returns `None` if the member object does not exist.
133+
"""
134+
if not force_refresh:
135+
member = models.DiscordMember.objects.get(id=user_id)
136+
if not util.is_stale(member.last_update, 60 * 60):
137+
return member
138+
139+
member = fetch_member_details(user_id)
140+
if member:
141+
member.save()
142+
143+
return member

0 commit comments

Comments
 (0)