Skip to content

Commit

Permalink
Handle VATUSA outages on login
Browse files Browse the repository at this point in the history
  • Loading branch information
williammck committed Dec 7, 2024
1 parent 6c99d6b commit 9d4e387
Showing 1 changed file with 27 additions and 10 deletions.
37 changes: 27 additions & 10 deletions apps/vatsim/oauth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
from typing import Optional

import requests
from django.conf import settings
Expand Down Expand Up @@ -34,13 +35,6 @@ def process_oauth(code: str) -> User:
.get("data")
)

# Get user's home division. If they are in VATUSA get their home facility.
division = f"VAT{data.get('vatsim').get('division').get('id')}"
if division == "VATUSA":
req = requests.get(f"https://api.vatusa.net/v2/user/{data.get('cid')}")
if req.status_code == 200:
division = req.json().get("data").get("facility")

user_query = User.objects.filter(cid=data.get("cid"))
if not user_query.exists():
user = User.objects.create_user(
Expand All @@ -49,15 +43,38 @@ def process_oauth(code: str) -> User:
first_name=data.get("personal").get("name_first"),
last_name=data.get("personal").get("name_last"),
rating=data.get("vatsim").get("rating").get("short"),
home_facility=division,
home_facility=get_home_facility(
data.get("cid"),
data.get('vatsim').get('division').get('id'),
),
)
else:
user = user_query.first()
user.home_facility = division
user.home_facility = get_home_facility(
user.cid,
data.get('vatsim').get('division').get('id'),
user.home_facility,
)
user.rating = data.get("vatsim").get("rating").get("short")
user.save()

if division == "ZHU":
if user.home_facility == "ZHU":
user.set_membership("HC")

return user

# Get the user's home facility.
# Fallback to existing facility if VATUSA API is down.
def get_home_facility(cid: int, division: str, existing_facility: Optional[str] = None) -> str:
if division != "USA":
return f"VAT{division}"

req = requests.get(f"https://api.vatusa.net/v2/user/{cid}")

if req.status_code == 404:
return "VATUSA"

if req.status_code != 200:
return existing_facility or "VATUSA"

return req.json().get("data").get("facility")

0 comments on commit 9d4e387

Please sign in to comment.