auth/backends/file.py

74 lines
2.0 KiB
Python
Raw Normal View History

2023-12-28 23:51:38 +11:00
from os import path,rename
2023-12-25 00:27:23 +11:00
def init():
if not path.exists(config['path']): raise Exception(f"Backend directory doesn't exist: {config['path']}")
for n in ['users','invite_tokens','access_tokens']:
p=path.join(config['path'],n+'.csv')
globals()[n]=p
if not path.exists(p): open(p,'w').write('\n')
if path.isdir(p): raise Exception(f"Backend file is a directory: {p}")
try: open(p).close()
except PermissionError: raise Exception(f"Backend file can't be read: {p}")
2023-12-28 23:51:38 +11:00
try: open(p,'a').close()
2023-12-25 00:27:23 +11:00
except PermissionError: raise Exception(f"Backend file can't be written: {p}")
def load_user(username):
for line in linegen(users):
split=line.split(',')
if split[0]==username: return models.User(*split)
def save_user(user):
gen=linegen(users)
for line in gen:
split=line.split(',')
if split[0]==user.username: update(users,{gen.send(True):user.csv}); break
else: update(users,{-1:user.csv})
2023-12-28 23:51:38 +11:00
def delete_user(user):
gen=linegen(users)
for line in gen:
split=line.split(',')
if split[0]==user.username: remove(users,[gen.send(True)]); break
2023-12-25 00:27:23 +11:00
def load_tokens(user): pass
def save_token(token): pass
def delete_token(token): pass
def load_invites(user): pass
def save_invite(token): pass
def delete_invite(token): pass
def linegen(path):
i=0
file=open(path)
line=file.readline()
while line:
i+=1
response=yield line
if response is not None: yield i
line=file.readline()
file.close()
def update(path,lines):
2023-12-28 23:51:38 +11:00
def _action(file,i,line):
if i in lines: file.write(lines[i]+'\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)
writefile(path,_action)
def writefile(path,action,post=None):
2023-12-25 00:27:23 +11:00
i=0
file=open(path)
write=open(f'{path}.tmp','w')
line=file.readline()
while line:
i+=1
2023-12-28 23:51:38 +11:00
action(write,i,line)
2023-12-25 00:27:23 +11:00
line=file.readline()
2023-12-28 23:51:38 +11:00
if post is not None: post(write)
2023-12-25 00:27:23 +11:00
file.close()
2023-12-28 23:51:38 +11:00
write.close()
rename(f'{path}.tmp',path)