async def get_current_user_detail(jwt: str = Cookie(None)) -> Any: if not jwt or len(jwt) < 50: return None try: user_dict = await authfunc.retrieve_detail(jwt) except: raise HTTPException(status_code=500, detail='上游服务器无响应') user_dict = dict(user_dict) if not user_dict: return None return UserDetail(**user_dict)
async def delete_order_item_by_id( order_id: PositiveInt, order_item_id: PositiveInt, orders_repo: OrdersRepository = Depends(get_repository(OrdersRepository)), ): order_item = await orders_repo.delete_order_item_by_id( order_id=order_id, order_item_id=order_item_id) if order_item is None: raise HTTPException(status.HTTP_404_NOT_FOUND, "OrderItem not found") return order_item
async def get_current_user(jwt: str = Cookie(None)) -> Optional[UserPayload]: if not jwt or len(jwt) < 50: return None try: user_dict = await authfunc.retrieve_payload(jwt) except: raise HTTPException(status_code=500, detail='上游服务器无响应') user_dict['exp'] = float(user_dict['exp']) if not user_dict: return None return UserPayload(user_dict)
def get_errors_history( ukrdc3: Session, statsdb: Session, facility_code: str, user: UKRDCUser, since: Optional[datetime.date] = None, until: Optional[datetime.date] = None, ) -> list[HistoryPoint]: """Get a day-by-day error count for a particular facility/unit Args: ukrdc3 (Session): SQLAlchemy session statsdb (Session): SQLAlchemy session errorsdb (Session): SQLAlchemy session facility_code (str): Facility/unit code user (UKRDCUser): Logged-in user since (Optional[datetime.date]): Filter start date. Defaults to None. until (Optional[datetime.date]): Filter end date. Defaults to None. Returns: list[HistoryPoint]: Time-series error data """ code = ( ukrdc3.query(Code) .filter(Code.coding_standard == "RR1+", Code.code == facility_code) .first() ) if not code: raise HTTPException(404, detail="Facility not found") # Assert permissions units = Permissions.unit_codes(user.permissions) if (Permissions.UNIT_WILDCARD not in units) and (code.code not in units): raise PermissionsError() # Get cached statistics history = statsdb.query(ErrorHistory).filter(ErrorHistory.facility == facility_code) # Default to last year history = history.filter( ErrorHistory.date >= (since or (datetime.datetime.utcnow() - datetime.timedelta(days=365))) ) # Optionally filter by end date if until: history = history.filter(ErrorHistory.date <= until) points = [ HistoryPoint(time=point.date, count=point.count) for point in history.all() ] return points
def kill_all_nodes(self): """ Shut down any active dtale instances for this source. """ try: for node in self.nodes.values(): if node.dtale_url: node.shut_down() except Exception as e: self.error = str(e) raise HTTPException(status_code=500, detail=str(e))
async def create_brand( request: Request, db: Session = Depends(get_db), *, item_in: BrandCreate, ) -> Any: if not request.state.is_admin: raise HTTPException(status_code=401, detail="You don't have enough privileges") brand = await crud.brand.create(db, obj_in=item_in) return brand
async def _delete(pod_id: uuid.UUID): """Close Pod Context """ with pod_store._session(): try: pod_store._delete(pod_id=pod_id) return {'status_code': status.HTTP_200_OK} except KeyError: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f'Pod ID {pod_id} not found! Please create a new Pod')
async def get_cleaning_by_id( id: int, cleanings_repo: CleaningsRepository = Depends( get_repository(CleaningsRepository)), ) -> CleaningPublic: cleaning = await cleanings_repo.get_cleaning_by_id(id=id) if not cleaning: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="No cleaning found with that id.") return cleaning
async def __call__( self, request: Request) -> Optional[HTTPAuthorizationCredentials]: authorization: str = request.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) if not (authorization and scheme and credentials): if self.auto_error: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated") else: return None if scheme.lower() != "bearer": if self.auto_error: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Invalid authentication credentials", ) else: return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
async def change_username( *, id: int, username: str = Body("", embed=True), user: User = Depends(get_authenticated_user), ): service = AuthService(user) if user.id == id or user.is_admin: return await service.change_username(id, username) else: raise HTTPException(403)
async def delete_cleaning_by_id( id: int = Path(..., ge=1, title="The ID of the cleaning to delete"), cleanings_repo: CleaningsRepository = Depends( get_repository(CleaningsRepository)), ) -> int: delete_id = await cleanings_repo.delete_cleaning_by_id(id=id) if not delete_id: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="No cleaning found with that id") return delete_id
async def get_systems_distance_calculator( first_system: str, second_system: str, systems_service: SystemsService = Depends(), ) -> SystemsDistance: """Get distance between two specified systems.""" try: return await systems_service.get_systems_distance_calculator( first_system, second_system) except SystemNotFoundException as e: raise HTTPException(status_code=400, detail=e.error_code)
async def create_telegram_user( user: TelegramUser, api_key: APIKey = Depends(get_api_key), ): try: return crud_create_telegram_user(odoo, user) except OdooException as e: raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=e.message, )
async def __call__( self, request: Request) -> Optional[HTTPAuthorizationCredentials]: authorization: str = request.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) if credentials != self.token: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Invalid authentication credentials", ) else: await super().__call__(request)
async def create_attachment( app_release: AppRelease, api_key: APIKey = Depends(get_api_key), ): try: return crud_create_app_release(odoo, app_release) except OdooException as e: raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=e.message, )
def read_reference_by_uid( uid: str, current_user: User = Security(get_current_user)): reference_dict = services.references.retrieve_one(current_user, uid) if reference_dict is None: raise HTTPException( status_code=404, detail="Not found", ) return reference_dict
async def read_file_block(file_path: str): try: filename = get_filename(file_path) logger.info('%s: readblock from server %d', file_path, settings.server_id) file_path = os.path.join(settings.data_dir, filename) # buffer = await read_file_block_from_fs(file_path) # stream = io.BytesIO(buffer) return FileResponse(file_path, media_type='application/octet-stream') except Exception as e: logger.exception(e) raise HTTPException(400, str(e))
async def get_acquires_available_merchant_numbers(acquirer: str): response = {"statusCode": 200, "data": [], "messages": ""} try: response["data"], response["mapKeys"] = AcquirerModel( 'ALL').load_merchants(acquirer) return response except Exception as errors: print(str(errors)) response["messages"] = str(errors) response["statusCode"] = status.HTTP_500_INTERNAL_SERVER_ERROR raise HTTPException(status_code=500, detail=response)
async def register_user(input_data: RegisterInput): if await User.objects.get_or_none(username=input_data.username, email=input_data.email): raise HTTPException(HTTP_409_CONFLICT, "User exists") new_user = await User( username=input_data.username, hashed_password=pwd_context.hash(input_data.password), email=input_data.email, ).save() return new_user
def get_prices(page_id: int, after: datetime = None, sess: Session = Depends(create_session)): if page_id is None: raise HTTPException(400, "page id is not given") if not after: after = datetime.now() - timedelta(days=30) prices = (sess.query(PriceORM).filter(PriceORM.page_id == page_id).filter( PriceORM.created_time >= after).order_by( PriceORM.created_time.desc()).all()) return [Price.from_orm(p) for p in prices]
async def register(username: str, password: str, email: str) -> str: try: id = uuid4() hashed_password = HASHER.hash(password) connection: Connection = await asyncpg.connect(dsn=DBURI) statement: PreparedStatement = await connection.prepare(INSERTQ) await statement.fetchval(id, username, hashed_password, email) await connection.close() return str(id) except Exception: raise HTTPException(status_code=500, detail="internal server error")
async def getIRToken(): clientId = str(os.environ.get("AZ_IMMERSIVE_READER_CLIENT_ID")) clientSecret = str(os.environ.get("AZ_IMMERSIVE_READER_CLIENT_SECRET")) resource = "https://cognitiveservices.azure.com/" grantType = "client_credentials" # AAD auth endpoint tenantId = str(os.environ.get("AZ_IMMERSIVE_READER_TENANT_ID")) oauthTokenUrl = f"https://login.windows.net/{tenantId}/oauth2/token" subdomain = str(os.environ.get("AZ_IMMERSIVE_READER_SUBDOMAIN")) try: headers = {"content-type": "application/x-www-form-urlencoded"} data = { "client_id": clientId, "client_secret": clientSecret, "resource": resource, "grant_type": grantType, } resp = requests.post( oauthTokenUrl, data=data, headers=headers, ) jsonResp = resp.json() if "access_token" not in jsonResp: print(jsonResp) raise HTTPException( 910, "AAD Authentication error. Check your IR access credentials") token = jsonResp["access_token"] return ImmersiveReaderTokenResponse(token=token, subdomain=subdomain) except Exception as e: message = f"Unable to acquire Azure AD token for Immersive Reader: {str(e)}" log.error(message) raise HTTPException(920, message)
async def introspect_token(self, async_client: AsyncClient, token: str) -> OIDCUserModel: """ Introspect the access token to retrieve the user info. Args: token: the access_token Returns: OIDCUserModel from openid server """ await self.check_openid_config(async_client) assert self.openid_config response = await async_client.post( self.openid_config.introspect_endpoint, params={"token": token}, auth=BasicAuth(self.resource_server_id, self.resource_server_secret), headers={"Content-Type": "application/x-www-form-urlencoded"}, ) try: data = dict(response.json()) except JSONDecodeError: logger.warning("Unable to parse introspect response", detail=response.text) raise HTTPException(status_code=HTTPStatus.UNAUTHORIZED, detail=response.text) logger.debug("Response from openid introspect", response=data) if response.status_code not in range(200, 300): logger.warning( "Introspect cannot find an active token, user unauthorized", detail=response.text) raise HTTPException(status_code=HTTPStatus.UNAUTHORIZED, detail=response.text) return OIDCUserModel(data)
async def authenticate_user( email: Text, password: Text, scopes: Optional[List[str]] = None) -> Optional[User]: """ Authenticates user with email and password and return. Parameters ---------- email : str user email password : str user password scopes : list of str, optional user scopes, default [] Returns ------- UserModel user if valid """ if not scopes: scopes = [] authenticate_value = 'Bearer' user = await get_user({'email': email}) if user and verify_password(password, user.hashed_password): user_scopes = user.scopes.split() for scope in scopes: if scope not in user_scopes: authenticate_value = f'Bearer scope="{" ".join(scopes)}"' raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail='Not enough permissions', headers={'WWW-Authenticate': authenticate_value}, ) return user raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail='Incorrect username or password', headers={'WWW-Authenticate': authenticate_value}, )
def get_current_user(token: str = Depends(oauth2_scheme)) -> UserModel: encoded_data: Dict = crypt.decode_jwt(token=token) username: str = encoded_data.get("sub") user_db = UserDBManagement(DBConnection(Database())) user = user_db.retrieve_user_by(email=username) if not user.is_active: raise HTTPException(detail="User isn`t active", status_code=status.HTTP_403_FORBIDDEN) expires_date: datetime.timestamp = encoded_data.get("exp") if datetime.fromtimestamp(expires_date) <= datetime.utcnow(): raise HTTPException(detail="Token has expire", headers={"WWW-Authenticate": "Bearer"}, status_code=status.HTTP_410_GONE) return user
def delete_resource( *, session: Session = Depends(get_session), resource_id: int, current_user: User = Depends(deps.get_current_user), ): resource = get_resource(session, resource_id) if not current_user.is_superuser and resource.user.id != current_user.id: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) session.delete(resource) session.commit() return {"ok": True}
async def extract_user_id(Authorization: str = Header(None)) -> ObjectId: try: decoded = jwt.decode(jwt=Authorization.split()[1], key=AUTH_SECRET, algorithms=["HS256"]) if "exp" not in decoded: raise jwt.ExpiredSignatureError userId = ObjectId(decoded["userId"]) return userId except: raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail="Unauthorized")
def test_render_http_exception(self): resp = middleware.ProblemResponse(HTTPException(400, 'test error'), ) assert resp.media_type == 'application/problem+json' assert resp.debug is False assert resp.status_code == 400 assert json.loads(resp.body) == { 'type': 'about:blank', 'status': 400, 'title': 'Bad Request', 'detail': 'test error', }
def creat_character(chara: orm.CharaCreate): if chara.name != "" and chara.name not in chara_data: auths = [] chara_data[chara.name] = { "auths": auths, "description": chara.description, } settings.value["character"]["charas"] = chara_data settings.value.update() return chara.name else: raise HTTPException(403, "name exists or none")
def get_logged_user(token: str = Depends(oauth_scheme), db: Session = Depends(get_db)) -> UserOut: access_token = Token(token) username = access_token.get_username() if not username: return HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid Token") db_user = db.query(users.User).get(username) return UserOut(username=db_user.username, name=db_user.name, surname=db_user.surname, active=db_user.active)