Does anyone know how to make it work
I’m trying to add loggin in the the CodeComm API.
It isn’t working…
help
from fastapi import FastAPI
import json
import re
from passlib.hash import pbkdf2_sha256
import ast
app = FastAPI()
accregex = r"^[a-z0-9_\\-]{0,20}$"
@app.get('/')
def main():
return {'codecomm': 'v1'}
@app.get('/accounts/join')
def join(username: str, password: str):
if re.fullmatch(accregex, username):
#hash password
password = pbkdf2_sha256.hash(password)
accjson = {username: {"name": username, "password": password, "admin": False}}
#write user data to users.json
with open('users.json') as f:
data = json.load(f)
data.update(accjson)
with open('users.json', 'w') as f:
json.dump(data, f)
return {'ok': 'made account'}
else:
return {'error': 'invalid username'}
@app.get('/accounts/login')
def login(username: str, password: str):
global userdata, userpwdhash
userdata = json.loads('users.json')
userdata = ast.literal_eval(userdata)
if username in userdata:
userdata = json.loads(userdata)
userpwdhash = userdata.get('password')
else:
return {'error': 'user not found'}
pbkdf2_sha256.verify(password, userpwdhash)
return {'ok': 'logged in'}
Hey!!! It works
from fastapi import FastAPI
import json
import re
from passlib.hash import pbkdf2_sha256
import ast
app = FastAPI()
accregex = r"^[a-z0-9_\\-]{0,20}$"
@app.get('/')
def main():
return {'codecomm': 'v1'}
@app.get('/accounts/join')
def join(username: str, password: str):
if re.fullmatch(accregex, username):
#hash password
password = pbkdf2_sha256.hash(password)
accjson = {username: {"name": username, "password": password, "admin": False}}
#write user data to users.json
with open('users.json') as f:
data = json.load(f)
data.update(accjson)
with open('users.json', 'w') as f:
json.dump(data, f)
return {'ok': 'made account'}
else:
return {'error': 'invalid username'}
@app.get('/accounts/login')
def login(username: str, password: str):
global userdata, userpwdhash
with open("users.json","r") as file: #r is reading mode
userdata = json.loads(file.read()) #outputs str
if username in userdata:
userpwdhash = userdata.get(username).get('password')
else:
return {'error': 'user not found'}
pbkdf2_sha256.verify(password, userpwdhash)
return {'ok': 'logged in'}