def parse(self, body: http.Body) -> typing.Any: if not body: raise exceptions.BadRequest(detail='Empty JSON') try: return json.loads(body.decode('utf-8')) except json.JSONDecodeError: raise exceptions.BadRequest(detail='Invalid JSON')
def login(data: UserData, jwt: JWT) -> dict: # do some check with your database here to see if the user is authenticated user = db_login(data) # print(user) if not user: raise exceptions.Forbidden('Incorrect username or password.') payload = { 'id': user.id, 'username': user.email, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, 'phone': user.phone, 'language': user.language, 'groups': user.groups, 'location': user.location, 'picture': user.picture, # expiration data 'iat': datetime.datetime.utcnow(), 'exp': datetime.datetime.utcnow() + JWT_EXPIRATION_TIME } # noinspection PyUnresolvedReferences token = jwt.encode(payload) if token is None: # encoding failed, handle error raise exceptions.BadRequest() return {'token': token}
def resolve(self, content: Body, headers: Headers, parameter: Parameter): if not content: raise NotImplementedError content_type = headers.get('Content-Type') try: codec = negotiate_content_type(self.codecs, content_type) except exceptions.NoCodecAvailable: raise exceptions.UnsupportedMediaType() try: value = codec.decode(content, headers=headers) except exceptions.ParseError as exc: raise exceptions.BadRequest(str(exc)) try: return self.handle_parameter(parameter, value) except Exception: raise exceptions.BadRequest(f"{parameter.name} invalid")
def only_editable_today(self): """ Permission où le jour de modification doit correspondre au jour de création. """ today = pendulum.now(settings.TZ) created = pendulum.instance(self.acte.created).in_tz(settings.TZ) if not today.is_same_day(created): raise exceptions.BadRequest( "Un acte ne peut être modifié en dehors du jours même")
def get_one(self, key, value): """ obtiene un usuario dada una llave y un valor, en caso de pasar la llave con el nombre password lanzara una exepcion """ if key == 'password': raise exceptions.BadRequest('password key is not allow') return object_id_to_str(self.users.find_one({key: value}))
def _check_id_format(feature_id): """ This function check the id format. """ id_format = "^(\w+).+\S$" if not re.match(id_format, feature_id): msg = "The id field cannot contains whitespaces." raise exceptions.BadRequest({"message": msg})
def _check_version_format(version): """ This function check the version format. """ version_format = "^[\d].[\d].[\d]$" if not re.match(version_format, version): msg = "The version format is invalid. The correct is (Example: 1.0.0)." raise exceptions.BadRequest({"message": msg})
def create(self, user): """ crea un usuario y retorna los datos del usuario creado """ user = remove_object_id(dict(user)) try: new_user = self.users.insert_one(user).inserted_id except Exception as e: raise exceptions.BadRequest('resource not created') new_user = self.users.find_one({'_id':new_user}) return object_id_to_str(new_user)
async def update_article(article_id: int, data: http.RequestData, password: http.Header): # if not is_auth(password): # raise exceptions.BadRequest() if not data['title']: raise exceptions.BadRequest() try: repo.update_article(article_id, data['title']) except LookupError: raise exceptions.NotFound()
async def create_article(app: App, data: http.RequestData, password: http.Header) -> http.JSONResponse: # if not is_auth(password): # raise exceptions.BadRequest() if not data['title']: raise exceptions.BadRequest() article_id = repo.add_article({'title': data['title']}) url = app.reverse_url('get_article', article_id=article_id) headers = {'Location': url} return http.JSONResponse({}, status_code=201, headers=headers)
def parse(self, body: http.Body) -> typing.Any: if not body: raise exceptions.BadRequest(detail=f'Empty MessagePack: {body}.') try: if has_msgpack: data_from_msgpack = loads(msgpack.unpackb(body)) else: data_from_msgpack = loads(umsgpack.unpackb(body)) except UnicodeEncodeError as error: raise exceptions.BadRequest( detail=f'Invalid Unicode UTF-8 on MessagePack error: {error}.') except ValueError as error: raise exceptions.BadRequest( detail=f'Invalid Keys or Values on MessagePack error: {error}') except JSONDecodeError as error: raise exceptions.BadRequest(detail=f'Invalid MessagePack: {error}') except Exception as error: raise exceptions.BadRequest( detail=f'{self} Unknown Exception: {error}, parsing {body}.') else: return data_from_msgpack
def resolve(self, route: Route, data: http.RequestData): body_field = route.link.get_body_field() if not body_field or not body_field.schema: return data validator = body_field.schema try: return validator.validate(data, allow_coerce=True) except validators.ValidationError as exc: raise exceptions.BadRequest(exc.detail)
def resolve(parameter: Parameter, params_dict): try: value = params_dict[parameter.name] except KeyError: if parameter.default is not parameter.empty: return parameter.default else: raise exceptions.NotFound( f"Parameter {parameter.name} not resolved") try: return parameter.annotation(value) except Exception: raise exceptions.BadRequest(f"Parameter {parameter.name} invalid")
def resolve(self, content: http.Body, headers: http.Headers): if not content: return None content_type = headers.get('Content-Type') try: codec = negotiate_content_type(self.codecs, content_type) except exceptions.NoCodecAvailable: raise exceptions.UnsupportedMediaType() try: return codec.decode(content, headers=headers) except exceptions.ParseError as exc: raise exceptions.BadRequest(str(exc))
def resolve(self, route: Route, query_params: http.QueryParams) -> ValidatedQueryParams: query_fields = route.link.get_query_fields() validator = validators.Object( properties=[(field.name, field.schema if field.schema else validators.Any()) for field in query_fields], required=[field.name for field in query_fields if field.required]) try: query_params = validator.validate(query_params, allow_coerce=True) except validators.ValidationError as exc: raise exceptions.BadRequest(exc.detail) return ValidatedQueryParams(query_params)
def login(data: UserData, jwt: JWT) -> dict: # do some check with your database here to see if the user is authenticated if data.email != USERS_DB['email'] or data.password != USERS_DB['password']: raise exceptions.Forbidden('Incorrect username or password.') payload = { 'id': USERS_DB['id'], 'username': USERS_DB['email'], 'iat': datetime.datetime.utcnow(), 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60) # ends in 60 minutes } token = jwt.encode(payload) if token is None: # encoding failed, handle error raise exceptions.BadRequest() return {'token': token}
def login(self, username, password): """ comprueba usuario y contraseña y retorna un token con tiempo de expiracion """ user = self.users.find_one({'username': username}) if user: ph = PasswordHasher() try: if ph.verify(user['password'], password): exp = datetime.utcnow() + timedelta(hours=EXPIRY_TIME) token = jwt.encode(payload={'user': str(user['_id']), 'exp': exp}, key=SECRET_KEY) return {'token': token.decode('UTF-8')} except VerifyMismatchError: raise exceptions.BadRequest('Incorrect password') raise exceptions.NotFound('User not found')
def update_id(p: http.QueryParam, name: str, login: http.QueryParam, password: http.QueryParam) -> dict: _auth(p) old_id = redisclient.get_id(name) if not old_id: raise exceptions.NotFound() new_id = json.loads(old_id) if not (login or password): raise exceptions.BadRequest() if login: new_id['login'] = login if password: new_id['password'] = password response = redisclient.set_id(name, json.dumps(new_id)) if not response: raise exceptions.HTTPException( 'Internal error while updating ' + 'identity {}'.format(name), 500) return json.loads(redisclient.get_id(name))
def uquery(params: http.QueryParams) -> list: try: fopen = open(fields["fpuser"], "r") except: b = exceptions.NotFound() b.default_detail = "Bad user file path" raise b retlist = [] if (not params._list): raise exceptions.BadRequest() ##Empty for line in fopen.read().splitlines(): f = line.split(":") f.pop(1) for i, ufield in enumerate(f): if (params.get(userf[i]) and params.get(userf[i]) != ufield): break if (i == len(f) - 1): retlist.append(dict(zip(userf, f))) return retlist
def resolve(self, authorization: http.Header) -> User: """ Determina el usuario asociado con una peticion, usando Token de autenticacion """ if authorization is None: return None scheme, token = authorization.split() if scheme.lower() != 'token': return None try: token = jwt.decode(jwt=token, key=SECRET_KEY, algorithm=ALGORITHM) user = UserDAO() user = user.users.find_one({'_id': ObjectId(token['user'])}) if user: return User(_id=str(user['_id']), username=user['username'], groups=user['groups']) except Exception as e: raise exceptions.BadRequest(str(e)) return None
def gquery(params: http.QueryParams) -> list: try: fopen = open(fields["fpgroup"], "r") except: b = exceptions.NotFound() b.default_detail = "Bad group file path" raise b retlist = [] if (not params._list): raise exceptions.BadRequest() ##Empty for line in fopen.read().splitlines(): f = line.split(":") f.pop(1) for i, gfield in enumerate(f): if (i == len(f) - 1): #last element is always member check f[-1] = f[-1].split(",") if (params._dict.get("member")): qmems = params.get_list("member") #get list of members if (len(qmems) > len(f[-1])): break if (len(set(qmems) & set(f[-1])) != len(qmems)): break retlist.append(dict(zip(groupf, f))) if (params.get(groupf[i]) and params.get(groupf[i]) != gfield): break return retlist
def resolve(self, parameter: inspect.Parameter, data: ValidatedRequestData): try: return parameter.annotation(data) except validators.ValidationError as exc: raise exceptions.BadRequest(exc.detail)
def fail() -> dict: raise exceptions.BadRequest("fail")
def error(): raise exceptions.BadRequest()
def resolve(self, parameter: Parameter, query_params: QueryParams): try: return self.handle_parameter(parameter, query_params) except Exception: raise exceptions.BadRequest(f"Parameter {parameter.name} invalid")
def bad_request(): raise exceptions.BadRequest({"message": "bad request"})