Compare commits

..

No commits in common. "10586b480a4740d4ed70288d53981c12189df0f7" and "620f780113cacea4c6dbc0f3a9322c3a26c385e1" have entirely different histories.

4 changed files with 28 additions and 61 deletions

View File

@ -15,7 +15,7 @@ def _load(name,pos,file,obj):
for line in linegen(file):
split=line.split(',')
if split[pos]==name: return obj(*split)
return None
raise Exception('No such',obj.__name__,'with identifier',name)
def _load_multi(name,pos,file,obj):
out=[]
for line in linegen(file):
@ -46,56 +46,53 @@ def load_token(tokeid):
def load_tokens(user):
return _load_multi(user.username,1,access_tokens,models.AccessToken)
def save_token(token):
return _save(token,0,access_tokens,str(token))
return _save(token,0,access_tokens,token.value)
def delete_token(token):
return _delete(token,0,access_tokens,str(token))
return _delete(token,0,access_tokens,token.value)
def load_invite(tokeid):
return _load(tokeid,0,invite_tokens,models.InviteToken)
def load_invites(user):
return _load_multi(user.username,1,invite_tokens,models.InviteToken)
def save_invite(token):
return _save(token,0,invite_tokens,str(token))
return _save(token,0,invite_tokens,token.value)
def delete_invite(token):
return _delete(token,0,invite_tokens,str(token))
return _delete(token,0,invite_tokens,token.value)
def linegen(path):
i=0
file=open(path)
line=_rl(file)
line=file.readline()
while line:
i+=1
response=yield line
if response is not None: yield i
line=_rl(file)
line=file.readline()
file.close()
def update(path,lines):
def _action(file,i,line):
if i in lines: file.write(lines[i]+'\n')
else: file.write(line+'\n')
else: file.write(line)
def _post(file):
if -1 in lines: file.write(lines[-1]+'\n')
writefile(path,_action,_post)
def remove(path,lines):
def _action(file,i,line):
if i not in lines: file.write(line+'\n')
if i not in lines: file.write(line)
writefile(path,_action)
def writefile(path,action,post=None):
i=0
file=open(path)
write=open(f'{path}.tmp','w')
line=_rl(file)
line=file.readline()
while line:
i+=1
action(write,i,line)
line=_rl(file)
line=file.readline()
if post is not None: post(write)
file.close()
write.close()
rename(f'{path}.tmp',path)
def _rl(file):
return file.readline().rstrip('\n') # Maybe sometimes there won't be one.

View File

@ -6,6 +6,5 @@ globals()['backend']=import_module('.backends.'+config['backend']['type'],'auth'
backend.config=config['backend']['options']
backend.utils=utils
backend.models=models
models.utils=utils
models.backend=backend
backend.init()

View File

@ -1,15 +1,19 @@
from dataclasses import dataclass
from pydantic.v1 import validate_arguments
from datetime import datetime
from hashlib import shake_256
import uuid
def phash(pw,salt=None):
if salt is None: salt=uuid.uuid4()
return shake_256(f'{pw}{salt}'.encode('utf-8')).hexdigest(256),salt
class AbstractUser():
pass # It fixes circular dep on user.invited_by
# And on User.register (InviteToken)
@dataclass
class Token():
value: uuid.UUID
value: str
owner: AbstractUser
def __init__(self,value,owner=None):
if owner is None:
@ -20,20 +24,14 @@ class Token():
self.owner=owner
def revoke(self):
backend.delete_token(self)
@property
def serialise(self):
return ','.join(map(str,[self,self.owner]))
def __str__(self): return str(self.value)
@dataclass
class InviteToken(Token):
_uses: int=0
_max_uses: int=-1
expires: datetime=None
@validate_arguments
def __init__(self,value,owner,uses:int,maxuses:int,expiry:datetime|None):
self.uses,self.max_uses,self.expires=uses,maxuses,expiry
return super().__init__(value,owner)
_expires: datetime=None
def __init__(self,*args,**kwargs):
return super().__init__(*args,**kwargs)
@property
def uses(self): return self._uses
@uses.setter
@ -46,9 +44,6 @@ class InviteToken(Token):
def max_uses(self,val):
if -1<val<=self.uses: self.revoke()
self._max_uses=val
@property
def serialise(self):
return super().serialise+','+','.join(map(str,[self.uses,self.max_uses,self.expires]))
@dataclass
class AccessToken(Token):
@ -60,49 +55,31 @@ class User(AbstractUser):
username: str
password_hash: str
salt: str
_invited_by: AbstractUser|str # Root node will just reference itself
invited_by: AbstractUser=None # Root node will just reference itself
email: str=''
def _load_invite(self):
if self._invited_by==self.username: return self # Sanity-check to prevent infinite recursion.
return backend.load_user(self._invited_by)
@property
def invited_by(self):
if isinstance(self._invited_by,str):
self._invited_by=self._load_invite()
return self._invited_by
@property
def serialise(self):
return ','.join([self.username,self.password_hash,str(self.salt),self.invited_by.username,self.email or ''])
return ','.join([self.username,self.password_hash,str(self.salt),self.invited_by.username,self.email])
def create_inv_token(self,*args,**kwargs):
tok=InviteToken(self,*args,**kwargs)
backend.save_invite(tok)
backend.save_token(tok)
return tok
def auth(self,pw):
return utils.phash(pw,self.salt)[0]==self.password_hash
def change_password(self,old_pw:str|None,new_pw:str):
if self.auth(old_pw):
self.password_hash,self.salt=utils.phash(new_pw)
self.save()
def change_password(self,old_pw:str|None,new_pw:str): pass
def save(self):
backend.save_user(self)
def __str__(self): return self.username
@classmethod
def login(cls,username:str,password:str):
u=backend.load_user(username)
if u is None: raise Exception("User doesn't exist")
if u.auth(password):
a=AccessToken(u)
backend.save_token(a)
return a
if phash(password,u.salt)[0]==u.password_hash: return AccessToken(u)
raise Exception("Incorrect password")
@classmethod
def register(cls,username:str,password:str,invite:InviteToken,email:str=''):
def register(cls,username:str,password:str,invite:InviteToken,email:str|None):
if set([chr(n) for n in range(32)]+[','])&set(username): raise Exception('Invalid username')
u=backend.load_user(username)
if u is not None: raise Exception("User already exists")
u=User(username,*utils.phash(password),invite.owner,email)
u=User(username,*phash(password),invite.owner,email)
u.save()
invite.uses+=1
backend.save_invite(invite)
return u

View File

@ -1,6 +0,0 @@
from hashlib import shake_256
import uuid
def phash(pw,salt=None):
if salt is None: salt=uuid.uuid4()
return shake_256(f'{pw}{salt}'.encode('utf-8')).hexdigest(256),salt