CustomIWMServer/customiwmserver/database.py
magmaus3 9d59b8882b
Add more security
still insecure but slightly less :3
2023-07-07 19:20:32 +02:00

76 lines
2.3 KiB
Python

from datetime import datetime
from typing import Literal
from pymongo import MongoClient
from itsdangerous.serializer import Serializer
from itsdangerous import TimestampSigner
from os import environ, urandom
import json
# Database
client = MongoClient("mongodb://root:catboys@mongo:27017")
db = client["IWM_CustomServer_DB"]
user_collection = db.users
maps_collection = db.maps
reports_collection = db.reports
general_collection = db.general
admin_log_collection = db.admin_log
# Auth token stuff
SECRET_KEY = environ.get("SECRET_KEY", urandom(32).hex())
# s = TimestampSigner(SECRET_KEY)
s = TimestampSigner(SECRET_KEY)
def LogAdminAction(
action_type: str, action_data: dict, UserID: int = None, success: bool = True
):
"""Log administrator action."""
admin_log_collection.insert_one(
{
"date": datetime.utcnow(),
"action_type": action_type,
"action_data": action_data,
}
)
def login_auth_check(username: str, password: str):
# FIXME: This function currently DOES NOT perform any authentication.
# This means that ANYONE knowing the username could perform actions as the user.
query = user_collection.find_one({"Username": username})
if not query:
return False, "noauth"
return True, query
def auth_check(Authorization) -> (tuple[Literal[False], Literal["noauth"]] | tuple[Literal[True], dict]):
"""Checks credentials.
Returns a tuple with result (for example False, "nouser").
Results:
- False if wrong username or password
- True, [dict] if correct
"""
# FIXME (not relevant here anymore): This function currently DOES NOT perform any authentication.
# This means that ANYONE knowing the username could perform actions as the user.
if Authorization is None:
return False, "noauth"
# In this case I assume that the server already authenticated the user,
# and signed the token.
username = s.unsign(Authorization).decode()
print("DBG[auth_check]:", username)
query = user_collection.find_one({"Username": username})
if not query:
return False, "noauth"
# if query["Password"] != password:
# return False, "wrongpass"
return True, query
def id_to_mapcode(id_):
return hex(id_).replace("0x", "").rjust(8, "0")[0:8].upper()