Skip to content

Commit

Permalink
fix: misc review fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
goteusz-maszyk committed Jun 12, 2024
1 parent 10b1a7d commit 651095f
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 84 deletions.
5 changes: 3 additions & 2 deletions core/context_processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ def sidebar_links(request):
return {}
links = {}
for role in user.roles.all():
if SIDEBAR_LINKS.get(role.permissions) is None:
permission_sidebar = SIDEBAR_LINKS.get(role.permissions)
if permission_sidebar is None:
continue
links[role.permissions] = SIDEBAR_LINKS.get(role.permissions)
links[role.permissions] = permission_sidebar
return {"sidebar_links": links}
49 changes: 21 additions & 28 deletions core/discord_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from django.core.handlers.wsgi import WSGIRequest
from django.urls import reverse
from django.utils import timezone
from requests import HTTPError
from requests.exceptions import JSONDecodeError

from core.models import User, UserRole
Expand Down Expand Up @@ -34,9 +33,7 @@ def authorise_code(request: WSGIRequest) -> dict[str, str] | None:
headers=headers,
auth=(CLIENT_ID, CLIENT_SECRET),
)
try:
response.raise_for_status()
except HTTPError:
if not response.ok:
return None
return response.json()

Expand All @@ -56,18 +53,8 @@ def refresh_access_token(refresh_token):


def fetch_user(access_token: str) -> User | None:
headers = {
"Authorization": f"Bearer {access_token}",
}
response = requests.get(
f"{API_ENDPOINT}/oauth2/@me",
headers=headers,
)
if not response.ok:
return None
try:
json = response.json()
except JSONDecodeError:
json = json_api_get("/oauth2/@me", access_token)
if json is None:
return None

user = User.objects.get_or_create(discord_id=json["user"]["id"])[0]
Expand All @@ -86,25 +73,31 @@ def fetch_user_details(access_token: str) -> bool:
:param access_token: access token for Discord API
:return: True if data was fetched successfully
"""
json = json_api_get(f"/users/@me/guilds/{GUILD_ID}/member", access_token)
if json is None:
return False

user = User.objects.get_or_create(discord_id=json["user"]["id"])[0]
for role_id in json["roles"]:
try:
role = UserRole.objects.get(id=role_id)
user.roles.add(role)
except UserRole.DoesNotExist:
pass
return True


def json_api_get(endpoint: str, access_token: str):
headers = {
"Authorization": f"Bearer {access_token}",
}
response = requests.get(
f"{API_ENDPOINT}/users/@me/guilds/{GUILD_ID}/member",
f"{API_ENDPOINT}{endpoint}",
headers=headers,
)
if not response.ok:
return False
return None
try:
json = response.json()
return response.json()
except JSONDecodeError:
return False
user = User.objects.get_or_create(discord_id=json["user"]["id"])[0]
for role_id in json["roles"]:
try:
role = UserRole.objects.get(id=role_id)
user.roles.add(role)
except UserRole.DoesNotExist:
pass
return True
return None
19 changes: 8 additions & 11 deletions core/discord_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,19 @@


def user_logged_in(request: HttpRequest) -> User | None:
"""Returns user if logged in. If not, returns 0 when session should be refreshed or 1 when session is invalid."""
"""Returns user if logged in."""
token = request.COOKIES.get(DISCORD_TOKEN_COOKIE)
if token is None:
return None

discord_id = request.COOKIES.get(DISCORD_ID_COOKIE)
discord_id = int(request.COOKIES.get(DISCORD_ID_COOKIE))
fetched_user = fetch_user(token)
if discord_id is None:
user = fetch_user(token)
else:
try:
user = User.objects.get(discord_id=discord_id)
if fetch_user(token) != user:
return None
except User.DoesNotExist or ValueError:
return None
return user
return fetched_user
elif fetched_user.discord_id != discord_id:
print(fetched_user.discord_id, discord_id)
return None
return User.objects.get(discord_id=discord_id)


def require_no_user():
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Generated by Django 5.0.4 on 2024-05-07 20:06

import core.models
import datetime
from django.db import migrations, models


Expand All @@ -19,6 +21,12 @@ class Migration(migrations.Migration):
),
),
("name", models.CharField()),
(
"permissions",
models.CharField(
choices=core.models.get_permission_choices, default=""
),
),
],
),
migrations.CreateModel(
Expand All @@ -37,6 +45,14 @@ class Migration(migrations.Migration):
("username", models.CharField()),
("avatar_hash", models.CharField()),
("roles", models.ManyToManyField(to="core.userrole")),
(
"data_valid_until",
models.DateTimeField(
default=datetime.datetime(
1971, 1, 1, 0, 0, tzinfo=datetime.timezone.utc
)
),
),
],
),
]
22 changes: 0 additions & 22 deletions core/migrations/0002_user_data_valid_until.py

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def remove_default_roles(apps, schema_editor):

class Migration(migrations.Migration):
dependencies = [
("core", "0003_userrole_permissions"),
("core", "0001_users_initial"),
]

operations = [migrations.RunPython(create_default_roles, remove_default_roles)]
20 changes: 0 additions & 20 deletions core/migrations/0003_userrole_permissions.py

This file was deleted.

0 comments on commit 651095f

Please sign in to comment.