async def enter_authorization( request: Request, _query_params: OAuthAuthorizeRequestQueryParams = Depends( OAuthAuthorizeRequestQueryParams), sid: Optional[str] = Cookie(None, alias=COOKIE_KEY_SID), session_state: Optional[str] = Cookie(None, alias=COOKIE_KEY_STATE), ): """Enter the authorization process. May redirect to login page or return directly.""" user = await async_validate_session(sid) if user is not None and user.active: user_with_groups = await UserWithRoles.async_load_groups( user, _query_params.client_id) resp = await run_in_threadpool( authorization.create_authorization_response, request=await oauth2_request(request), grant_user=user_with_groups, ) if isinstance(resp, RedirectResponse): # Directly return the result, optionally redirect directly add_session_state(resp, user_with_groups) if str(user_with_groups.last_modified) != session_state: update_session_state(resp, user_with_groups) return resp if isinstance(resp, ErrorJSONResponse): return resp assert not isinstance(resp, JSONResponse) return FileResponse(authorize_static_path, media_type='text/html')
def client_game_config( request: Request, profile_id: Optional[str] = Cookie(alias="PHPSESSID", default=None), ) -> Union[TarkovSuccessResponse[dict], TarkovErrorResponse]: url_root = get_request_url_root(request) if profile_id is None: return TarkovErrorResponse.profile_id_is_none() return TarkovSuccessResponse( data={ "queued": False, "banTime": 0, "hash": "BAN0", "lang": "en", "aid": profile_id, "token": "token_" + profile_id, "taxonomy": "341", "activeProfileId": "user" + profile_id + "pmc", "nickname": "user", "backend": { "Trading": url_root, "Messaging": url_root, "Main": url_root, "RagFair": url_root, }, "totalInGame": 0, })
def client_game_keepalive( profile_id: Optional[str] = Cookie(alias="PHPSESSID", default=None), ) -> Union[TarkovSuccessResponse[dict], TarkovErrorResponse]: if not profile_id: return TarkovErrorResponse(err=True, errmsg="No Session", data=None) return TarkovSuccessResponse(data={"msg": "ok"})
async def post_issue_token( request: Request, _body_params: TokenRequestBodyParams = Depends(TokenRequestBodyParams), _query_params: TokenRequestQueryParams = Depends( TokenRequestQueryParams), session_state: Optional[str] = Cookie(None, alias=COOKIE_KEY_STATE), ): """Issues a token for a token request.""" await async_throttle_sleep(request) oauth_request = await oauth2_request(request) response: Response = await run_in_threadpool( authorization.create_token_response, request=oauth_request) allow_all_get_post_cors.augment(request, response) if isinstance(response, ErrorJSONResponse): retry_after, retry_delay = await async_throttle_failure_request(request ) response.headers['X-Retry-After'] = retry_after response.headers['X-Retry-Wait'] = retry_delay if (isinstance(response, JSONResponse) and not isinstance(response, ErrorJSONResponse) and str(oauth_request.user.last_modified) != session_state): response.set_cookie( key=COOKIE_KEY_STATE, value=str(oauth_request.user.last_modified), max_age=config.oauth2.token_expiration.session, secure=os.environ.get('AUTHLIB_INSECURE_TRANSPORT') != 'true', ) return response
def retrieve_token(authorization: str = Cookie("")) -> str: # type: ignore """Retrieves a JSON Web Token from Authorization header Parameters ---------- authorization : str The Authorization header, retrieved from FastAPI request Returns ------- str The extracted JSON Web Token Raises ------ UnauthorizedException If header is missing, invalid scheme or token is empty """ if len(authorization) == 0: raise UnauthorizedException("missing_auth_header", "missing authorization header") scheme, _, param = authorization.partition(" ") if scheme.lower() != "bearer": raise UnauthorizedException("invalid_scheme", "invalid authorization scheme") elif len(param) == 0: raise UnauthorizedException( "missing_token", "token is missing from authorization header") return param
def nickname_reserved( profile_id: str = Cookie(..., alias="PHPSESSID"), account_service: AccountService = Depends( Provide[AppContainer.launcher.account_service]), ) -> TarkovSuccessResponse[str]: account = account_service.get_account(profile_id) return TarkovSuccessResponse(data=account.nickname)
async def customization_storage( profile_id: Optional[str] = Cookie(alias="PHPSESSID", default=None), ) -> Union[TarkovSuccessResponse[dict], TarkovErrorResponse]: if profile_id is None: return TarkovErrorResponse(data="", err=True, errmsg="No session cookie provided") # customization_data = ujson.load( # root_dir.joinpath('resources', 'profiles', profile_id, 'storage.json').open('r', encoding='utf8') # ) return TarkovSuccessResponse(data={})
def create_profile( profile_id: str = Cookie(..., alias="PHPSESSID"), side: str = Body(..., embed=True), nickname: str = Body(..., embed=True), profile_service: ProfileService = Depends(Provide[AppContainer.profile.service]), ) -> TarkovSuccessResponse[dict]: profile = profile_service.create_profile( profile_id=profile_id, nickname=nickname, side=side, ) return TarkovSuccessResponse(data={"uid": profile.id})
async def logout(response: Response, session: str = Cookie(None)): if session is None: raise HTTPException(404, "cookie not found") try: verification = auth.verify_session_cookie(session) auth.revoke_refresh_tokens(verification["sub"]) except auth.InvalidSessionCookieError: raise HTTPException(401) response.delete_cookie("session") return True
async def client_game_profile_list( profile_id: str = Cookie(..., alias="PHPSESSID"), ) -> Union[TarkovSuccessResponse[List[dict]], TarkovErrorResponse]: try: async with profile_manager.locks[profile_id]: profile = profile_manager.get_profile(profile_id) return TarkovSuccessResponse(data=[ profile.pmc.dict(exclude_none=True), profile.scav.dict(exclude_none=True), ]) except Profile.ProfileDoesNotExistsError as error: logger.exception(error) return TarkovSuccessResponse(data=[])
def client_notifier_channel_create( request: Request, profile_id: Optional[str] = Cookie(alias="PHPSESSID", default=None), ) -> TarkovSuccessResponse[dict]: url_root = get_request_url_root(request).rstrip("/") notifier_server_url = f"{url_root}/notifierServer/get/{profile_id}" response = { "notifier": { "server": f"{url_root}/", "channel_id": "testChannel", "url": notifier_server_url, }, "notifierServer": notifier_server_url, } return TarkovSuccessResponse(data=response)
async def with_profile_readonly( self, profile_id: str = Cookie(..., alias="PHPSESSID"), ) -> AsyncIterable[Profile]: """ Provides a Profile instance Should work the same way as with_profile method but it won't save the profile """ async with self.locks[profile_id]: profile = self.get_profile(profile_id) try: yield profile except Exception as error: profile.read() logger.exception(error) raise
def post_items_all_params( item_id: str = Path(...), body: Item = Body(...), query_a: int = Query(None), query_b=Query(None), coo: str = Cookie(None), x_head: int = Header(None), x_under: str = Header(None, convert_underscores=False), ): return { "item_id": item_id, "body": body, "query_a": query_a, "query_b": query_b, "coo": coo, "x_head": x_head, "x_under": x_under, }
async def get_userinfo( request: Request, session_state: Optional[str] = Cookie(None, alias=COOKIE_KEY_STATE), ): """Introspect self.""" oauth_request = await oauth2_request(request) origin = request.headers.get("origin") if origin is not None: origin_response = await request_origin_verifier.create_response( oauth_request, origin) if origin_response is not None: return origin_response response = await user_introspection.create_response(oauth_request) allow_all_get_cors.augment(request, response) if str(oauth_request.user.last_modified) != session_state: update_session_state(response, oauth_request.user) return response
def post_items_all_params_default( item_id: str, body_item_a: Item, body_item_b: Item, query_a: int, query_b: int, coo: str = Cookie(None), x_head: int = Header(None), x_under: str = Header(None, convert_underscores=False), ): return { "item_id": item_id, "body_item_a": body_item_a, "body_item_b": body_item_b, "query_a": query_a, "query_b": query_b, "coo": coo, "x_head": x_head, "x_under": x_under, }
async def with_profile( self, background_tasks: BackgroundTasks, profile_id: str = Cookie(..., alias="PHPSESSID"), ) -> AsyncIterable[Profile]: """ Provides a Profile instance and saves it after request using background task Should be only used as a dependency for fastapi routes """ async with self.locks[profile_id]: profile = self.get_profile(profile_id) try: background_tasks.add_task(self._save_profile_task, profile) profile.update() yield profile except Exception as error: # Else read it again from filesystem profile.read() logger.exception(error) raise
async def end_session( id_token_hint: Optional[str] = Query(None), post_logout_redirect_uri: Optional[str] = Query(None), state: Optional[str] = Query(None), sid: Optional[str] = Cookie(None, alias=COOKIE_KEY_SID), referer: Optional[str] = Header(None), ): """Ends the session.""" if sid is not None: await async_session_collection.delete_one({'_id': sid}) if id_token_hint is not None: await async_token_collection.delete_one( {'access_token': id_token_hint}) if post_logout_redirect_uri is not None: if state is not None: if '#' in post_logout_redirect_uri: post_logout_redirect_uri, post_logout_redirect_hash = post_logout_redirect_uri.split( '#', 1) post_logout_redirect_hash = '#' + post_logout_redirect_hash else: post_logout_redirect_hash = '' if '?' in post_logout_redirect_uri[:-1]: post_logout_redirect_uri += '&state=' + state else: post_logout_redirect_uri += '?state=' + state post_logout_redirect_uri += post_logout_redirect_hash elif referer is not None: post_logout_redirect_uri = referer else: post_logout_redirect_uri = '' response = RedirectResponse( status_code=302, headers={'Location': post_logout_redirect_uri}, ) response.delete_cookie(COOKIE_KEY_SID) response.delete_cookie(COOKIE_KEY_STATE) return response
async def user_delete(token: Optional[str] = Cookie(None)): generated_id = await delete(await check_token(token)) return JSONResponse(content={'id': generated_id}, status_code=202)
async def user_update(user: User, token: Optional[str] = Cookie(None)): generated_id = await update(await check_token(token), user.username, user.password, user.email) return JSONResponse(content={'id': generated_id}, status_code=202)
def query_or_cookie_extractor( q: str = Depends(query_extractor), last_query: Optional[str] = Cookie(None) ): if not q: return last_query return q
async def create(survey: Survey, token: Optional[str] = Cookie(None)): id = await create_survey(survey.title, await check_token(token)) return JSONResponse(content={"id": id}, status_code=201)
async def delete(survey_id: str, token: Optional[str] = Cookie(None)): id = await delete_survey(survey_id, await check_token(token)) return JSONResponse(content={"id": id}, status_code=202)
def test_cookie_repr(params): assert repr(Cookie(params)) == "Cookie(" + str(params) + ")"
def get_cookie(coo=Cookie(None)): return coo