from fastapi import Request, Response, HTTPException from fastapi.responses import JSONResponse, PlainTextResponse import aiosqlite from user_mgmt import * import db_setup as db async def register_endpoint(req: Request): body = await req.json() try: create_user(body["first_name"], body["last_name"], body["email"], body["password"]) except KeyError: raise HTTPException(400, "Missing args") async def login_endpoint(req: Request): """ The login endpoint Takes email and password Returns 401 or 400 in error. Returns the user's full info if correct """ body = await req.json() #print(body) try: user_data = await fetch_user_info(body["email"], "email") if (user_data is None): print("User doesn't exist") raise HTTPException(status_code=401, detail="User doesn't exist") else: pwd = user_data.get("password") if (bcrypt.checkpw(body["password"].encode(), user_data.get("password").encode())): return user_data else: print("Wrong password") raise HTTPException(status_code=401, detail="Wrong password") except KeyError: raise HTTPException(status_code=400) async def me_get_endpoint(req: Request): """ Retrieves user profile data. Trusts Nuxt's backend to allow it or not. """ args = dict(req.query_params) me = None try: # Prefer id over e-mail if "id" in args.keys(): me = fetch_user_info(args["id"], "id") elif "email" in args.keys(): me = fetch_user_info(args["email"], "email") else: raise HTTPException(400, "Provide either email or user id") #print(args) if (me is None): raise HTTPException(404, "User doesn't exist") else: return me except KeyError: raise HTTPException(400, "Please provide email")