server code with basic account stuff
This commit is contained in:
+118
@@ -0,0 +1,118 @@
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
class Database():
|
||||
def __init__(self,name):
|
||||
print(f"init db {name}")
|
||||
self.name = name
|
||||
self.con = sqlite3.connect(f"{name}.db")
|
||||
self.cur = self.con.cursor()
|
||||
|
||||
def execute(self,cmd: str,*args):
|
||||
print("execute",[cmd,*args])
|
||||
return self.cur.execute(cmd,*args)
|
||||
|
||||
def executemany(self,cmd: str,*args):
|
||||
print("executemany",[cmd,*args])
|
||||
return self.cur.executemany(cmd,*args)
|
||||
|
||||
def select(self,cmd: str,*args) -> list[tuple]:
|
||||
return self.execute(cmd,*args).fetchall()
|
||||
|
||||
def sameType(self,typeA: str,typeB: str) -> bool:
|
||||
return typeA.lower() == typeB.lower()
|
||||
|
||||
|
||||
# tables
|
||||
def tableExists(self,table: str) -> bool:
|
||||
res = self.select("SELECT name FROM sqlite_master WHERE type='table' AND name=?",(table,))
|
||||
return type(res)!=type(None) and len(res)>0
|
||||
|
||||
def createTable(self,table: str,cols: dict[str,str]) -> None:
|
||||
if self.tableExists(table): return self.checkColumns(table,cols)
|
||||
# i know i shouldn't be inserting these directly but using placeholders returns a syntax error for some reason
|
||||
self.execute(f"CREATE TABLE {table}({", ".join([f"{n} {cols[n]}" for n in cols])})")
|
||||
|
||||
def dropTable(self,table: str) -> None:
|
||||
self.execute(f"DROP TABLE {table}")
|
||||
|
||||
|
||||
# columns
|
||||
def getColumns(self,table: str) -> tuple[str]:
|
||||
if not self.tableExists(table): return ()
|
||||
res = self.select(f"PRAGMA table_info('{table}')")
|
||||
return dict([e[1:3] for e in res])
|
||||
|
||||
def hasColumn(self,table: str,colname: str) -> bool:
|
||||
return colname in self.getColumns(table)
|
||||
|
||||
def insertColumn(self,table: str,colname: str,coltype: str) -> None:
|
||||
self.execute(f"ALTER TABLE {table} ADD COLUMN {colname} {coltype}")
|
||||
|
||||
def checkColumns(self,table: str,cols: dict[str,str]) -> None:
|
||||
tcols = self.getColumns(table)
|
||||
for colname in cols:
|
||||
if not colname in tcols:
|
||||
self.insertColumn(table,colname,cols[colname])
|
||||
continue
|
||||
if not self.sameType(cols[colname],tcols[colname]):
|
||||
raise Exception(f"Invalid table '{table}' in database '{self.name}': column '{colname}' has type '{tcols[colname]}' instead of '{cols[colname]}'")
|
||||
|
||||
|
||||
# rows
|
||||
def insertRows(self,table: str,values: list[list|tuple|dict]) -> None:
|
||||
if len(values)==0: return
|
||||
amount=len(values[0])
|
||||
if type(values[0])==dict:
|
||||
cols = self.getColumns(table)
|
||||
for e in values:
|
||||
for c in cols:
|
||||
if not c in e:
|
||||
e[c] = None
|
||||
self.executemany(f"INSERT INTO {table} VALUES({", ".join([f":{e}" for e in cols])})",values)
|
||||
else:
|
||||
self.executemany(f"INSERT INTO {table} VALUES({", ".join(["?"]*amount)})",values)
|
||||
self.con.commit()
|
||||
|
||||
def insertRow(self,table: str,values: list|tuple|dict) -> None:
|
||||
self.insertRows(table,[values])
|
||||
|
||||
def rowAmount(self,table: str) -> int:
|
||||
return self.select(f"SELECT COUNT(*) FROM {table}")[0][0]
|
||||
|
||||
# find
|
||||
def findRowList(self,table: str,pattern: str,*args) -> list | None:
|
||||
res = self.select(f"SELECT * FROM {table} WHERE {pattern}",*args)
|
||||
if len(res)==0: return None
|
||||
return res[0]
|
||||
|
||||
def findRow(self,table: str,pattern: str,*args) -> dict | None:
|
||||
res = self.findRowList(table,pattern,*args)
|
||||
if res==None: return None
|
||||
cols = list(self.getColumns(table))
|
||||
return dict([[cols[i],res[i]] for i in range(len(cols))])
|
||||
|
||||
# PK = primary key
|
||||
def rowListFromPK(self,table: str,pkname: str,pk) -> tuple | None:
|
||||
res = self.select(f"SELECT * FROM {table} WHERE {pkname} = ?",(pk,))
|
||||
if len(res)==0: return None
|
||||
return res[0]
|
||||
|
||||
def rowFromPK(self,table: str,pkname: str,pk) -> dict | None:
|
||||
res = self.rowListFromPK(table,pkname,pk)
|
||||
if res==None: return None
|
||||
cols = list(self.getColumns(table))
|
||||
return dict([[cols[i],res[i]] for i in range(len(cols))])
|
||||
|
||||
def hasPK(self,table: str,pkname: str,pk) -> bool:
|
||||
return type(self.rowListFromPK(table,pkname,pk))!=type(None)
|
||||
|
||||
def removePK(self,table: str,pkname: str,pk) -> None:
|
||||
self.execute(f"DELETE FROM {table} WHERE {pkname} = ?",(pk,))
|
||||
self.con.commit()
|
||||
|
||||
def updateFromPK(self,table: str,pkname: str,pk,row:dict):
|
||||
keys = list(row)
|
||||
vals = [row[i] for i in keys]
|
||||
self.execute(f"UPDATE {table} SET {", ".join([f"{e} = ?" for e in keys])} WHERE {pkname} = ?",(*vals,pk))
|
||||
self.con.commit()
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import asyncio
|
||||
import json, random, re, math, time, traceback
|
||||
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"})
|
||||
userdb.createTable("PASSWORDS",{"id":"int","sum":"string"})
|
||||
|
||||
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:
|
||||
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 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 = {}
|
||||
|
||||
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"))
|
||||
if id(ws) in sessionUsers:
|
||||
uid = sessionUsers[id(ws)]
|
||||
match cmd["type"]:
|
||||
case "ping":
|
||||
return await ws.send(response("Pong!"))
|
||||
case "createuser":
|
||||
uid = makeUserID()
|
||||
name = cmd["name"]
|
||||
name = name.lower()
|
||||
if not isValidUsername(name):
|
||||
return await ws.send(clientError("Username is not valid."))
|
||||
if len(userdb.select("SELECT * FROM NAMES WHERE name = ?",(name,)))>0:
|
||||
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."))
|
||||
create = time.time()
|
||||
userdb.insertRow("NAMES",{"id":uid,"name":cmd["name"],"creation_date":create,"last_login":create})
|
||||
userdb.insertRow("PASSWORDS",{"id":uid,"sum":psum})
|
||||
return await ws.send(response({"uid":uid}))
|
||||
|
||||
case "login":
|
||||
if id(ws) in sessionUsers:
|
||||
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."))
|
||||
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 not id(ws) in sessionUsers:
|
||||
return await ws.send(clientError("You are already logged out."))
|
||||
del sessionUsers[id(ws)]
|
||||
return await ws.send(response("success"))
|
||||
|
||||
case "status":
|
||||
if not id(ws) in sessionUsers:
|
||||
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}))
|
||||
|
||||
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 Exception as e:
|
||||
traceback.print_exception(e)
|
||||
await ws.send(serverError("Cannot process JSON."))
|
||||
|
||||
async def main():
|
||||
async with serve(serveClient, "", 30341) as server:
|
||||
await server.serve_forever()
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("now serving")
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user