示例#1
0
async def DELETE_Group(request):
    """HTTP method to delete a group resource"""
    log.request(request)
    app = request.app
    meta_cache = app['meta_cache']

    group_id = request.match_info.get('id')
    if not group_id:
        msg = "Missing group id"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)
    if not isValidUuid(group_id, "Group"):
        msg = f"Invalid group id: {group_id}"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)

    username, pswd = getUserPasswordFromRequest(request)
    await validateUserPassword(app, username, pswd)

    domain = getDomainFromRequest(request)
    if not isValidDomain(domain):
        msg = f"Invalid domain: {domain}"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)
    bucket = getBucketForDomain(domain)

    # get domain JSON
    domain_json = await getDomainJson(app, domain)

    # TBD - verify that the obj_id belongs to the given domain
    await validateAction(app, domain, group_id, username, "delete")

    verifyRoot(domain_json)

    if group_id == domain_json["root"]:
        msg = "Forbidden - deletion of root group is not allowed - delete domain first"
        log.warn(msg)
        raise HTTPForbidden()

    req = getDataNodeUrl(app, group_id)
    req += "/groups/" + group_id
    params = {}
    if bucket:
        params["bucket"] = bucket
    log.debug(f"http_delete req: {req} params: {params}")

    await http_delete(app, req, params=params)

    if group_id in meta_cache:
        del meta_cache[group_id]  # remove from cache

    resp = await jsonResponse(request, {})
    log.response(request, resp=resp)
    return resp
示例#2
0
async def DELETE_Attribute(request):
    """HTTP method to delete a attribute resource"""
    log.request(request)
    app = request.app
    collection = getRequestCollectionName(
        request)  # returns datasets|groups|datatypes

    obj_id = request.match_info.get('id')
    if not obj_id:
        msg = "Missing object id"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)
    if not isValidUuid(obj_id, obj_class=collection):
        msg = f"Invalid object id: {obj_id}"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)
    attr_name = request.match_info.get('name')
    log.debug(f"Attribute name: [{attr_name}]")
    validateAttributeName(attr_name)

    username, pswd = getUserPasswordFromRequest(request)
    await validateUserPassword(app, username, pswd)

    domain = getDomainFromRequest(request)
    if not isValidDomain(domain):
        msg = f"Invalid domain: {domain}"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)
    bucket = getBucketForDomain(domain)

    # get domain JSON
    domain_json = await getDomainJson(app, domain)
    if "root" not in domain_json:
        log.error(f"Expected root key for domain: {domain}")
        raise HTTPBadRequest(reason="Unexpected Error")

    # TBD - verify that the obj_id belongs to the given domain
    await validateAction(app, domain, obj_id, username, "delete")

    req = getDataNodeUrl(app, obj_id)
    req += '/' + collection + '/' + obj_id + "/attributes/" + attr_name
    log.info("PUT Attribute: " + req)
    params = {}
    if bucket:
        params["bucket"] = bucket
    rsp_json = await http_delete(app, req, params=params)

    log.info(f"PUT Attribute resp: {rsp_json}")

    hrefs = []  # TBD
    req_rsp = {"hrefs": hrefs}
    resp = await jsonResponse(request, req_rsp)
    log.response(request, resp=resp)
    return resp
示例#3
0
def getUserPasswordFromRequest(request):
    """ Return user defined in Auth header (if any)
    """
    user = None
    pswd = None
    app = request.app
    if 'Authorization' not in request.headers:
        log.debug("no Authorization in header")
        return None, None
    scheme, _, token =  request.headers.get('Authorization', '').partition(' ')
    if not scheme or not token:
        log.info("Invalid Authorization header")
        raise HTTPBadRequest("Invalid Authorization header")

    if scheme.lower() == 'basic':
        # HTTP Basic Auth
        try:
            token = token.encode('utf-8')  # convert to bytes
            token_decoded = base64.decodebytes(token)
        except binascii.Error:
            msg = "Malformed authorization header"
            log.warn(msg)
            raise HTTPBadRequest(msg)
        if token_decoded.index(b':') < 0:
            msg = "Malformed authorization header (No ':' character)"
            log.warn(msg)
            raise HTTPBadRequest(msg)
        user, _, pswd = token_decoded.partition(b':')
        if not user or not pswd:
            msg = "Malformed authorization header, user/password not found"
            log.warn(msg)
            raise HTTPBadRequest(msg)
        user = user.decode('utf-8')   # convert bytes to string
        pswd = pswd.decode('utf-8')   # convert bytes to string
    elif scheme.lower() == 'bearer' and config.get('azure_app_id') and config.get('azure_resource_id'):
        # Azure AD Oauth
        app_id = config.get('azure_app_id')
        resource_id = config.get('azure_resource_id')
        log.debug(f"Got bearer token  app_id: {app_id} resource_id: {resource_id}")
        #log.debug(f"bearer token: {token}")
        # see if we've already validated this token
        user = _checkTokenCache(app, token)
        if not user:
            user = _verifyBearerToken(app, token)
        if user:
            pswd = token

    else:
        msg = f"Unsupported Authorization header scheme: {scheme}"
        log.warn(msg)
        raise HTTPBadRequest(msg)

    return user, pswd
def param_to_positive_int(params: Dict, name: str, default: int) -> int:
    """
    Convert value from params dict to int
    Raise exception if it is negative or not a number
    """
    try:
        result = int(params.get(name, default))
    except ValueError:
        raise HTTPBadRequest(text=f'Invalid param "{name}" value')
    else:
        if result < 0:
            raise HTTPBadRequest(text=f'Invalid param "{name}" value')
        return result
示例#5
0
文件: views.py 项目: fedtf/sd_eshop
    async def post(self):
        try:
            data = await self.request.json()
        except JSONDecodeError:
            raise HTTPBadRequest(reason='Invalid json')

        try:
            product = Product(**data)
            await product.commit()
        except ValidationError as e:
            raise HTTPBadRequest(reason=e.normalized_messages())

        return web.json_response(product.dump(), status=HTTPStatus.CREATED)
示例#6
0
async def GET_DatasetShape(request):
    """HTTP method to return JSON for dataset's shape"""
    log.request(request)
    app = request.app

    dset_id = request.match_info.get('id')
    if not dset_id:
        msg = "Missing dataset id"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)
    if not isValidUuid(dset_id, "Dataset"):
        msg = f"Invalid dataset id: {dset_id}"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)

    username, pswd = getUserPasswordFromRequest(request)
    if username is None and app['allow_noauth']:
        username = "******"
    else:
        await validateUserPassword(app, username, pswd)

    domain = getDomainFromRequest(request)
    if not isValidDomain(domain):
        msg = f"Invalid domain: {domain}"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)
    bucket = getBucketForDomain(domain)

    # get authoritative state for dataset from DN (even if it's in the meta_cache).
    dset_json = await getObjectJson(app, dset_id, refresh=True, bucket=bucket)

    await validateAction(app, domain, dset_id, username, "read")

    hrefs = []
    dset_uri = '/datasets/' + dset_id
    self_uri = dset_uri + "/shape"
    hrefs.append({'rel': 'self', 'href': getHref(request, self_uri)})
    dset_uri = '/datasets/' + dset_id
    hrefs.append({'rel': 'owner', 'href': getHref(request, dset_uri)})
    root_uri = '/groups/' + dset_json["root"]
    hrefs.append({'rel': 'root', 'href': getHref(request, root_uri)})

    resp_json = {}
    resp_json["shape"] = dset_json["shape"]
    resp_json["hrefs"] = hrefs
    resp_json["created"] = dset_json["created"]
    resp_json["lastModified"] = dset_json["lastModified"]

    resp = await jsonResponse(request, resp_json)
    log.response(request, resp=resp)
    return resp
示例#7
0
文件: chunk_dn.py 项目: derobins/hsds
async def DELETE_Chunk(request):
    """HTTP DELETE method for /chunks/
    Note: clients (i.e. SN nodes) don't directly delete chunks.  This method should
    only be called by the AN node.
    """
    log.request(request)
    app = request.app
    params = request.rel_url.query
    chunk_id = request.match_info.get('id')
    if not chunk_id:
        msg = "Missing chunk id"
        log.error(msg)
        raise HTTPBadRequest(reason=msg)
    log.info(f"DELETE chunk: {chunk_id}")

    if not isValidUuid(chunk_id, "Chunk"):
        msg = f"Invalid chunk id: {chunk_id}"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)
    if "bucket" in params:
        bucket = params["bucket"]
    else:
        bucket = None

    validateInPartition(app, chunk_id)

    chunk_cache = app['chunk_cache']
    s3key = getS3Key(chunk_id)
    log.debug(f"DELETE_Chunk s3_key: {s3key}")

    if chunk_id in chunk_cache:
        del chunk_cache[chunk_id]

    filter_map = app["filter_map"]
    dset_id = getDatasetId(chunk_id)
    if dset_id in filter_map:
        # The only reason chunks are ever deleted is if the dataset is being deleted,
        # so it should be safe to remove this entry now
        log.info(f"Removing filter_map entry for {dset_id}")
        del filter_map[dset_id]

    if await isStorObj(app, s3key, bucket=bucket):
        await deleteStorObj(app, s3key, bucket=bucket)
    else:
        log.info(
            f"delete_metadata_obj - key {s3key} not found (never written)?")

    resp_json = {}
    resp = json_response(resp_json)
    log.response(request, resp=resp)
    return resp
示例#8
0
async def DELETE_Group(request):
    """HTTP method to delete a group resource"""
    log.request(request)
    app = request.app
    meta_cache = app['meta_cache']

    group_id = request.match_info.get('id')
    if not group_id:
        msg = "Missing group id"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)
    if not isValidUuid(group_id, "Group"):
        msg = "Invalid group id: {}".format(group_id)
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)

    username, pswd = getUserPasswordFromRequest(request)
    await validateUserPassword(app, username, pswd)

    domain = getDomainFromRequest(request)
    if not isValidDomain(domain):
        msg = "Invalid host value: {}".format(domain)
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)

    # get domain JSON
    domain_json = await getDomainJson(app, domain)
    if "root" not in domain_json:
        log.error("Expected root key for domain: {}".format(domain))
        raise HTTPBadRequest(reason="Unexpected Error")

    # TBD - verify that the obj_id belongs to the given domain
    await validateAction(app, domain, group_id, username, "delete")

    if group_id == domain_json["root"]:
        msg = "Forbidden - deletion of root group is not allowed - delete domain first"
        log.warn(msg)
        raise HTTPForbidden()

    req = getDataNodeUrl(app, group_id)
    req += "/groups/" + group_id

    await http_delete(app, req)

    if group_id in meta_cache:
        del meta_cache[group_id]  # remove from cache

    resp = await jsonResponse(request, {})
    log.response(request, resp=resp)
    return resp
示例#9
0
def validate_request(search_rq: SearchRequest):
    st: SearchType = search_rq.SearchType
    sf: str = search_rq.SearchField

    if st in [SearchType.keywords, SearchType.all, SearchType.description,
              SearchType.title, SearchType.date, SearchType.actor]:
        if sf == "":
            raise HTTPBadRequest()

    if st is SearchType.id:
        try:
            int(sf)
        except ValueError:
            raise HTTPBadRequest()
示例#10
0
async def trading_view_hook_handler(request):
    if not request.body_exists or not request.can_read_body:
        raise HTTPBadRequest()
    body = await request.json()
    await check_auth(request, body)
    logging.info("=" * 80)
    logging.info("got trading_view hook: [%s]" % body)
    try:
        app.process_message(body)
    except (KeyError, ValueError) as e:
        message = "%s %s %s" % (type(e), e.args, e)
        logging.error(message)
        telegram.post_message("=" * 80 + "\nERROR: " + message)
        raise HTTPBadRequest(body=message.encode('utf-8'))
    return web.Response(text='OK')
示例#11
0
 async def manage_updater(self, request: web.Request):
     channel = self.bot.get_channel(int(request.match_info["channel_id"]))
     await self.authenticate_request(request, channel)
     try:
         data = json.loads(await request.content.read())
     except MemoryError:  # if someone wants to try to DoS this by sending large data forms...
         # they aren't getting anything
         return ""
     except json.JSONDecodeError:
         raise HTTPBadRequest(reason="Malformed JSON") from None
     db_channel = await get_from_db(channel)
     if "autoupdater" not in data:
         raise HTTPBadRequest(reason="No autoupdater data sent")
     ad = data["autoupdater"]
     if "enabled" not in ad:
         raise HTTPBadRequest(
             reason="Didn't specify whether to enable updater.")
     if ad["enabled"]:
         db_channel.autoupdater.already_set = True
         if "country_name" in ad:
             name = await self.bot.worldometers_api.try_to_get_name(
                 ad["country_name"])
             if name[0] in ("country", "world", "continent"):
                 db_channel.autoupdater.country_name = name[1]
             else:
                 raise HTTPBadRequest(reason="Country/continent not found")
         if "delay" in ad:
             try:
                 delay = int(ad["delay"])
             except ValueError:
                 raise HTTPBadRequest(reason="Delay is not numeric")
             if 600 >= delay > 31536000:
                 raise HTTPBadRequest(
                     reason=
                     "Delay outside of constraints: 3153600 > delay >= 600")
             db_channel.autoupdater.delay = delay
         if "force_update" in ad:
             try:
                 force_update = bool(ad["force_update"])
             except ValueError:
                 raise HTTPBadRequest(reason="Force update not boolean")
             db_channel.autoupdater.force_update = force_update
         if "do_update_at" in ad:
             try:
                 do_update_at = datetime.utcfromtimestamp(
                     float(ad["do_update_at"]))
             except ValueError:
                 raise HTTPBadRequest(
                     reason="Update time not a valid UTC unix timestamp")
             db_channel.autoupdater.do_update_at = do_update_at
     else:
         db_channel.autoupdater.already_set = False
     try:
         await db_channel.autoupdater.save(force_update=True)
         await db_channel.save(force_update=True)
     except tortoise.exceptions.IntegrityError:
         raise HTTPInternalServerError(reason="Database integrity error")
     return web.json_response({"result": "ok"})
示例#12
0
文件: ctype_sn.py 项目: jjaraalm/hsds
async def DELETE_Datatype(request):
    """HTTP method to delete a committed type resource"""
    log.request(request)
    app = request.app
    meta_cache = app['meta_cache']

    ctype_id = request.match_info.get('id')
    if not ctype_id:
        msg = "Missing committed type id"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)
    if not isValidUuid(ctype_id, "Type"):
        msg = f"Invalid committed type id: {ctype_id}"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)

    username, pswd = getUserPasswordFromRequest(request)
    await validateUserPassword(app, username, pswd)

    domain = getDomainFromRequest(request)
    if not isValidDomain(domain):
        msg = f"Invalid domain: {domain}"
        log.warn(msg)
        raise HTTPBadRequest(reason=msg)
    bucket = getBucketForDomain(domain)
    params = {}
    if bucket:
        params["bucket"] = bucket

    # get domain JSON
    domain_json = await getDomainJson(app, domain)
    if "root" not in domain_json:
        log.error(f"Expected root key for domain: {domain}")
        raise HTTPBadRequest(reason="Unexpected Error")

    # TBD - verify that the obj_id belongs to the given domain
    await validateAction(app, domain, ctype_id, username, "delete")

    req = getDataNodeUrl(app, ctype_id) + "/datatypes/" + ctype_id

    await http_delete(app, req, params=params)

    if ctype_id in meta_cache:
        del meta_cache[ctype_id]  # remove from cache

    resp = await jsonResponse(request, {})
    log.response(request, resp=resp)
    return resp
示例#13
0
async def session_post(request: Request):
    session_maker = request.app['db_session_manager']
    session: Session = session_maker()
    try:
        data = await request.json()

        if data:
            user = session.query(Users).filter_by(login=data['login']).first()
            if not user:
                return HTTPNotFound()

            user_id = user.id
            if UsersSchema.check_password_hash(data['password'], user.password):
                response = HTTPAccepted()
                await remember(request, response, json.dumps({'user_id': user_id, 'login': user.login}))
                return response
            else:
                response = HTTPUnauthorized()
                if user_id:
                    await forget(request, response)
                return response
        else:
            return HTTPBadRequest()
    except Exception:
        raise
    finally:
        session.close()
示例#14
0
async def DELETE_Object(request):
    log.request(request)

    app = request.app
    delete_set = app["delete_set"]

    objid = request.match_info.get('id')
    if not isValidUuid(objid):
        log.warn(f"Invalid id: {objid}")
        raise HTTPBadRequest()

    if isSchema2Id(objid):
        # get rootid for this id
        collection = getCollectionForId(objid)
        if collection == "datasets":
            delete_set.add(objid)
        elif collection == "groups":
            # only need to do anything if this the root group
            if isRootObjId(objid):
                log.info(f"adding root group: {objid} to delete_set")
                delete_set.add(objid)
            else:
                log.info(f"ignoring delete non-root group: {objid}")
        elif collection == "datatypes":
            log.info(f"ignoring delete for datatype object: {objid}")
        else:
            log.error(f"Unexpected collection type: {collection}")
         
    resp_json = {}
    resp = json_response(resp_json)
    log.response(request, resp=resp)
    return resp
示例#15
0
async def nodestate(request):
    """HTTP method to return information about registed nodes"""
    log.request(request) 
    node_type = request.match_info.get('nodetype', '*')
    node_number = '*'
    if node_type != '*':
        node_number = request.match_info.get('nodenumber', '*')
        
    log.info("nodestate/{}/{}".format(node_type, node_number))
    if node_type not in ("sn", "dn", "*"):
        msg="invalid node_type"
        log.response(request, code=400, message=msg)
        raise HTTPBadRequest(reason=msg)
        
    app = request.app
    resp = StreamResponse()
    resp.headers['Content-Type'] = 'application/json'
    
    if node_number == '*':
        nodes = []
        for node in app["nodes"]:
            if node["node_type"] == node_type or node_type == "*":
                nodes.append(node)
        answer = {"nodes": nodes }
    else:
         answer = {}
         for node in app["nodes"]:
            if node["node_type"] == node_type and str(node["node_number"]) == node_number:
                answer = node
                break
    answer["cluster_state"] = app["cluster_state"]  
    resp = json_response(answer)
    log.response(request, resp=resp)
    return resp
示例#16
0
    async def post_create_user(self, request: Request) -> Response:
        """
        Request to create an user

        Args:
            request: input REST request

        Returns: json REST response with the created user

        """
        LOGGER.info('REST request to create user')

        try:
            username = request['data']['username']
            password = request['data']['password']
            first_name = request['data']['first_name']
            last_name = request['data']['last_name']
            email = request['data']['email']
        except Exception as ex:
            raise HTTPBadRequest(text=str(ex)) from ex

        user_service: UserService = container.get('user_service')
        user_created = await user_service.create_user(username, password, first_name, last_name, email)

        return json_response(dict(user_created), status=200)
示例#17
0
    async def _add_auth_info(self, request: web.Request):
        """Adds the authentication information, if any, to the request.

        Catches exceptions from decoding the payload and converts them to HTTP exceptions to be propagated.
        If authentication is disabled via :attr:`~_ignore_auth` doesn't do anything.

        Headers are kept in a `CIMultiDictProxy`_ so case of the header is not important.

        .. _CIMultiDictProxy: https://multidict.readthedocs.io/en/stable/multidict.html#multidict.CIMultiDictProxy
        """
        if self._ignore_auth:
            return None

        try:
            oidc_data = request.headers["X-Amzn-Oidc-Data"]
        except KeyError:
            logger.warning("No 'X-Amzn-Oidc-Data' header present. Dropping request.")
            raise HTTPProxyAuthenticationRequired()
        try:
            request["auth_payload"] = (self._header_name, await self._decode_payload(oidc_data))
        except ExpiredSignatureError:
            logger.warning("Got expired token. Dropping request.")
            raise HTTPUnauthorized()
        except DecodeError as e:
            logger.warning("Couldn't decode token. Dropping request.")
            logger.debug("Couldn't decode token: %s" % e)
            raise HTTPBadRequest()
示例#18
0
async def company_middleware(request, handler):
    try:
        public_key = request.match_info.get('company')
        if public_key:
            c = sa_companies.c
            select_fields = c.id, c.name, c.public_key, c.private_key, c.name_display, c.options, c.domains
            q = select(select_fields).where(c.public_key == public_key)
            conn = await request['conn_manager'].get_connection()
            result = await conn.execute(q)
            company = await result.first()

            if company and company.domains is not None:
                origin = request.headers.get('Origin') or request.headers.get(
                    'Referer')
                if origin and not domain_allowed(company.domains,
                                                 URL(origin).host):
                    raise HTTPForbiddenJson(
                        status='wrong Origin domain',
                        details=
                        f"the current Origin '{origin}' does not match the allowed domains",
                    )
            if company:
                request['company'] = company
            else:
                raise HTTPNotFoundJson(
                    status='company not found',
                    details=f'No company found for key {public_key}',
                )
        return await handler(request)
    except CancelledError:
        raise HTTPBadRequest()
示例#19
0
    async def post(self, request, domain, service):
        """Call a service.

        Returns a list of changed states.
        """
        hass: ha.HomeAssistant = request.app["hass"]
        body = await request.text()
        try:
            data = json.loads(body) if body else None
        except ValueError:
            return self.json_message("Data should be valid JSON.",
                                     HTTPStatus.BAD_REQUEST)

        context = self.context(request)

        try:
            await hass.services.async_call(domain,
                                           service,
                                           data,
                                           blocking=True,
                                           context=context)
        except (vol.Invalid, ServiceNotFound) as ex:
            raise HTTPBadRequest() from ex

        changed_states = []

        for state in hass.states.async_all():
            if state.context is context:
                changed_states.append(state)

        return self.json(changed_states)
示例#20
0
def _init_header(request: web.Request,
                 token: str) -> CIMultiDict | dict[str, str]:
    """Create initial header."""
    headers = {}

    # filter flags
    for name, value in request.headers.items():
        if name in (
                hdrs.CONTENT_LENGTH,
                hdrs.CONTENT_ENCODING,
                hdrs.TRANSFER_ENCODING,
                hdrs.SEC_WEBSOCKET_EXTENSIONS,
                hdrs.SEC_WEBSOCKET_PROTOCOL,
                hdrs.SEC_WEBSOCKET_VERSION,
                hdrs.SEC_WEBSOCKET_KEY,
        ):
            continue
        headers[name] = value

    # Inject token / cleanup later on Supervisor
    headers[X_HASSIO] = os.environ.get("HASSIO_TOKEN", "")

    # Ingress information
    headers[X_INGRESS_PATH] = f"/api/hassio_ingress/{token}"

    # Set X-Forwarded-For
    forward_for = request.headers.get(hdrs.X_FORWARDED_FOR)
    if (peername := request.transport.get_extra_info("peername")) is None:
        _LOGGER.error("Can't set forward_for header, missing peername")
        raise HTTPBadRequest()
示例#21
0
    async def patch(self):
        resource = await self._retrieve_resource()

        try:
            payload = await self.request.json()
            payload = self._clean_not_editable_fields(payload)
            resource.update(payload)
            ResourceModel.schema.validate(resource.to_dict())
        except SchemaError as error:
            raise HTTPBadRequest(reason=error.code)
        except JSONDecodeError:
            raise HTTPBadRequest(reason='Invalid payload')

        await resource.save()

        return self.response(200, resource)
示例#22
0
    def _process_auth(
        self, request: Request
    ) -> Tuple['Config', Union[SimpleNamespace, 'User'], Optional[str]]:
        config = self.config(request)
        if not config:
            raise HTTPNotFound()

        hass_user = request.get('hass_user')
        request_id = request.headers.get('X-Request-Id')
        remote_accepted = False
        if config.diagnostics_mode:
            remote_address = ipaddress.ip_address(request.remote)
            for network in config.diagnostics_mode:
                if remote_address in network:
                    remote_accepted = True
                    break

        if remote_accepted:
            # Facilitate the use of diagnostics mode by adding dummy data to the request
            if not hass_user:
                hass_user = SimpleNamespace(id=999999)
            if not request_id:
                request_id = str(uuid4()).upper()
        elif not hass_user:
            raise HTTPUnauthorized()
        elif not request_id:
            raise HTTPBadRequest()

        return config, hass_user, request_id
示例#23
0
async def discover(request: Request):
    """Discover peering network nodes.

    List of nodes with highest rating will be returned by default.

    ?hash=<magnet> — return list of peers ordered by distance to provided hash

    Peer list size is always limited by the node (recommended is 500 items)
    and has no pagination by design.
    """
    magnet = request.query.get('magnet')
    if magnet and not is_magnet(magnet):
        log.error("Requested value is not a magnet")
        raise HTTPBadRequest()

    if magnet:
        peers = await request.app['sarafan'].nearest_peers(magnet)
    else:
        peers = await request.app['sarafan'].hot_peers()

    if peers is None or len(peers) == 0:
        log.warning(
            "Respond with empty peer list: no peers received from application")
        peers = []

    return web.json_response([{
        'service_id': peer.service_id,
        'rating': peer.rating
    } for peer in peers])
示例#24
0
 async def authorize(self, request: Request):
     if 'redirectbacktoken' in request.query:
         # Someone is trying to authenticate with the add-on, direct them to the google auth url
         raise HTTPSeeOther(await self.exchanger.getAuthorizationUrl(
             request.query.get('redirectbacktoken')))
     elif 'state' in request.query and 'code' in request.query:
         state = request.query.get('state')
         code = request.query.get('code')
         try:
             creds = (await self.exchanger.exchange(code)).serialize(
                 include_secret=False)
             # Redirect to "state" address with serialized creentials"
             raise HTTPSeeOther(state + "?creds=" +
                                urllib.parse.quote(json.dumps(creds)))
         except Exception as e:
             if isinstance(e, HTTPSeeOther):
                 # expected, pass this thorugh
                 raise
             self.logError(request, e)
             content = "The server encountered an error while processing this request: " + str(
                 e) + "<br/>"
             content += "Please <a href='https://github.com/sabeechen/hassio-google-drive-backup/issues'>file an issue</a> on Home Assistant Google Backup's GitHub page so I'm aware of this problem or attempt authorizing with Google Drive again."
             return Response(status=500, body=content)
     else:
         raise HTTPBadRequest()
示例#25
0
 async def __aexit__(self, exc_type, exc_val, exc_tb):
     try:
         if self._conn is not None:
             await self._engine.release(self._conn)
             self._conn = None
     except CancelledError:
         raise HTTPBadRequest()
示例#26
0
async def new_document(request):
    post = await request.json()
    text = post.get('text')
    sentences = nltk.sent_tokenize(text)
    if not sentences:
        raise HTTPBadRequest(reason="Empty document")

    pool = request.app['db_pool']
    sentence_ids = []
    queue = request.app['queue']

    async with pool.acquire() as connection:

        async with connection.transaction():
            sql = "INSERT INTO document (id) VALUES (DEFAULT) RETURNING id;"
            document_id = await connection.fetchval(sql)

        for i, s in enumerate(sentences):
            async with connection.transaction():
                sql = """
                  INSERT INTO sentence (id, document_id, ordering, text, indexed)
                  VALUES (DEFAULT, $1, $2, $3, False) RETURNING id;
                """
                sentence_id = await connection.fetchval(sql, document_id, i, s)
            sentence_ids.append(sentence_id)
            await queue.put(sentence_id)

    return web.json_response({
        "success": True,
        "document_id": document_id,
        "sentence_ids": sentence_ids
    })
示例#27
0
文件: api.py 项目: legnaleurc/dvd
    async def create(self):
        kwargs = await self.request.json()
        kwargs = unpack_dict(kwargs, (
            'parent_id',
            'name',
        ))
        ok = all((k in kwargs for k in (
            'parent_id',
            'name',
        )))
        if not ok:
            raise HTTPBadRequest()

        drive: Drive = self.request.app['drive']
        parent_id = kwargs['parent_id']
        name = kwargs['name']
        parent = await drive.get_node_by_id(parent_id)
        try:
            node = await drive.create_folder(
                parent_node=parent,
                folder_name=name,
                exist_ok=False,
            )
            return node.to_dict()
        except Exception as e:
            EXCEPTION('engine', e) << name << parent_id
            raise HTTPConflict() from e
示例#28
0
async def munch(request):
    name = request.query.get("cookie", None)
    if name is None:
        raise HTTPBadRequest(text="Requires cookie param")
    resp = web.HTTPFound(location="/login")
    resp.del_cookie(name=name)
    return resp
示例#29
0
文件: hdf5dtype.py 项目: whigg/hsds
def validateTypeItem(typeItem):
    try:
        dt = createDataType(typeItem)
        log.debug("got numpy type: {}".format(str(dt)))
    except (KeyError, TypeError, ValueError) as e:
        log.warn("Got error parsing type... {}".format(e))
        raise HTTPBadRequest(reason=str(e))
示例#30
0
    async def authenticate(self, request: Request) -> Response:
        """
        Request to authenticate an user

        Args:
            request: input REST request

        Returns: json REST response with the authentication token

        """
        LOGGER.info('REST request to authenticate an user')

        try:
            username = request['data']['username']
            password = request['data']['password']
        except Exception as ex:
            raise HTTPBadRequest(text=str(ex)) from ex

        auth_service: AuthService = container.get('auth_service')
        token_json = await auth_service.authenticate(username, password)

        token_response = json_response(token_json, status=200)
        token_response.set_cookie(name='JWT_TOKEN',
                                  value=token_json['token'],
                                  httponly=True)
        return token_response