async def getUser(response: Response, Authorize: AuthJWT = Depends()): Authorize.jwt_required() try: user = Authorize.get_jwt_subject() obj = get_user_object(username=user) if obj: return { Statuses.status_code: Statuses.HTTP_200_OK, Statuses.status: Statuses.success, Statuses.data: SerilizerMixin.serialize( obj, unwanted_keys=["password"], function_keys={"date_of_birth": SerilizerMixin.parseDOb}) } response.status_code = status.HTTP_400_BAD_REQUEST return { Statuses.status_code: Statuses.HTTP_BAD_REQUEST, Statuses.status: Statuses.failed, Statuses.description: f"Authentication Failed" } except Exception as exc: response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR ProjectUtils.print_log_msg(exc, ProjectUtils.EXCEPTION) return { Statuses.status_code: Statuses.HTTP_500_INTERNAL_SERVER_ERROR, Statuses.status: Statuses.exception, Statuses.description: str(exc) }
def postCategory(category: BasePostCategory, response: Response, Authorze: AuthJWT = Depends()): Authorze.jwt_required() try: if not get_category(category_name=category.categoryName): category.created_by = Authorze.get_jwt_subject() create_category(category) return { Statuses.status_code: Statuses.HTTP_200_OK, Statuses.status: Statuses.success } response.status_code = status.HTTP_400_BAD_REQUEST return { Statuses.status_code: Statuses.HTTP_BAD_REQUEST, Statuses.status: Statuses.failed, Statuses.description: "Category already exists" } except Exception as exc: response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR ProjectUtils.print_log_msg(exc, ProjectUtils.EXCEPTION) return { Statuses.status_code: Statuses.HTTP_500_INTERNAL_SERVER_ERROR, Statuses.status: Statuses.exception, Statuses.description: str(exc) }
def errors(request: Request, authorize: AuthJWT = Depends()): """Errors page""" authorize.jwt_optional() if not authorize.get_jwt_subject(): return RedirectResponse('/login') return templates.TemplateResponse("errors.html", {"request": request})
def updateCategory(category_id: int, category: BaseupdateCategory, response: Response, Authorze: AuthJWT = Depends()): Authorze.jwt_required() try: cateObj = get_category(category_id=category_id) if cateObj: category.updated_by = Authorze.get_jwt_subject() update_category(category, cateObj) return { Statuses.status_code: Statuses.HTTP_200_OK, Statuses.status: Statuses.success } response.status_code = status.HTTP_400_BAD_REQUEST return { Statuses.status_code: Statuses.HTTP_BAD_REQUEST, Statuses.status: Statuses.failed, Statuses.description: "Category Not Found" } except Exception as exc: response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR ProjectUtils.print_log_msg(exc, ProjectUtils.EXCEPTION) return { Statuses.status_code: Statuses.HTTP_500_INTERNAL_SERVER_ERROR, Statuses.status: Statuses.exception, Statuses.description: str(exc) }
def inboxq(Authorize: AuthJWT = Depends()): Authorize.jwt_required() current_id = Authorize.get_jwt_subject() all_messages = db.session.query(MessageDB).filter( MessageDB.recipient_id == current_id).all() messages = [] test_list = {} for message in all_messages: messages.append({ 'id': message.id, 'sender_id': message.sender_id, 'body': message.body, 'company_name': message.author.company_name }) if message.author.company_name in test_list: test_list[message.author.company_name].append({'id': message.id, 'sender_id': message.sender_id, \ 'body': message.body, 'company_name': message.author.company_name}) else: test_list[message.author.company_name] = [{'id': message.id, 'sender_id': message.sender_id, \ 'body': message.body, 'company_name': message.author.company_name}] print([test_list]) inbox = Inbox(inbox=test_list) print(inbox) return inbox
async def addtoCart(product_id: int, response: Response, Authorize: AuthJWT = Depends()): Authorize.jwt_required() try: user = Authorize.get_jwt_subject() obj = get_user_object(username=user) if obj: prodObj = get_product(product_id) if prodObj: session = SessionLocal() cart_id = obj.cart(session).cart_id if session.query(CartProduct).filter( CartProduct.cart_id == cart_id, CartProduct.product_id == product_id).count() == 0: cartProductObj = CartProduct(cart_id=cart_id, product_id=product_id) session.add(cartProductObj) session.commit() cartProdutsObjs = session.query(CartProduct).filter( CartProduct.cart_id == cart_id) session.close() return { Statuses.status: Statuses.success, Statuses.status_code: Statuses.HTTP_200_OK, Statuses.count: cartProdutsObjs.count(), Statuses.data: SerilizerMixin.serialize(cartProdutsObjs, many=True), Statuses.description: "Product added succesfully to cart" } response.status_code = status.HTTP_400_BAD_REQUEST return { Statuses.status_code: Statuses.HTTP_BAD_REQUEST, Statuses.status: Statuses.failed, Statuses.description: "Product already in cart" } response.status_code = status.HTTP_400_BAD_REQUEST return { Statuses.status_code: Statuses.HTTP_BAD_REQUEST, Statuses.status: Statuses.failed, Statuses.description: f"product not found --> {product_id}" } response.status_code = status.HTTP_400_BAD_REQUEST return { Statuses.status_code: Statuses.HTTP_BAD_REQUEST, Statuses.status: Statuses.failed, Statuses.description: f"Authentication Failed" } except Exception as exc: ProjectUtils.print_log_msg(exc, ProjectUtils.EXCEPTION) return { Statuses.status_code: Statuses.HTTP_500_INTERNAL_SERVER_ERROR, Statuses.status: Statuses.exception, Statuses.description: str(exc) }
def refresh(Authorize: AuthJWT = Depends()): Authorize.jwt_refresh_token_required() current_user = Authorize.get_jwt_subject() new_access_token = Authorize.create_access_token(subject=current_user) Authorize.set_access_cookies(new_access_token) return {"refresh": "successful", "access_token": new_access_token}
def update_user( user: schemas.UserCreate, db: Session = Depends(get_db), Authorize: AuthJWT = Depends(), ): auth_check(Authorize) current_user = Authorize.get_jwt_subject() return crud.update_user(db=db, user=user, current_user=current_user)
def refresh(Authorize: AuthJWT = Depends()): Authorize.jwt_refresh_token_required() current_token = Authorize.get_jwt_subject() new_access_token = Authorize.create_access_token( subject=str(current_token)) # Set the JWT cookies in the response Authorize.set_access_cookies(new_access_token) return {"msg": "The token has been refresh"}
def create_sharing_link( Authorize: AuthJWT = Depends(), db: Session = Depends(get_db), ): Authorize.jwt_required() user = Authorize.get_jwt_subject() return {"user": user}
def get_current_user(Authorize: AuthJWT = Depends()): try: Authorize.jwt_required() current_user_mail = Authorize.get_jwt_subject() user_id = db.find_user_by_email(current_user_mail)[0] return {"current_user": current_user_mail, "id": user_id} except InvalidHeaderError: raise HTTPException(409, "Unknown user")
def refresh(Authorize: AuthJWT = Depends()): Authorize.jwt_refresh_token_required() current_user = Authorize.get_jwt_subject() new_access_token = Authorize.create_access_token(subject=current_user) Authorize.set_access_cookies(new_access_token) return {"msg": "The token has been refresh"}
def get_parent_from_token(auth: AuthJWT) -> Parent: session = Session() try: email = auth.get_jwt_subject() auth.jwt_required() return session.query(Parent).filter_by(email=email).one() finally: session.close()
def get_api_keys(db: Session = Depends(get_db), Authorize: AuthJWT = Depends()): auth_check(Authorize) current_user = Authorize.get_jwt_subject() if current_user is not None: user = crud.get_user_by_name(db=db, username=current_user) else: raise HTTPException(status_code=401, detail="Not logged in.") return crud.get_keys(user, db)
def verify(response: Response, Authorize: AuthJWT = Depends()): try: Authorize.jwt_required() current_user = Authorize.get_jwt_subject() response.status_code = status.HTTP_200_OK return {'tokenVerified': True} except: response.status_code = status.HTTP_200_OK return {'tokenVerified': False}
async def user_rate_meal(meal_id: int, rating: int, Authorize: AuthJWT = Depends()): Authorize.jwt_required() current_user = Authorize.get_jwt_subject() Rating.insert(user_id=current_user.id, meal_id=meal_id, rating=rating).execute() return "ok" # TODO: Better response here.
def inboxf(sender: Sender, Authorize: AuthJWT = Depends()): Authorize.jwt_required() current_id = Authorize.get_jwt_subject() query = db.session.query(MessageDB).filter( MessageDB.sender_id == sender.sender).filter( MessageDB.recipient_id == current_id).all() return query
def me(Authorize: AuthJWT = Depends()): Authorize.jwt_required() user = Authorize.get_jwt_subject() if (user): current_user = json.loads(str(user)) return {"user": current_user} return {}
def protected(Authorize: AuthJWT = Depends()): """ We do not need to make any changes to our protected endpoints. They will all still function the exact same as they do when sending the JWT in via a headers instead of a cookies """ Authorize.jwt_required() current_user = Authorize.get_jwt_subject() return {"user": current_user}
def get_folder_list( Authorize: AuthJWT = Depends(), db: Session = Depends(get_db), ): Authorize.jwt_required() user = Authorize.get_jwt_subject() folders = crud.get_list_of_folders(db, user) return {"Folders": folders}
async def check( self, authorize: AuthJWT = Depends(), ): """Ручка проверки авторизации""" print("hi") authorize.jwt_required() current_user = authorize.get_jwt_subject() return JSONResponse(status_code=200, content={"email": current_user})
def user_details(Authorize: AuthJWT = Depends(),db: Session = Depends(service.get_db)): logger.info("user details fetching started!") Authorize.jwt_required() current_user = Authorize.get_jwt_subject() current_user = current_user.replace("\'", "\"") user_info = json.loads(current_user) user_id = user_info["id"] records = db.query(models.User).filter(models.User.user_id == user_id).first() return records
async def get_user(auth: AuthJWT = Depends()): auth.jwt_required() user_id = auth.get_jwt_subject() user = await User.get_or_none(pk=user_id) if user is None: raise HTTPException(status_code=404) return PyUserOut.from_orm(user)
async def delete_post_data(id: str, Authorize: AuthJWT = Depends()): Authorize.jwt_required() current_user = Authorize.get_jwt_subject() user = await get_user_data(current_user) deleted_post = await delete_post(id, user=user['_id']) if deleted_post: return ResponseModel(f'Post with ID:{id} removed', 'Successfully delete post') return ErrorResponseModel('An error occurred', 404, f'Post with ID:{id} does not exist')
async def get_refresh_token(db: Session = Depends(deps.get_db), Authorize: AuthJWT = Depends()) -> dict: Authorize.jwt_refresh_token_required() current_user = Authorize.get_jwt_subject() new_access_token = Authorize.create_access_token(subject=current_user) return { 'access_token': new_access_token, 'token_type': 'bearer', }
def post( post_in: PostCreate, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db), ): Authorize.jwt_required() user_id = Authorize.get_jwt_subject() dbpost = postCRUD.create(db, obj_in=post_in, owner_id=user_id) return {'url': f'localhost:8000/posts/{dbpost.id}'}
def refresh(Authorize: AuthJWT = Depends()): """ Refresh token endpoint. This will generate a new access token from the refresh token, but will mark that access token as non-fresh, as we do not actually verify a password in this endpoint. """ Authorize.jwt_refresh_token_required() current_user = Authorize.get_jwt_subject() new_access_token = Authorize.create_access_token(subject=current_user) return {"access_token": new_access_token}
def get_folder_content( folder_name: str, Authorize: AuthJWT = Depends(), db: Session = Depends(get_db), ): Authorize.jwt_required() user = Authorize.get_jwt_subject() list_of_files = crud.get_folder_content(db, user, folder_name) return {"files": list_of_files}
async def refresh_access_token(Authorize: AuthJWT = Depends()): Authorize.jwt_refresh_token_required() user_email = Authorize.get_jwt_subject() user = await User.get_or_none(email=user_email).first() if user is None: raise HTTPException(403, "JWT subject not found") return {"access_token": Authorize.create_access_token(subject=user_email)}
def get_current_user(db: Session = Depends(get_db), Authorize: AuthJWT = Depends()) -> models.User: Authorize.jwt_required() current_user_email = Authorize.get_jwt_subject() user = crud.user.get_by_email(db, email=current_user_email) if not user: raise HTTPException(status_code=404, detail="User not found") return user