예제 #1
0
def swagger(app: Sanic):
    auth_bp, auth_me_bp, auth_verify_bp, auth_refresh_bp, auth_logout = app.jwt.bp.routes

    doc.summary('Авторизация')(auth_bp.handler)
    json_consumes(
        {
            'login': doc.String('Логин'),
            'password': doc.String('Пароль')
        },
        required=True)(auth_bp.handler)
    doc.response(200,
                 {'access_token': doc.String('Access Token')})(auth_bp.handler)

    doc.summary('Получение текущего пользователя')(auth_me_bp.handler)
    doc.security(True)(auth_me_bp.handler)
    doc.response(200, {'me': swagger_models.User})(auth_me_bp.handler)

    doc.summary('Проверка авторизации')(auth_verify_bp.handler)
    doc.response(200, {'valid': doc.Boolean()})(auth_verify_bp.handler)

    doc.summary('Обновление Access Token')(auth_refresh_bp.handler)
    doc.security(True)(auth_refresh_bp.handler)
    form_data_consumes({'refresh_token': doc.String('Refresh Token')},
                       required=True)(auth_refresh_bp.handler)
    doc.response(200, {'access_token': doc.String('Access Token')})(
        auth_refresh_bp.handler)

    doc.summary('Выход')(auth_logout.handler)
    doc.security(True)(auth_logout.handler)
    doc.response(200, {'response': doc.String('success')})(auth_logout.handler)
예제 #2
0
        def response(handler):
            async def handle_request(request):
                # log.info("Accept request: {}".format(request.json))
                return json(asdict(handler(Box(request.json))))

            _, newHandler = post(handle_request)
            doc.summary(summary)
            doc.consumes(doc.JsonBody(to_dict(requestData)),
                         content_type="application/json",
                         location='body')(newHandler)
            doc.produces(to_dict(responseData),
                         content_type="application/json")(newHandler)
            return newHandler
예제 #3
0
    def wrapper(func):
        @wraps(func)
        def wrapped(request, *a, **kw):
            try:
                if consumes:
                    if 'data' in kw:
                        raise OverflowError(
                            f'data kwarg already being passed to {func}')

                    data = validate_data(consumes, request.json)
                    if isinstance(data, sanic.response.HTTPResponse):
                        # Error in validation
                        return data
                    result = func(request, *a, **kw, data=data)
                    return result
                return func(request, *a, **kw)
            except ValidationError as e:
                error = API_ERRORS[type(e)]
                body = {
                    'error': error['message'],
                    'code': error['code'],
                }
                logger.error(e, exc_info=True)

                if e.__cause__:
                    cause = e.__cause__
                    cause = API_ERRORS[type(cause)] if cause else None
                    body['cause'] = {
                        'error': cause['message'],
                        'code': cause['code']
                    }

                r = response.json(body, error['status'])
                return r
            except APIError as e:
                # The endpoint returned a standardized APIError, convert it to a json response
                error = API_ERRORS[type(e)]
                r = response.json(
                    {
                        'message': str(e),
                        'api_error': error['message'],
                        'code': error['code']
                    }, error['status'])
                return r

        # Apply the docs to the wrapped function so sanic-openapi can find the wrapped function when
        # building the schema.  If these docs are applied to `func`, sanic-openapi won't be able to lookup `wrapped`
        if summary:
            wrapped = doc.summary(summary)(wrapped)
        if consumes:
            wrapped = doc.consumes(consumes, location='body')(wrapped)
        if produces:
            wrapped = doc.produces(produces)(wrapped)
        for resp in responses:
            wrapped = doc.response(*resp)(wrapped)
        if tag:
            wrapped = doc.tag(tag)(wrapped)

        return wrapped
예제 #4
0
def add_swagger_doc():
    AuthenticateEndpoint.decorators.extend([
        doc.summary("Authenticate user and get token"),
        doc.consumes(LoginSwDoc, location='body'),
        doc.produces(LoginSwDoc),
    ])

    RetrieveUserEndpoint.decorators.extend([
        doc.summary("Retrieve use logged in"),
        doc.consumes({'AUTHORIZATION': str}, location='header'),
    ])

    VerifyEndpoint.decorators = [
        protected(),
        doc.summary("Verify token"),
        doc.consumes({'Authorization': str}, location='header'),
    ]

    RefreshEndpoint.decorators.extend([
        doc.summary("refresh token"),
        doc.consumes({'Authorization': str}, location='header'),
        doc.consumes({'refresh_token': str}, location='body'),
    ])
예제 #5
0
    def __init__(self, table, slug, related=False):
        self.table = table
        self.slug = slug

        self.related = related

        app.route(slug, methods=["POST"])(self.create)
        doc.summary('Creates a record by name, assigns sequential ID.')(
            self.create)
        doc.consumes({"name": str})

        app.route(os.path.join(slug, '<db_id:int>'), methods=[
            "GET",
        ])(self.read)
        doc.summary('Fetches a single record by ID or all at once')(self.read)
        doc.produces({"result": {"id": int, "name": str}})(self.read)

        app.route(slug, methods=["GET"])(self.read)

        app.route(os.path.join(slug, '<db_id:int>'),
                  methods=["PUT", "PATCH"])(self.update)
        app.route(os.path.join(slug, '<db_id:int>'),
                  methods=["OPTIONS"])(self.preflight)
        doc.summary('Updates a record by ID.')(self.update)
        doc.consumes({
            "name": str,
            "author_id/book_id": int,
            "id": int
        })(self.update)

        app.route(os.path.join(slug, '<db_id:int>'),
                  methods=["DELETE"])(self.delete)
        doc.summary('Deletes a record by ID.')(self.delete)
        doc.produces({"result": "Success"})(self.delete)

        app.route(os.path.join(slug, 'relcount', '<db_id:int>'),
                  methods=["GET"])(self.count_related)
        doc.summary('Counts related authors/books by ID.')(self.count_related)
        doc.produces({"result": int})(self.count_related)

        app.route(os.path.join(slug, 'rellist', '<db_id:int>'),
                  methods=["GET"])(self.list_related)
        doc.summary('Lists related authors/books by ID.')(self.list_related)
        doc.produces({"result": [{"id": int, "name": str}]})
예제 #6
0
    finally:
        await mem_cache.set('agent', ag
                            )  #  in case agent state changes over process_post


@app.post('/api/v0/agent-nym-lookup')
@doc.summary('Lookup agent nym on ledger by DID')
@doc.consumes(openapi_model(agent, 'agent-nym-lookup'), location='body')
@doc.produces(dict)
@doc.tag('{} as Base Agent'.format(profile))
async def process_post_agent_nym_lookup(request):
    return await _process_post(request)


@cond_deco(app.post('/api/v0/agent-nym-send'), offers(agent, 'agent-nym-send'))
@cond_deco(doc.summary('Send agent nym to ledger'),
           offers(agent, 'agent-nym-send'))
@cond_deco(
    doc.consumes(openapi_model(agent, 'agent-nym-send'), location='body'),
    offers(agent, 'agent-nym-send'))
@cond_deco(doc.produces(dict), offers(agent, 'agent-nym-send'))
@cond_deco(
    doc.tag('{} as Trust Anchor{}'.format(
        profile, '' if is_native(agent, 'agent-nym-send') else ' by Proxy')),
    offers(agent, 'agent-nym-send'))
async def process_post_agent_nym_send(request):
    return await _process_post(request)


@app.post('/api/v0/agent-endpoint-lookup')
@doc.summary('Lookup agent endpoint on ledger by DID')