Beispiel #1
0
    async def set_state(self, request):
        """
            Relay set value
        """
        relay, status = RelayController.try_intParse(
            request.match_info['relay'])
        if not status:
            return web.HTTPNotFound(text="Relay not found")

        state_in, status = RelayController.try_intParse(
            request.match_info['state'])
        if not status:
            return web.HTTPNotFound(text="State invalid")

        if state_in < 0 or state_in > 1:
            return web.HTTPError()

        relay_mapped = next((x for x in self.mapping if x['id'] == relay),
                            None)
        if relay_mapped == None:
            return web.HTTPError()

        if relay_mapped['active'] == 'high':
            self.gpio.get(relay_mapped['chip']).output(
                relay_mapped['line'], HIGH if state_in else LOW)
        elif relay_mapped['active'] == 'low':
            self.gpio.get(relay_mapped['chip']).output(
                relay_mapped['line'], LOW if state_in else HIGH)

        return web.json_response({"status": "ok"})
Beispiel #2
0
async def del_redirect(request):
    uri = request.match_info["uri"]
    try:
        await request.app["db"].del_redirect(uri)
        return web.HTTPOk()
    except:
        return web.HTTPError()
Beispiel #3
0
 async def post(self):
     name, slug = await get_name_slug(self.request)
     db, session = await get_base_needed(self.request)
     data = await self.request.post()
     token, user = session['token'], session['user']
     whom_user = SITE_STORAGE[user]
     status = await check_token(session_token=token,
                                html_token=data['csrf_token'])
     if status:
         password = data['password']
         status = await Rooms.check_password(db=db,
                                             username=whom_user,
                                             name=name,
                                             slug=slug,
                                             password=password)
         if status:
             session['flag-password-iteration'] = 'pull-password'
             del SITE_STORAGE[user]
             location = self.request.app.router['current_room'].url_for(
                 name=name, slug=slug)
             return web.HTTPFound(location=location)
         else:
             return web.HTTPFound(location='/messages')
     else:
         return web.HTTPError()
Beispiel #4
0
 async def start_scanning(self, request):
     await check_authorized(request)
     try:
         self.adapter.start_scan()
     except Exception as exc:
         return web.HTTPError(reason=str(exc))
     return web.Response()
Beispiel #5
0
 async def stop_discoverable(self, request):
     await check_authorized(request)
     try:
         self.adapter.stop_discoverable()
     except Exception as exc:
         return web.HTTPError(reason=str(exc))
     return web.Response()
 async def handler(request: web.Request) -> NoReturn:
     # Since `resolve_job` excepts any Exception, `assert` will be caught there
     name = request.query.get("name")
     if name != job_name:
         pytest.fail(f"received: {name}")
     owner = request.query.get("owner")
     if owner != "user":
         pytest.fail(f"received: {owner}")
     raise web.HTTPError()
async def delete_collection_endpoint(request: Request):
    origin = request.headers.get("Origin", "")
    data = await request.json()
    h = {"Access-Control-Allow-Origin": origin}
    collection = data.get("collection", None)
    if collection is None:
        return web.HTTPBadRequest(headers=h, reason="Missing required field: 'collection'")
    folder = Path(CONFIG.working_directory).absolute() / "collections" / collection
    try:
        shutil.rmtree(folder)
    except Exception as e:
        return web.HTTPError(reason=f"Error when attempting delete: {e}", headers=h)
    return web.HTTPOk(headers=h)
Beispiel #8
0
    async def post(self) -> Union[web.json_response, web.HTTPException]:

        request_data = await self.request.json()

        if await self.is_user_exist(request_data):
            raise web.HTTPConflict(text="User already exist")

        data = await self.prepare_db_request(request_data)

        result = await self.request.app['db'].users.insert_one(data)

        if result:
            return web.Response(text="User create successfully", status=200)
        raise web.HTTPError(text="Unexpected error")
Beispiel #9
0
async def post_search_settings(request):
    db = request.app['db']
    data = await request.json()

    try:
        validated = search_settings_schema.check(data)
    except DataError as err:
        return web.HTTPError(reason=err.error)

    await add_or_update_setting(db, validated)

    updated_data = await get_setting(db)

    return web.json_response(data=updated_data,
                             content_type='application/json')
Beispiel #10
0
 async def handler(request: web.Request) -> NoReturn:
     # Since `resolve_job` excepts any Exception, `assert` will be caught there
     name = request.query.get("name")
     if name != job_name:
         pytest.fail(f"received: {name}")
     owner = request.query.get("owner")
     if owner != job_owner:
         pytest.fail(f"received: {owner}")
     reverse = request.query.get("reverse")
     if reverse != "1":
         pytest.fail(f"received: reverse={reverse}")
     limit = request.query.get("limit")
     if limit != "1":
         pytest.fail(f"received: limit={limit}")
     raise web.HTTPError()
Beispiel #11
0
async def invite_room(whom_to_send, whom_to_room, redis, user):
    if not whom_to_send or not whom_to_room:
        return web.HTTPError()

    user_ver_slug = await create_slug(user)
    whom_to_room_ver_slug = await create_slug(whom_to_room)

    lst_invite = await redis.hgetall(whom_to_send, encoding='utf-8')
    if lst_invite == {}:
        user = user + '.---.' + str(user_ver_slug)
        whom_to_room = whom_to_room + '.---.' + str(whom_to_room_ver_slug)
        await redis.hmset(whom_to_send, user, whom_to_room)
    else:
        user = user + '.---.' + str(
            user_ver_slug) + f'___-%-_{str(randint(10, 99))}'
        whom_to_room = whom_to_room + '.---.' + str(whom_to_room_ver_slug)
        await redis.hmset(whom_to_send, user, whom_to_room)
Beispiel #12
0
async def middleware(request, handler):
    perf.views += 1

    resp = await handler(request)
    headers = request.headers
    if 'user-agent' in headers:
        print(f'{request.path} has been viewed by', headers['user-agent'])
    else:
        print(f'{request.path} has been viewed by an unknown user', headers)
        return web.HTTPError('Error: No UA found')
    # if ''
    if resp.content_type == 'text/html':
        try:
            resp.text = resp.text.replace('[[PATH]]', request.path)
        except AttributeError:
            pass
    return resp
Beispiel #13
0
    async def get_state(self, request):
        """
            Relay get value
        """
        try:
            relay = int(request.match_info['relay'])
            relay_mapped = next((x for x in self.mapping if x['id'] == relay),
                                None)
            if relay_mapped == None:
                return web.HTTPError()

            relay_value = self.gpio.get(relay_mapped['chip']).value(
                relay_mapped['line'])
            return web.json_response({
                "state":
                RelayController.relay_status(relay_mapped, relay_value)
            })

        except ValueError:
            return web.HTTPNotFound(text="Relay not found")
Beispiel #14
0
    async def _request(cls,
                       url,
                       method='GET',
                       params=None,
                       headers=None,
                       cookies=None,
                       encoding=None,
                       debug=False):
        params = params or {}
        method = method.lower()
        headers = headers or cls.get_header()
        cookies = cookies or cls.cookies
        encoding = encoding or ('utf-8', 'backslashreplace')

        if method not in ('get', 'post'):
            raise web.HTTPError('Method must be of GET or POST')
        async with aiohttp.ClientSession(cookies=cookies) as session:
            request_call = getattr(session, method)
            async with request_call(url,
                                    params=params,
                                    headers=headers,
                                    timeout=30) as res:
                if debug:
                    print('HTTP {} {} {} with params {} and headers {}'.format(
                        method, res.status, url, params, headers))
                if res.status == 200:
                    ctype = res.headers.get('Content-type', '').lower()
                    if 'json' in ctype or url.endswith('json'):
                        data = await res.json()
                    else:
                        data = await res.text(*encoding)
                    return data
                elif res.status == 404:
                    raise web.HTTPNotFound()
                else:
                    raise aiohttp.errors.HttpProcessingError(
                        code=res.status,
                        message=res.reason,
                        headers=res.headers)
async def apply(request: web.BaseRequest):
    context = request.app["request_context"]
    params = await request.json()
    outbound_handler = request.app["outbound_message_router"]

    connection_id = params["connection_id"]
    payload = params["payload"]

    service_id = params["service"]["service_id"]
    consent_schema = params["service"]["consent_schema"]
    service_schema = params["service"]["service_schema"]
    label = params["service"]["label"]

    try:
        connection: ConnectionRecord = await ConnectionRecord.retrieve_by_id(
            context, connection_id
        )
    except StorageNotFoundError:
        raise web.HTTPNotFound(reason="Connection not found")
    #
    # NOTE(KKrzosa): Send a credential offer for consent to the other agent
    # TODO(KKrzosa): Cache the credential definition
    #

    ledger: BaseLedger = await context.inject(BaseLedger)
    issuer: BaseIssuer = await context.inject(BaseIssuer)

    try:
        # NOTE: Register Schema on LEDGER
        async with ledger:
            schema_id, schema_definition = await shield(
                ledger.create_and_send_schema(
                    issuer,
                    "consent_schema",
                    "1.0",
                    [
                        "oca_schema_dri",
                        "oca_schema_namespace",
                        "data_dri",
                        "service_consent_match_id",
                    ],
                )
            )
            LOGGER.info("OK consent schema saved on ledger! %s", schema_id)

        # TODO: Error here with unpacking it returns a dict now
        # NOTE: Register Credential DEFINITION on LEDGER
        async with ledger:
            credential_definition_id, credential_definition, novel = await shield(
                ledger.create_and_send_credential_definition(
                    issuer,
                    schema_id,
                    signature_type=None,
                    tag="consent_schema",
                )
            )
            LOGGER.info(
                "OK consent_schema CREDENTIAL DEFINITION saved on ledger! %s",
                credential_definition_id,
            )

        # NOTE: Create credential OFFER
        (
            credential_exchange_record,
            credential_offer_message,
            service_consent_match_id,
        ) = await create_consent_credential_offer(
            context=context,
            cred_def_id=credential_definition_id,
            connection_id=connection_id,
            consent_schema=consent_schema,
            auto_issue=True,
            auto_remove=False,
        )
    except (LedgerError, IssuerError, BadLedgerRequestError) as err:
        LOGGER.error(
            "credential offer creation error! %s",
            err,
        )
        raise web.HTTPError(reason="Ledger error, credential offer creation error")

    if connection.is_ready:
        await outbound_handler(credential_offer_message, connection_id=connection_id)

        payload_dri = await save_string(context, payload)
        record = ServiceIssueRecord(
            connection_id=connection_id,
            state=ServiceIssueRecord.ISSUE_WAITING_FOR_RESPONSE,
            author=ServiceIssueRecord.AUTHOR_SELF,
            service_id=service_id,
            label=label,
            consent_schema=consent_schema,
            service_schema=service_schema,
            payload_dri=payload_dri,
            credential_definition_id=credential_exchange_record.credential_definition_id,
            service_consent_match_id=service_consent_match_id,
        )

        data_dri = await record.save(context)

        request = Application(
            service_id=record.service_id,
            exchange_id=record.exchange_id,
            credential_definition_id=credential_exchange_record.credential_definition_id,
            data_dri=data_dri,
            service_consent_match_id=service_consent_match_id,
        )
        await outbound_handler(request, connection_id=connection_id)
        return web.json_response(request.serialize())

    raise web.HTTPBadGateway
async def process_application(request: web.BaseRequest):
    outbound_handler = request.app["outbound_message_router"]
    context = request.app["request_context"]
    params = await request.json()

    REJECTED = ServiceIssueRecord.ISSUE_REJECTED
    LEDGER_ERROR = ServiceIssueRecord.ISSUE_SERVICE_LEDGER_ERROR
    ACCEPTED = ServiceIssueRecord.ISSUE_ACCEPTED

    try:
        issue: ServiceIssueRecord = await ServiceIssueRecord.retrieve_by_id(
            context, params["issue_id"]
        )
        service: ServiceRecord = await ServiceRecord.retrieve_by_id(
            context, issue.service_id
        )
    except StorageNotFoundError:
        raise web.HTTPNotFound

    confirmer = StatusConfirmer(
        outbound_handler, issue.connection_id, issue.exchange_id
    )

    #
    # NOTE(KKrzosa): Validate the state of the issue and
    #                check if credential is correct
    # TODO(KKrzosa): inform about invalid credential
    #

    if params["decision"] == "reject" or issue.state == REJECTED:
        issue.state = REJECTED
        await issue.save(context, reason="Issue reject saved")
        await confirmer.send_confirmation(issue.state)
        return web.json_response(issue.serialize())

    service_namespace = service.consent_schema["oca_schema_namespace"]
    service_dri = service.consent_schema["oca_schema_dri"]
    service_data_dri = service.consent_schema["data_dri"]

    credentials: BaseRecord = await THCFCredential.query(context)

    # TODO: Optimize
    found_credential = None
    for cred in credentials:
        if (
            cred.credentialSubject["data_dri"] == service_data_dri
            and cred.credentialSubject["oca_schema_namespace"] == service_namespace
            and cred.credentialSubject["oca_schema_dri"] == service_dri
            and cred.credentialSubject["service_consent_match_id"]
            == issue.service_consent_match_id
        ):
            found_credential = cred
            break

    if found_credential == None:
        raise web.HTTPNotFound(reason="Credential for consent not found")

    #
    # NOTE(KKrzosa): Create a schema and credential def but only if they dont exist
    #                 and based on those issue a credential
    #

    service_manager: ServiceManager = await create_service_manager(context, service)

    try:
        await service_manager.create_schema()
        await service_manager.create_credential_definition()
        (
            credential_exchange_record,
            credential_offer_message,
        ) = await service_manager.create_credential_offer(
            connection_id=issue.connection_id,
            preview_spec={
                "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/issue-credential/1.0/credential-preview",
                "attributes": [
                    {
                        "name": "oca_schema_dri",
                        "mime-type": "application/json",
                        "value": service.service_schema["oca_schema_dri"],
                    },
                    {
                        "name": "data_dri",
                        "mime-type": "application/json",
                        "value": issue.payload_dri,
                    },
                    {
                        "name": "oca_schema_namespace",
                        "mime-type": "application/json",
                        "value": service.service_schema["oca_schema_namespace"],
                    },
                    {
                        "name": "service_consent_match_id",
                        "mime-type": "application/json",
                        "value": issue.service_consent_match_id,
                    },
                ],
            },
            auto_issue=True,
            auto_remove=False,
        )
    except (LedgerError, IssuerError, BadLedgerRequestError) as err:
        LOGGER.error(
            "credential offer creation error! %s",
            err,
        )
        issue.state = LEDGER_ERROR
        raise web.HTTPError(reason="Ledger error, credential offer creation error")

    issue.state = ACCEPTED
    await issue.save(context, reason="Accepted service issue, credential offer created")

    await confirmer.send_confirmation(issue.state)
    await outbound_handler(credential_offer_message, connection_id=issue.connection_id)
    return web.json_response(
        {
            "issue": issue.serialize(),
            "credential_exchange_record": credential_exchange_record.serialize(),
        }
    )