def get_user_by_id(userid: int, isAdmin=Depends(is_logged_user_admin)): stackpath = "get_user_by_id" print('\x1b[0;30;44m' + "get------>" + '\x1b[0m', stackpath) db_user = user_db.get_user_by_id(userid) if not db_user: return {"error": "user not found"} user = User.to_User_model(db_user) print('\x1b[0;30;44m' + "<------get" + '\x1b[0m', stackpath) return user
def register_user(user: User): stackpath = "register_user" print('\x1b[0;30;44m' + "post------>" + '\x1b[0m', stackpath) exist_user = get_user_by_username(user.username) if (exist_user): raise HTTPException(status_code=400, detail='Username already taken') new_user = create_user(user) usermodel = User.to_User_model(new_user) token = jwt.encode(usermodel.dict(), JWT_SECRET) print('\x1b[0;30;44m' + "<------post" + '\x1b[0m', stackpath) return {'access_token': token, 'user_type': usermodel.user_type}
def login_generate_token(form_data: OAuth2PasswordRequestForm = Depends()): stackpath = "login_generate_token" print('\x1b[0;30;44m' + "post------>" + '\x1b[0m', stackpath) user = authenticate_user(form_data.username, form_data.password) if not user: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Invalid username or password') usermodel = User.to_User_model(user) token = jwt.encode(usermodel.dict(), JWT_SECRET) print('\x1b[0;30;44m' + "<------post" + '\x1b[0m', stackpath) return {'access_token': token, 'user_type': usermodel.user_type}
def get_current_user(token: str = Depends(oauth2scheme)): stackpath = "get_current_user" print('\x1b[0;33;44m' + "def----->" + '\x1b[0m', stackpath) try: payload = jwt.decode(token, JWT_SECRET, algorithms=['HS256']) user = user_db.get_user_by_id(payload["id"]) user = User.to_User_model(user) except: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Invalid username or password') print('\x1b[0;33;44m' + "<-----def" + '\x1b[0m', stackpath) return user