def create_meeting(meetingData: MeetingType): """ Create a new meeting. """ try: meeting = Meeting() meeting.validate(meetingData) meeting = Meeting.create(**dump_schema(meetingData)) headers = {"Content-Location": f"/v1/meetings/{meeting.id}"} msg = "Meeting created successfully." log.info(f"{msg} with id: {meeting.id}") return HTTP_201, {"message": f"{msg}"}, headers except ValidationError as error: log.error(f"ValidationError: {error}") raise HTTPError(HTTP_400, {"errors": str(error)}) except ConflictError as error: log.error(f"ConflictError: {error}") raise HTTPError(HTTP_409, {"errors": str(error)})
def handle( resolver: DependencyResolver, request: Request, environ: Environ, route: Optional[Route], ) -> Response: if route is None or not getattr(route.handler, "supports_ws", False): return handler() try: connection = request.headers["connection"] upgrade = request.headers["upgrade"] websocket_key = request.headers["sec-websocket-key"] websocket_version = request.headers["sec-websocket-version"] except HeaderMissing as e: raise HTTPError( HTTP_400, {"errors": { str(e): "this header is required" }}) try: origin = request.headers["origin"] except HeaderMissing: origin = "" if self.origin_re and not self.origin_re.match(origin): raise HTTPError(HTTP_400, {"error": "invalid origin"}) if "upgrade" not in connection.lower( ) or "websocket" not in upgrade.lower(): raise HTTPError(HTTP_400, {"error": "invalid upgrade request"}) if websocket_version not in SUPPORTED_VERSIONS: return Response( HTTP_426, headers={"sec-websocket-version": SUPPORTED_VERSIONS_STR}) # TODO: Implement extension handling. # TODO: Implement subprotocol handling. stream = _BufferedStream(environ["gunicorn.socket"]) stream.write( UPGRADE_RESPONSE_TEMPLATE % { b"websocket_accept": b64encode(sha1(f"{websocket_key}{PSK}".encode()).digest()), }) websocket = Websocket(stream) resolver.add_component(_WebsocketComponent(websocket)) try: handler() except Exception as e: handle_exception = resolver.resolve(self.handle_exception) handle_exception(exception=e) finally: websocket.close(CloseMessage()) raise RequestHandled("websocket request was upgraded")
def update_meeting(id: int, meetingData: MeetingType): """ Update a meeting by id """ try: meeting = Meeting.find_or_fail(id) meeting.validate(meetingData) meeting.update(**dump_schema(meetingData)) meeting.save() msg = f"Meeting update successfully." log.info(f"{msg} with id: {id}") return HTTP_200, {"message": msg} except ValidationError as error: log.error(f"ValidationError: {error}") raise HTTPError(HTTP_400, {"errors": str(error)}) except NotFoundError as error: log.error(f"NotFoundError: {error}") raise HTTPError(HTTP_404, {"errors": str(error)}) except ConflictError as error: log.error(f"ConflictError: {error}") raise HTTPError(HTTP_409, {"errors": str(error)})
def auth_user(auth_service_name: str, code: Optional[QueryParam], request: Request): route_url = request.path.split("?")[0] if not code and auth_service_name != AuthTypes.guest.name: # redirect to oauth service try: auth_params: dict = OAUTH_URLS[auth_service_name] except KeyError: raise HTTPError(HTTP_404) auth_query_params = auth_params["query"].copy() auth_query_params["redirect_uri"] = route_url query = urlencode(auth_query_params) return redirect(f"{auth_params['url']}?{query}") try: auth_type = AuthTypes[auth_service_name] except KeyError: raise HTTPError( HTTP_400, {"error": f"Invalid auth type. Must be one of {AuthTypes.options()}"}, ) auth_client = AuthClient(auth_type, code, route_url) user = User.find_external(auth_client.user_id, auth_type.value) if not user: user = User( name=auth_client.user.name, surname=auth_client.user.surname, external_id=auth_client.user.id, auth_type=auth_type.value, avatar=auth_client.user.avatar, ) user.save() token = components.User(id_=str(user.id)).as_token() query = urlencode({"access_token": token.decode("utf-8")}) return redirect(f"{settings.Server.frontend_server_url}/authenticated?{query}")
def resolve(self, authentication: Optional[Header]) -> User: """ Determine the user associated with a request """ if authentication is None: raise HTTPError(HTTP_401, {"error": "Authorization header is required."}) try: return User.from_token(authentication) except Exception as err: LOGGER.error(f"Failed to parse token: {err}") raise HTTPError(HTTP_403, {"error": "Incorrect token."})
def update_todo(todo_id: str, todo: Todo, manager: TodoManager) -> Todo: """Handles PATCH /v1/todos/{id} """ todo = manager.update_by_id(todo_id, todo) if todo is None: raise HTTPError(HTTP_404, {"error": f"todo {todo_id} not found"}) return todo
def get_todo_by_id(todo_id: int, todo_manager: TodoManager) -> Todo: """Retrieves a Todo by id""" try: _todo = todo_manager.get_todo_by_id(todo_id) except EntityNotFound as err: raise HTTPError(HTTP_404, APIResponse(status=404, message=err.message)) return _todo
def get_todo(todo_id: str, manager: TodoManager) -> Todo: """Handles GET /v1/todos/{id} """ todo = manager.get_by_id(int(todo_id)) if todo is None: raise HTTPError(HTTP_404, {"error": f"todo {todo_id} not found"}) return todo
def get_user_by_display_name( display_name: str, user_manager: UserManager) -> Union[User, APIResponse]: try: user = user_manager.get_user_by_display_name(display_name) except EntityNotFound as err: raise HTTPError(HTTP_404, APIResponse(status=404, message=err.message)) return user
def get_comment(comment_id: int, session: Session) -> CommentSchema: ob = session.query(Comment).get(comment_id) if ob is None: raise HTTPError(HTTP_404, {"error": f"comment {comment_id} not found"}) return CommentSchema(id=ob.id, content=ob.content, user_id=ob.user_id, date_created=ob.date_created)
def raise_409(self, id: int): """Raises a 409 HTTP error response in the event of Conflict""" raise HTTPError( HTTP_409, { "status": 409, "message": f"Entity {self.__class__.__name__} with id: {id} already exists" })
def get_todo(todo_id: int, session: Session) -> Todo: todo_ob = session.query(TodoModel).get(todo_id) if todo_ob is None: raise HTTPError(HTTP_404, {"error": f"todo {todo_id} not found"}) return Todo( id=todo_ob.id, description=todo_ob.description, status=todo_ob.status, )
def chat(account: Optional[Account], handler_factory: ChatHandlerFactory, session: Session, socket: Websocket): if not account: raise HTTPError(HTTP_403, {"errors": "forbidden"}) # Grab the username and close the DB session to avoid starvation. username = account.username session.close() handler = handler_factory(socket, username) handler.handle_until_close()
def create_account(account_data: AccountData, account_manager: AccountManager) -> AccountData: try: account = account_manager.create(account_data.username, account_data.password) return schema_from_model(AccountData, account) except UsernameTaken: raise HTTPError(HTTP_400, {"errors": { "username": "******" }})
def get_user(user_id: int, session: Session) -> UserSchema: ob = session.query(User).get(user_id) if ob is None: raise HTTPError(HTTP_404, {"error": f"user {user_id} not found"}) return UserSchema( id=ob.id, email_address=ob.email_address, display_name=ob.display_name, title=ob.title, # comments=ob.comments )
def create_session(session: Session, session_data: SessionData, account_manager: AccountManager): account = account_manager.find_by_username_and_password( session_data.username, session_data.password) if not account: raise HTTPError( HTTP_400, {"errors": { "username": "******" }}) session["account_id"] = account.id return {}
def send_envelope(envelope: Envelope) -> Response: if envelope.recipient != "*": try: MAILBOXES[envelope.recipient].put(envelope) except KeyError: raise HTTPError(HTTP_404, {"error": f"user {envelope.recipient} not found"}) else: for mailbox in MAILBOXES.values(): mailbox.put(envelope) return Response(HTTP_204)
def middleware(jwt_identity: JWTIdentity, settings: Settings) -> Any: white_list = settings.get("JWT_AUTH_WHITELIST", []) if ( getattr(handler, "allow_anonymous", False) or handler.__name__ in white_list ): return handler() # TODO change this error message to something more sensible. if jwt_identity is None: raise HTTPError( HTTP_401, response="UNAUTHORIZED", headers={"WWW-Authenticate": "Bearer"}, ) try: jwt_identity.token.validate() except TokenValidationError as err: raise HTTPError( HTTP_401, response={"status": 401, "error_message": str(err)}, headers={"WWW-Authenticate": "Bearer"}, ) if hasattr(handler, "claims"): claim_errors = [ {k: v} for k, v in handler.claims.items() if k not in jwt_identity.token or v != jwt_identity.token.get(k) ] if claim_errors: raise HTTPError( HTTP_403, response={"status": 403, "error_message": claim_errors}, ) return handler()
def create_user(user: User, user_manger: UserManager) -> User: try: _user = user_manger.create_user(user) except IntegrityError as err: # noqa: F841 raise HTTPError( HTTP_409, APIResponse( status=409, message= f"User email {user.email} or {user.display_name} already in use.", ), ) headers = {"Location": _user.href} return HTTP_201, _user, headers
def get_room_by_id(id: int): """ Get room by id. """ try: room = Room.find_or_fail(id) log.info(f"Get room by id: {id}") return HTTP_200, room.serialize() except NotFoundError as error: log.error(f"NotFoundError: {error}") raise HTTPError(HTTP_404, {"errors": str(error)})
def get_meetings(room_id: Optional[QueryParam], date: Optional[QueryParam]): """ Return all meetings. """ try: meetings = Meeting.by_room_id(room_id).by_date(date).get() log.info("Get all meetings") return HTTP_200, meetings.serialize() except ValidationError as error: log.error(f"ValidationError: {error}") raise HTTPError(HTTP_400, {"errors": str(error)})
def get_meeting_by_id(id: int): """ Get meeting by id. """ try: meeting = Meeting.find_or_fail(id) log.info(f"Get meeting by id: {id}") return meeting.serialize() except NotFoundError as error: log.error(f"NotFoundError: {error}") raise HTTPError(HTTP_404, {"errors": str(error)})
def delete_room(id: int): """ Delete a room by id. """ try: room = Room.find_or_fail(id) room.delete() msg = "Room deleted successfully." log.info(f"{msg} with id: {id}") return HTTP_200, {"message": msg} except NotFoundError as error: log.error(f"NotFoundError: {error}") raise HTTPError(HTTP_404, {"errors": str(error)})
def delete_meeting(id: int): """ Delete a meeting by id. """ try: meeting = Meeting.find_or_fail(id) meeting.delete() msg = f"Meeting deleted successfully." log.info(f"{msg} with id: {id}") return HTTP_200, {"message": msg} except NotFoundError as error: log.error(f"NotFoundError: {error}") raise HTTPError(HTTP_404, {"errors": str(error)})
def create_room(roomData: RoomType): """ Create a new room. """ try: name = roomData.name Room.validate(name) room = Room.create(name=name) headers = {"Content-Location": f"/v1/rooms/{room.id}"} msg = "Room created successfully." log.info(f"{msg} with id: {room.id}") return HTTP_201, {"message": msg}, headers except ConflictError as error: raise HTTPError(HTTP_409, {"errors": str(error)})
def update_room(id: int, roomData: RoomType): """ Update a room by id """ try: room = Room.find_or_fail(id) room.name = roomData.name room.save() msg = "Room update successfully." log.info(f"{msg} with id: {id}") return HTTP_200, {"message": msg} except NotFoundError as error: log.error(f"NotFoundError: {error}") raise HTTPError(HTTP_404, {"errors": str(error)})
def get_kitten(kitten_id: int, session: Session) -> Kitten: kitten_ob = session.query(KittenModel).get(kitten_id) if kitten_ob is None: raise HTTPError(HTTP_404, {"error": f"kitten {kitten_id} not found"}) return Kitten(id=kitten_ob.id, name=kitten_ob.name)
def handle(authorization: Optional[Header]): if authorization != "Bearer authorized": raise HTTPError(HTTP_403, {"error": "Forbidden"}) return handler()
def middleware(request: Request, authorization: Optional[Header]) -> Any: if authorization != "Bearer secret" and request.path not in [ "/_docs", "/_schema" ]: raise HTTPError(HTTP_403, {"error": "forbidden"}) return handler()
def middleware(authorization: Optional[Header]) -> Any: if authorization != "secret": raise HTTPError(HTTP_403, {"error": "forbidden"}) return handler()