Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
BrennanB committed Jul 21, 2024
2 parents 5ece469 + 5026adb commit 2c3ee03
Show file tree
Hide file tree
Showing 6 changed files with 77 additions and 17 deletions.
6 changes: 5 additions & 1 deletion discordoauth2/auth.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
from django.contrib.auth.backends import RemoteUserBackend
from .models import User
from typing import Union


class DiscordAuthenticationBackend(RemoteUserBackend):
def authenticate(self, request, user) -> User:
def authenticate(self, request, user) -> Union[User, None]:
found_user = User.objects.filter(id=user['id'])
if len(found_user) == 0:
# New user (first time login)
if user['email'] is None:
return None
new_user = User.objects.create_discord_user(user)
return new_user
# Returning user
Expand Down
14 changes: 12 additions & 2 deletions discordoauth2/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import Union
from django.http import JsonResponse, HttpRequest
from django.shortcuts import redirect, render
from django.contrib.auth import authenticate, login
Expand Down Expand Up @@ -36,20 +37,28 @@ def discord_api_login(request: HttpRequest):

def discord_login_redirect(request: HttpRequest):
user = exchange_code(request.GET.get('code'))
if user is None:
return redirect('/login-error/')
discord_user = authenticate(request, user=user)
if discord_user is None:
return redirect('/login-error/')
login(request, discord_user)
return redirect('/')


def discord_api_login_redirect(request: HttpRequest):
user = exchange_code(request.GET.get(
'code'), redirect_uri=DISCORD_API_REDIRECT_URI)
if user is None:
return redirect('/login-error/')
discord_user = authenticate(request, user=user)
if discord_user is None:
return redirect('/login-error/')
login(request, discord_user)
return redirect('/api/highscores/auth/')


def exchange_code(code: str, redirect_uri: str = DISCORD_REDIRECT_URI) -> requests.Response:
def exchange_code(code: str, redirect_uri: str = DISCORD_REDIRECT_URI) -> Union[requests.Response, None]:
data = {
'client_id': DISCORD_CLIENT_ID,
'client_secret': DISCORD_CLIENT_SECRET,
Expand All @@ -64,7 +73,8 @@ def exchange_code(code: str, redirect_uri: str = DISCORD_REDIRECT_URI) -> reques

response = requests.post('%s/oauth2/token' %
DISCORD_API_ENDPOINT, data=data, headers=headers)
response.raise_for_status()
if response.status_code != 200:
return None

response = requests.get('%s/users/@me' % DISCORD_API_ENDPOINT, headers={
'Authorization': 'Bearer %s' % response.json()['access_token']
Expand Down
52 changes: 38 additions & 14 deletions highscores/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ def submit_crescendo(score_obj: Score) -> Union[str, None]:
return submit_score(score_obj, crescendo_clean_code_check)


def submit_high_stakes(score_obj: Score) -> Union[str, None]:
return submit_score(score_obj, high_stakes_clean_code_check)


def decode_time_data(in_string: str) -> str:
out_bytes = ""

Expand Down Expand Up @@ -276,6 +280,10 @@ def crescendo_clean_code_check(score_obj: Score) -> Union[str, None]:
return clean_code_check(score_obj, check_crescendo_game_settings, check_subtraction_score)


def high_stakes_clean_code_check(score_obj: Score) -> Union[str, None]:
return clean_code_check(score_obj, check_high_stakes_game_settings, check_skills_challenge_score)


def extract_clean_code_info(score_obj: Score) -> tuple[str, list[str], str, str, str, str, str]:
""" Extracts the relevant information from the clean code.
:param score_obj: Score object to extract from
Expand Down Expand Up @@ -466,6 +474,20 @@ def check_crescendo_game_settings(game_options: list, restart_option: str, game_
return None # No error


def check_high_stakes_game_settings(game_options: list, restart_option: str, game_index: str) -> Union[str, None]:
""" Checks if the High Stakes game settings are valid.
:return: None if the settings are valid, or a response with an error message if they are not.
"""
if (game_index != '17'):
return 'Wrong game! This form is for High Stakes.'
if (restart_option != '2'):
return 'You must use restart option 2 (skills challenge) for High Stakes high score submissions.'
if (game_options[0] != '1'):
return 'You must have auto wall enabled for high score submissions.'

return None # No error


def check_robot_type(score_obj: Score, robot_model: str) -> Union[str, None]:
""" Checks if the robot model is valid.
:return: None if the robot model is valid, or a response with an error message if it is not.
Expand Down Expand Up @@ -555,23 +577,23 @@ def search_for_reused_code(score_obj: Score) -> Union[str, None]:

return 'That clean code has already been submitted by another player.'

# same ip but different player
ip_search = CleanCodeSubmission.objects.filter(
ip=score_obj.ip).exclude(player=score_obj.player)
# # same ip but different player
# ip_search = CleanCodeSubmission.objects.filter(
# ip=score_obj.ip).exclude(player=score_obj.player)

if ip_search.exists():
# Uh oh, there are multiple users submitting from the same IP.
# Report this via email.
# if ip_search.exists():
# # Uh oh, there are multiple users submitting from the same IP.
# # Report this via email.

message = f"{score_obj.player} ({score_obj.ip}) submitted a score (successfully): [{score_obj.score}] - {score_obj.leaderboard}\n\n This IP has also been used by {ip_search[0].player} ({ip_search[0].ip})\n\n {score_obj.source}\n\nhttps://secondrobotics.org/admin/highscores/score/"
try:
if (not DEBUG):
send_mail(f"Duplicate IP usage from {score_obj.player}",
message, EMAIL_HOST_USER, ADMIN_EMAILS, fail_silently=False)
except Exception as ex:
print(ex)
# message = f"{score_obj.player} ({score_obj.ip}) submitted a score (successfully): [{score_obj.score}] - {score_obj.leaderboard}\n\n This IP has also been used by {ip_search[0].player} ({ip_search[0].ip})\n\n {score_obj.source}\n\nhttps://secondrobotics.org/admin/highscores/score/"
# try:
# if (not DEBUG):
# send_mail(f"Duplicate IP usage from {score_obj.player}",
# message, EMAIL_HOST_USER, ADMIN_EMAILS, fail_silently=False)
# except Exception as ex:
# print(ex)

# Still allow the score to be submitted.
# # Still allow the score to be submitted.

return None # No error

Expand Down Expand Up @@ -631,6 +653,7 @@ def check_time_data(score_obj: Score) -> Union[str, None]:
"cs": submit_centerstage,
"ou": submit_over_under,
"cr": submit_crescendo,
"hs": submit_high_stakes,
}

game_to_submit_func = {
Expand All @@ -644,4 +667,5 @@ def check_time_data(score_obj: Score) -> Union[str, None]:
"CENTERSTAGE": submit_centerstage,
"Over Under": submit_over_under,
"Crescendo": submit_crescendo,
"High Stakes": submit_high_stakes,
}
17 changes: 17 additions & 0 deletions home/templates/home/login_error.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{% extends 'home/base.html' %} {% block content %}
<div
class="
position-relative
overflow-hidden
p-3 p-md-5
m-md-3
text-center
bg-danger
"
>
<div class="col-md-5 p-lg-5 mx-auto my-5">
<h1 class="display-4 fw-normal">Login error</h1>
<p>Ensure there is an email address attached to your discord account, and you select authorize.</p>
</div>
</div>
{% endblock %}
1 change: 1 addition & 0 deletions home/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@
path("privacy/", views.privacy, name="privacy"),
path("logopack/", views.logos, name="logos"),
path("link-success/", views.link_success, name="link success"),
path("login-error/", views.login_error, name="login error"),
]
4 changes: 4 additions & 0 deletions home/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ def login_page(request):
return redirect('/oauth2/login')


def login_error(request):
return render(request, "home/login_error.html", {})


def logout_user(request):
logout(request)
return redirect('/')
Expand Down

0 comments on commit 2c3ee03

Please sign in to comment.