2024-12-22 00:08:08 -05:00
|
|
|
import random
|
|
|
|
from urllib.parse import quote as url_escape
|
|
|
|
|
|
|
|
import requests
|
|
|
|
from django.core.handlers.wsgi import WSGIRequest
|
|
|
|
from django.http import HttpResponse
|
|
|
|
from django.template import loader
|
|
|
|
|
2024-12-23 13:21:56 -05:00
|
|
|
from tmessage.models import tMUser
|
2024-12-22 00:08:08 -05:00
|
|
|
from tmessage.settings import config
|
|
|
|
|
|
|
|
COLORS = ["rosewater", "flamingo", "pink", "mauve", "red", "maroon", "peach", "yellow", "green", "teal", "sky", "sapphire", "blue", "lavender"]
|
|
|
|
|
|
|
|
def render_template(
|
|
|
|
request: WSGIRequest,
|
|
|
|
template: str,
|
|
|
|
/, *,
|
|
|
|
status: int=200,
|
|
|
|
headers: dict[str, str]={},
|
|
|
|
content_type: str="text/html",
|
|
|
|
**context
|
|
|
|
) -> HttpResponse:
|
|
|
|
c = {
|
|
|
|
"accent": random.choice(COLORS),
|
2024-12-23 13:21:56 -05:00
|
|
|
"config": config,
|
|
|
|
"login_token": f"/auth/?sessionid={request.COOKIES.get('sessionid')}"
|
2024-12-22 00:08:08 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
for key, val in context.items():
|
|
|
|
c[key] = val
|
|
|
|
|
|
|
|
resp = HttpResponse(
|
|
|
|
loader.get_template(template).render(c, request),
|
|
|
|
status=status,
|
|
|
|
content_type=content_type
|
|
|
|
)
|
|
|
|
|
|
|
|
for key, val in headers.items():
|
|
|
|
resp[key] = val
|
|
|
|
|
|
|
|
return resp
|
|
|
|
|
2024-12-23 13:21:56 -05:00
|
|
|
def get_username(request: WSGIRequest) -> str | None:
|
2024-12-22 00:08:08 -05:00
|
|
|
resp = requests.get(config["services"]["auth"]["url"]["int"] + f"/api/authenticated/?token={url_escape(config['services']['message']['token'])}&service=message", cookies={**request.COOKIES}).json()
|
2024-12-23 13:21:56 -05:00
|
|
|
|
|
|
|
if not resp["success"]:
|
|
|
|
raise Exception("Unable to communicate with tAuth")
|
|
|
|
|
|
|
|
return resp["username"]
|
|
|
|
|
|
|
|
def username_exists(username: str) -> bool:
|
|
|
|
resp = requests.get(config["services"]["auth"]["url"]["int"] + f"/api/username/?token={url_escape(config['services']['message']['token'])}&service=message&username={url_escape(username)}").json()
|
|
|
|
|
|
|
|
if not resp["success"]:
|
|
|
|
raise Exception("Unable to communicate with tAuth")
|
|
|
|
|
|
|
|
return resp["exists"]
|
|
|
|
|
|
|
|
def get_user_object(username: str, *, i_promise_this_user_exists: bool=False) -> tMUser:
|
|
|
|
if i_promise_this_user_exists or username_exists(username):
|
|
|
|
try:
|
|
|
|
return tMUser.objects.get(username=username)
|
|
|
|
except tMUser.DoesNotExist:
|
|
|
|
return tMUser.objects.create(username=username)
|
|
|
|
|
|
|
|
else:
|
|
|
|
raise tMUser.DoesNotExist(f"tAuth doesn't know who {username} is")
|