Files
StingNET/server/main.py
T
Ponali a83ad194eb added admins and banning
this took more time than i thought it would
2026-08-07 16:44:28 +02:00

325 lines
14 KiB
Python

#!/usr/bin/env python
import asyncio
import json, random, re, math, time, traceback, datetime, humanize
from websockets.exceptions import ConnectionClosed, ConnectionClosedOK
from websockets.asyncio.server import serve
from db import Database
userdb = Database("users")
userdb.createTable("NAMES",{"id":"int","name":"string","creation_date":"int","last_login":"int","last_namechange":"int"})
userdb.createTable("PASSWORDS",{"id":"int","sum":"string"})
userdb.createTable("ADMIN",{"id":"int","is_admin":"int"})
userdb.createTable("BANNED",{"id":"int","is_banned":"int","motive":"str","ban_date":"int","expire_date":"int"})
isetdb = Database("isettings")
isetdb.createTable("BASIC",{"id":"int","color":"int","encoding":"str"})
def makeUserID() -> int:
count = userdb.rowAmount("NAMES")
digits = max(4,1+int(math.log10(10+count)))
uid=0
while uid==0 or userdb.hasPK("NAMES","id",uid) or userdb.hasPK("PASSWORDS","id",uid):
uid = random.randint(0,(10**digits)-1) & 0x7FFFFFFFFFFFFFFF
return uid
def isValidUsername(name) -> bool:
if len(name)<3 or len(name)>16: return False
pattern = re.compile("^[a-z][a-z0-9-_]*")
match = pattern.match(name)
if match==None: return False
return match.start()==0 and match.end()==len(name)
def isValidChecksum(cs) -> bool:
if len(cs)!=32: return False
pattern = re.compile("^[0-9a-f]*")
match = pattern.match(cs)
if match==None: return False
return match.start()==0 and match.end()==len(cs)
def isValidSimpleName(name) -> bool:
if len(name)==0: return False
pattern = re.compile("^[a-z][a-z0-9-_]*")
match = pattern.match(name.lower())
if match==None: return False
return match.start()==0 and match.end()==len(name)
def response(msg,**kwargs) -> str:
return json.dumps({"type":"response","response":msg,**kwargs})
def clientError(msg,**kwargs) -> str:
return json.dumps({"type":"error","error":msg,"server":False,**kwargs})
def serverError(msg,**kwargs) -> str:
print(f"Server error: {msg}")
return json.dumps({"type":"error","error":msg,"server":True,**kwargs})
sessionUsers = {}
sessionCreatedAccount = []
def forgetSession(sid):
if sid in sessionUsers:
del sessionUsers[sid]
if sid in sessionCreatedAccount:
sessionCreatedAccount.remove(sid)
def isAdmin(uid):
try:
if uid == None: return False
if not userdb.tableExists("ADMIN"): return False
row = userdb.rowFromPK("ADMIN","id",uid)
if row==None: return False
if int(row["is_admin"])!=1: return False
return True
except Exception:
return False
def isBanned(uid):
if not userdb.tableExists("BANNED"): return False
row = userdb.rowFromPK("BANNED","id",uid)
if row==None: return False
if int(row["is_banned"])==1:
if row["expire_date"]!=0 and time.time()>row["expire_date"]:
userdb.updateFromPK("BANNED","id",uid,{"is_banned":0})
return False
return True
return False
async def handleCommand(ws,cmd):
global sessionUsers
print(f"recieved command: {cmd} (from {id(ws)})")
if not "type" in cmd:
return await ws.send(clientError("Malformed command"))
uid = None
if id(ws) in sessionUsers:
uid = sessionUsers[id(ws)]
match cmd["type"]:
case "ping":
return await ws.send(response("Pong!"))
# accounts
case "createuser":
if uid != None:
return await ws.send(clientError("You are already logged in."))
uid = makeUserID()
name = cmd["name"]
name = name.lower()
if not isValidUsername(name):
return await ws.send(clientError("Username is not valid."))
if userdb.findRow("NAMES","name = ?",(name,))!=None:
return await ws.send(clientError(f"The username '{name}' is already taken."))
psum = cmd["pass"]
psum = psum.lower()
if not isValidChecksum(psum):
return await ws.send(clientError("Recieved password has not been correctly checksummed."))
if id(ws) in sessionCreatedAccount: raise
sessionCreatedAccount.append(id(ws))
create = time.time()
userdb.insertRow("NAMES",{"id":uid,"name":cmd["name"],"creation_date":create,"last_login":create,"last_namechange":create})
userdb.insertRow("PASSWORDS",{"id":uid,"sum":psum})
return await ws.send(response({"uid":uid}))
case "login":
if uid != None:
return await ws.send(clientError("You are already logged in."))
name = cmd["name"]
psum = cmd["pass"]
if not isValidUsername(name):
return await ws.send(clientError("Username is not valid."))
res = userdb.findRow("NAMES","name = ?",(name,))
if res==None:
return await ws.send(clientError("Invalid username or password."))
uid = res["id"]
if not isValidChecksum(psum):
return await ws.send(clientError("Recieved password has not been correctly checksummed."))
dbsum = userdb.rowFromPK("PASSWORDS","id",uid)["sum"]
if psum.lower() != dbsum.lower():
return await ws.send(clientError("Invalid username or password."))
if isBanned(uid):
row = userdb.rowFromPK("BANNED","id",uid)
expire = row["expire_date"]
timemsg = "You are permanently banned." if expire==0 else f"You will be unbanned in {humanize.naturaltime(datetime.datetime.fromtimestamp(expire))}."
return await ws.send(clientError(f"Your account has been banned!\nMovite: {row["motive"]}\n\n{timemsg}"))
print(f"session {id(ws)} has logged in as {name} ({uid})")
sessionUsers[id(ws)] = uid
userdb.updateFromPK("NAMES","id",uid,{"last_login":time.time()})
return await ws.send(response("success"))
case "logout":
if uid == None:
return await ws.send(clientError("You are already logged out."))
del sessionUsers[id(ws)]
return await ws.send(response("success"))
case "status":
if uid == None:
return await ws.send(response({"login":False}))
name = userdb.rowFromPK("NAMES","id",uid)["name"]
return await ws.send(response({"login":True,"uid":uid,"name":name,"admin":isAdmin(uid)}))
case "changename":
if uid == None:
return await ws.send(clientError("You are not logged in."))
name = cmd["name"]
if not isValidUsername(name):
return await ws.send(clientError("Username is not valid."))
if userdb.findRow("NAMES","name = ?",(name,))!=None:
return await ws.send(clientError(f"The username '{name}' is already taken."))
lastchange = userdb.rowFromPK("NAMES","id",uid)["last_namechange"]
if lastchange == None: lastchange = 0
if (lastchange+7*24*60*60)>time.time():
return await ws.send(clientError("You can only change your username after 7 days."))
userdb.updateFromPK("NAMES","id",uid,{"name":name,"last_namechange":time.time()})
return await ws.send(response("success"))
case "changepass":
if uid == None:
return await ws.send(clientError("You are not logged in."))
oldpass = cmd["oldpass"].lower()
newpass = cmd["newpass"].lower()
if not (isValidChecksum(oldpass) and isValidChecksum(newpass)):
return await ws.send(clientError("Recieved password has not been correctly checksummed."))
dbpass = userdb.rowFromPK("PASSWORDS","id",uid)["sum"].lower()
if oldpass != dbpass:
return await ws.send(clientError("Invalid username or password."))
userdb.updateFromPK("PASSWORDS","id",uid,{"sum":newpass})
return await ws.send(response("success"))
case "getuserinfo":
if "name" in cmd:
name = cmd["name"]
row = userdb.findRow("NAMES","name = ?",(name,))
if not row: await ws.send(clientError("Cannot find this user."))
auid = row["id"]
else:
auid = row["id"]
row = userdb.rowFromPK("NAMES","id",auid)
if not row: await ws.send(clientError("Cannot find this user."))
name = row["name"]
banned = isBanned(auid)
ban_details = {}
if banned:
brow = userdb.rowFromPK("BANNED","id",auid)
ban_details["motive"] = brow["motive"]
ban_details["ban_date"] = brow["ban_date"]
ban_details["expire_date"] = brow["expire_date"]
return await ws.send(response({
"name": name,
"id": auid,
"created": row["creation_date"],
"last_login": row["last_login"],
"last_namechange": row["last_namechange"],
"banned": banned,
"ban_details": ban_details
}))
# interface settings
case "getisettings":
if uid == None:
return await ws.send(clientError("You are not logged in."))
intname = cmd["interface"]
intname = intname.upper()
if (not isValidSimpleName(intname)) or (not isetdb.tableExists(intname)):
return await ws.send(clientError(f"The interface '{intname}' is not an existing interface."))
row = isetdb.rowFromPK(intname,"id",uid)
if row == None:
return await ws.send(clientError("This user has no settings for this interface set up."))
del row["id"]
return await ws.send(response(row))
case "setisettings":
if uid == None:
return await ws.send(clientError("You are not logged in."))
intname = cmd["interface"]
intname = intname.upper()
if (not isValidSimpleName(intname)) or (not isetdb.tableExists(intname)):
return await ws.send(clientError(f"The interface '{intname}' is not an existing interface."))
newset = cmd["settings"]
if not isetdb.hasPK(intname,"id",uid):
newset["id"]=uid
isetdb.insertRow(intname,newset)
else:
if "id" in newset:
del newset["id"]
isetdb.updateFromPK(intname,"id",uid,newset)
return await ws.send(response("success"))
# admin-specific
case "banuser":
if not isAdmin(uid):
return await ws.send(clientError("This account does not have admin privileges."))
user = cmd["user"]
if not userdb.hasPK("NAMES","id",user):
return await ws.send(clientError("Cannot find this user."))
motive = cmd["motive"]
duration = cmd["duration"] # in seconds
expire = time.time()+duration if duration>0 else 0
if userdb.hasPK("BANNED","id",user):
userdb.updateFromPK("BANNED","id",user,{"is_banned":1,"motive":motive,"ban_date": time.time(),"expire_date":expire})
else:
userdb.insertRow("BANNED",{"id":user,"is_banned":1,"motive":motive,"ban_date": time.time(),"expire_date":expire})
return await ws.send(response("success"))
case "unbanuser":
if not isAdmin(uid):
return await ws.send(clientError("This account does not have admin privileges."))
user = cmd["user"]
if not userdb.hasPK("NAMES","id",user):
return await ws.send(clientError("Cannot find this user."))
if userdb.hasPK("BANNED","id",user):
if userdb.rowFromPK("BANNED","id",user)["is_banned"]==0:
return await ws.send(clientError("This user is not banned."))
userdb.updateFromPK("BANNED","id",user,{"is_banned":0})
else:
userdb.insertRow("BANNED",{"id":user,"is_banned":0,"motive":""})
return await ws.send(response("success"))
case _:
return await ws.send(clientError(f"Command '{cmd["type"]}' does not exist."))
async def serveClient(ws):
print("serve client",id(ws))
await ws.send(json.dumps({"type":"connected"}))
while True:
try:
cmdtxt = await ws.recv()
if type(cmdtxt)==bytes: cmdtxt=cmdtxt.decode("utf8")
if type(cmdtxt)!=str: continue
cmd = json.loads(cmdtxt)
try:
await handleCommand(ws,cmd)
except Exception as e:
traceback.print_exception(e)
await ws.send(serverError(f"Cannot process command ({cmd["type"]})"))
except json.decoder.JSONDecodeError:
await ws.send(serverError("Cannot process JSON."))
except ConnectionClosedOK:
print(f"connection {id(ws)} has closed")
forgetSession(id(ws))
break
except ConnectionClosed as e:
print(f"connection {id(ws)} has closed with a non-OK exit code:")
traceback.print_exception(e)
break
except Exception as e:
traceback.print_exception(e)
await ws.send(serverError("Cannot parse command."))
async def main():
async with serve(serveClient, "", 30341) as server:
await server.serve_forever()
if __name__ == "__main__":
print("now serving")
asyncio.run(main())