def get_current_user(db: Session = Depends(get_db), token: str = Security(reusable_oauth2)): # try: # payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM]) # token_data = TokenPayload(**payload) # except PyJWTError: # raise HTTPException( # status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials" # ) # user = crud.user.get(db, user_id=token_data.user_id) # if not user: # raise HTTPException(status_code=404, detail="User not found") # return user # get the kid from the headers prior to verification headers = jwt.get_unverified_headers(token) kid = headers['kid'] # search for the kid in the downloaded public keys key_index = -1 for i in range(len(keys)): if kid == keys[i]['kid']: key_index = i break if key_index == -1: logger.info('Public key not found in jwks.json') return False # construct the public key public_key = jwk.construct(keys[key_index]) # get the last two sections of the token, # message and signature (encoded in base64) message, encoded_signature = str(token).rsplit('.', 1) # decode the signature decoded_signature = base64url_decode(encoded_signature.encode('utf-8')) # verify the signature if not public_key.verify(message.encode("utf8"), decoded_signature): logger.info('Signature verification failed') return False logger.info('Signature successfully verified') # since we passed the verification, we can now safely # use the unverified claims claims = jwt.get_unverified_claims(token) # additionally we can verify the token expiration if time.time() > claims['exp']: logger.info('Token is expired') raise HTTPException(status_code=404, detail="Sessions has expired.") # and the Audience (use claims['client_id'] if verifying an access token) if claims['client_id'] != app_client_id: logger.info('Token was not issued for this audience') raise HTTPException(status_code=404, detail="Unauthorized access. Access denied") # now we can use the claims # print(claims) user = crud.user.get(db, cognito_user_id=claims["sub"]) if not user: raise HTTPException(status_code=404, detail="User not found") return user
async def faceted_search( *, db: Session = Depends(get_db), start: int = 0, limit: int = 25, file_id: int, category: str, current_user: DBUser = Depends(get_current_active_user)): confirm_case_id_with_biz_id = get_by_file_ids(db, ids=[file_id], user_details=current_user) if not confirm_case_id_with_biz_id: logger.info( f"Invalid file_id of value {file_id} found for business_id {current_user.business_id}" ) raise HTTPException( status_code=400, detail="Invalid details passed.", ) cat = None if category: if category.__eq__("Body Part/Organ"): cat = "t023" else: for k, v in all_categories.items(): if category.__eq__(v): cat = k break else: logger.info( f"No category found for variable {category} and business_id {current_user.business_id}" ) raise HTTPException( status_code=400, detail="Invalid details passed.", ) params = { "fq": f"business_id%3A{current_user.business_id}%20AND%20file_id%3A{file_id}", "q": f"tui%3A{cat}", "rows": min(limit, 500), "start": start } local_session = await get_session() resp = await local_session.get(url, params=params) res = json.loads(await resp.text()) result = res["response"] return result
def confirm_case_id_with_biz_id_helper_func(db, case_id, current_user): confirm_case_id_with_biz_id = get_by_case_id(db, id=case_id, user_details=current_user) if not confirm_case_id_with_biz_id: logger.info( f"Invalid case_id of value {case_id} found for business_id {current_user.business_id}" ) raise HTTPException( status_code=400, detail="Invalid details passed.", )
async def preset_cat_filters( *, db: Session = Depends(get_db), case_id: int, category: str, # txt: Optional[str], # start: int = 0, # limit: int = 25, current_user: DBUser = Depends(get_current_active_user), response: Response): confirm_case_id_with_biz_id_helper_func(db, case_id, current_user) f_pivot = "category,text,confirmed_visit_date,id" params = { "q": "*:*", "fq": f"category:\"{category}\" AND business_id:{current_user.business_id} AND case_id:{case_id}", "facet.pivot": f_pivot, "facet": "true", "rows": "0", "facet.pivot.mincount": "1", "facet.limit": "-1" } local_session = await get_session() resp = await local_session.get(url, params=urllib.parse.urlencode(params)) res = json.loads(await resp.text()) if "error" in res: logger.info( f"Exception occurred for business_id: {current_user.business_id} while fetching file_id: {case_id} " f"with below exception. \n {res['error']['trace']}") raise HTTPException( status_code=res["error"]["code"], detail="Invalid details passed.", ) d: PresetCatFiltersSearchResults = PresetCatFiltersSearchResults( field=None, value=None, count=None, pivot=None) if len(res["facet_counts"]["facet_pivot"][f_pivot]) > 0: d = res["facet_counts"]["facet_pivot"][f_pivot][0] # response.headers["cache-control"] = f"private, max-age={int(86400)}" return d
def delete_by_file_id(db_session, *, file_id: list, user_details=None): # this is a cascade delete. It will delete from following tables: # select * from file; # select * from file_state; # select * from sf_ctakes_mentions; # select * from mentions_rel_text; try: deleted_objects = File.__table__.delete().where(File.id.in_(file_id)) db_session.execute(deleted_objects) db_session.commit() except Exception as e: logger.info( f"Exception for business_id: {user_details.business_id} and user: {user_details.id} " f"{e}") traceback.print_exc(file=sys.stdout) raise HTTPException( status_code=400, detail="Exception occurred while deleting file(s).", ) return True
async def get_pdf_cords( *, db: Session = Depends(get_db), case_id: int, m_id: int, current_user: DBUser = Depends(get_current_active_user), response: Response): confirm_case_id_with_biz_id_helper_func(db, case_id, current_user) params = { "q": "*:*", "fq": f"id:{m_id} AND business_id:{current_user.business_id} AND case_id:{case_id}", "fl": "full_text_bbox, page_number" } local_session = await get_session() resp = await local_session.get(url, params=urllib.parse.urlencode(params)) res = json.loads(await resp.text()) if "error" in res: logger.info( f"Exception occurred for business_id: {current_user.business_id} while fetching file_id: {case_id} " f"with below exception. \n {res['error']['trace']}") raise HTTPException( status_code=res["error"]["code"], detail="Invalid details passed.", ) obj_to_return = {} if len(res["response"]["docs"]) > 0: obj_to_return = res["response"]["docs"][0] else: obj_to_return["full_text_bbox"] = "" obj_to_return["page_number"] = 0 # Cache-Control:public, max-age=31536000 # response.headers["cache-control"] = f"private, max-age={int(86400)}" return obj_to_return
def delete_file(*, db: Session = Depends(get_db), file_id: list = Body(None), current_user: DBUser = Depends(get_current_active_user)): f_id = [(int(i["id"]), ) for i in file_id if "id" in i] # confirm_file_for_user = crud.file.get_by_file_ids(db, ids=f_id, user_details=current_user) try: result = crud.file.get_filestate_files(db, ids=f_id, user_details=current_user) # extract unique and all s3 files to delete s3_files_delete = () for r in result: s3_files_delete = s3_files_delete + r final_s3_files_delete = list(set(s3_files_delete)) # delete from database first crud.file.delete_by_file_id(db, file_id=f_id, user_details=current_user) # delete from s3 next crud.file.delete_s3_file(final_s3_files_delete) except Exception as e: logger.info( f'Exception occurred while deleting file with id: {file_id} for ' f"business_id: {current_user.business_id}. Exception is: ") logger.info(e) raise HTTPException( status_code=400, detail="There was a problem while deleting file.", ) return FileDelete(response="success")
async def faceted_search( *, db: Session = Depends(get_db), case_id: int, current_user: DBUser = Depends(get_current_active_user), response: Response): # confirm_case_id_with_biz_id = get_by_case_id(db, id=case_id, user_details=current_user) # # if not confirm_case_id_with_biz_id: # logger.info(f"Invalid case_id of value {case_id} found for business_id {current_user.business_id}") # raise HTTPException( # status_code=400, # detail="Invalid details passed.", # ) confirm_case_id_with_biz_id_helper_func(db, case_id, current_user) params = { "q": "%2A:%2A", "fq": f"business_id:{current_user.business_id}%20AND%20case_id:{case_id}", # %20AND%20" # f"concept_attributes:%28t037%20OR%20t047%20OR%20t184%20OR%20t190%20OR%20t017%29", "facet": "true", # "facet.field": "tui", "facet.field": "category", "rows": "0", "facet.mincount": "1" } local_session = await get_session() resp = await local_session.get(url, params=params) res = json.loads(await resp.text()) if "error" in res: logger.info( f"Exception occurred for business_id: {current_user.business_id} while fetching file_id: {case_id} " f"with below exception. \n {res['error']['trace']}") raise HTTPException( status_code=res["error"]["code"], detail="Invalid details passed.", ) result = res["facet_counts"]["facet_fields"]["category"] return_list = [] for i in range(0, len(result), 2): # if we were faceting by TUI or CUI then we would need line # obj = {str(all_categories[result[i]]): result[i + 1]} # but we are faceting by Category for easy viewing for end user if str(result[i]) in [ 'Sign Or Symptom', 'Medication', 'Body Site', 'Medical Procedure', 'Disease Disorder' ]: obj = {str(result[i]): result[i + 1]} return_list.append(obj) # response.headers["cache-control"] = f"private, max-age={int(86400)}" return return_list
async def search_text_for_visit_date( *, db: Session = Depends(get_db), file_id: int, cvd: Optional[str], txt: Optional[str], start: int = 0, limit: int = 25, current_user: DBUser = Depends(get_current_active_user)): if not cvd and not txt: logger.info( f"Visit Date and Text passed was Blank for file_id of value {file_id} and" f" business_id {current_user.business_id}") raise HTTPException( status_code=400, detail="Invalid details passed.", ) main_str = f"business_id:{current_user.business_id} AND file_id:{file_id} " if cvd: cvd = cvd.split(",") str_h = " AND (" cvd_str = f"confirmed_visit_date:" for i, c in enumerate(cvd): if i > 0: str_h = str_h + " OR " str_h = str_h + cvd_str + c str_h += ")" main_str += str_h if txt: main_str += f" AND (text:{txt} OR full_text:{txt})" confirm_case_id_with_biz_id = get_by_file_ids(db, ids=[file_id], user_details=current_user) if not confirm_case_id_with_biz_id: logger.info( f"Invalid file_id of value {file_id} found for business_id {current_user.business_id}" ) raise HTTPException( status_code=400, detail="Invalid details passed.", ) # in case someone ever tries to temper with frontend payload and try to get other business' details: if main_str.count("business_id") > 1: logger.warn( f"Looks like someone tried to temper with frontend payload and added business_id twice: " f"\nmain_str: {main_str}") raise HTTPException( status_code=400, detail="Invalid details passed.", ) params = {"fq": main_str, "q": "%2A%3A%2A", "rows": limit, "start": start} local_session = await get_session() resp = await local_session.get(url, params=params) res = json.loads(await resp.text()) distinct_full_text = [] result = res["response"] for i, r in enumerate(result["docs"]): if r["full_text"] + r["confirmed_visit_date"] not in distinct_full_text: distinct_full_text.append(r["full_text"] + r["confirmed_visit_date"]) else: result["docs"].pop(i) # numfound etc etc return result