Beispiel #1
0
async def check_login(request: Request, call_next):
    """Cookieからsessionidを取得し、django_sessionテーブルに存在すればログイン済み→素通り
        そうでなければ/admin/loginにリダイレクト
    """
    # ブラウザからアクセスされた時
    if 'Mozilla' in request.headers['user-agent']:
        if 'sessionid' not in request.cookies:
            return RedirectResponse('/admin/login/')

        session_id = request.cookies['sessionid']
        if db.table('django_session').where('session_key', session_id).count() == 0:
            return RedirectResponse('/admin/login/')
    # APIからアクセスされた時
    else:
        if 'sessionid' not in request.cookies:
            response = JSONResponse({})
            response.status_code = 403
            return response

        session_id = request.cookies['sessionid']
        if db.table('django_session').where('session_key', session_id).count() == 0:
            response = JSONResponse({})
            response.status_code = 403
            return response

    response = await call_next(request)
    return response
 async def send_error(self, context: Any, error) -> Dict:
     """Pull a form value from the request."""
     if isinstance(error, (dict, str)):
         res = JSONResponse({"error": error})
     else:
         res = JSONResponse({"error": str(error)})
     res.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
     return res
Beispiel #3
0
    async def telegram_logout_view(self, token: str = Cookie(None)):
        current_user = self.service.authenticate(token)

        is_user_logout = await self.service.telegram_logout(
            username=current_user['username'])

        if is_user_logout:
            message = 'User successfully logout'
            response = JSONResponse(content=message)
            response.status_code = 200

            return response

        message = 'User logout fail'
        response = JSONResponse(content=message)
        response.status_code = 418

        return response
Beispiel #4
0
async def http_error_handler(request: Request,
                             exc: HTTPException) -> JSONResponse:
    body = {"errors": [exc.detail]}

    response = JSONResponse(body)
    response.status_code = exc.status_code

    logging.error(body)

    return response
    async def send_response(self, context: Request, data) -> Dict:
        """Pull a form value from the request."""
        print("context.method", context.method)
        if isinstance(data, Response):
            return data

        status_code = 201 if context.method in ("POST") else 200
        if isinstance(data, tuple) and len(data) > 1:
            status_code = data[1]
            data = data[0]

        if isinstance(data, dict):
            resp = JSONResponse(data)
        else:
            resp = JSONResponse({"data": data})
        resp.status_code = status_code
        return resp
Beispiel #6
0
    async def telegram_authorize_view(self,
                                      user: TelegramAuthorizeUserModel,
                                      token: str = Cookie(None)):
        try:
            current_user = self.service.authenticate(token)

            user = await self.service.telegram_authorize_user(
                username=current_user['username'],
                phone_number=user.phone_number,
                password=user.password,
                code=user.code)

            return user
        except BaseException as error:
            message = str(error)
            response = JSONResponse(content=message)
            response.status_code = 449

            return response
Beispiel #7
0
    async def dispatch_func(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
        yfa.locals.init_request(request=request)
        r = {
            "data": None,
            "status": "OK",
            "errors": None
        }
        status_code = 200
        response = None
        try:
            if "Authorization" in request.headers:
                yfa.locals.current_user = decode_token(request.headers.get(
                    "Authorization").split(" ")[1])
            response = await call_next(request)
        except YFAException as e:  # noqa
            r["status"] = "FAILED"
            r["errors"] = [
                e.as_dict()
            ]
            status_code = e.http_status_code
        except Exception as e:
            status_code = 500
            r["status"] = "FAILED"
            r["errors"] = [
                UnknownError(e).as_dict()
            ]

        background_tasks = yfa.locals.background_tasks
        yfa.locals.release_local()

        if isinstance(response, Response):
            response.background = background_tasks
            return response

        r["data"] = response
        response = JSONResponse(r, background=background_tasks)
        response.status_code = status_code
        return response
Beispiel #8
0
def handle_auth_error(request, exc):
    response = JSONResponse(exc.error)
    response.status_code = exc.status_code
    return response
Beispiel #9
0
def handleError(request, error):
    response = JSONResponse(error.toDict())
    response.status_code = error.statusCode
    return response
Beispiel #10
0
async def before_and_after_request(request: Request, call_next) -> Response:
    """Process requests.
    Args:
        request {starlette.requests.Request): input request
        call_next {function}: callback function which invokes request
    Returns:
        starlette.responses.Response
    """
    # pylint: disable=too-many-locals,invalid-name,broad-except

    # check DB schema is valid
    # TODO (Alex): rewrite
    # if config.DB_SCHEMA['status'] == 'fail':
    #     return JSONResponse(config.DB_SCHEMA, HTTPStatus.INTERNAL_SERVER_ERROR)

    try:
        response = await call_next(request)

    except (BadProjectNameError, ProjectAlreadyExistsError) as e:
        return build_error_response(HTTPStatus.BAD_REQUEST, e)

    except (ProjectNotFoundError, RegisteredModelNotFoundError) as e:
        return build_error_response(HTTPStatus.NOT_FOUND, e)

    except ProjectIsAlreadyRunningError as e:
        return build_error_response(HTTPStatus.CONFLICT, e)

    except Exception as e:
        logger.error(e, exc_info=True)
        return build_error_response(HTTPStatus.INTERNAL_SERVER_ERROR, e)

    ip = request.headers.get('X-Forwarded-For', request.client.host)
    host = request.client.host.split(':', 1)[0]
    query_params = dict(request.query_params)

    log_params = [
        ('method', request.method),
        ('path', request.url.path),
        ('status', response.status_code),
        ('ip', ip),
        ('host', host),
        ('params', query_params)
    ]

    line = json.dumps(dict(log_params))
    logger.debug(line)
    final_response = response

    if response.headers.get('content-type') == 'application/json':

        body = [b async for b in response.body_iterator]
        content = response.render(b''.join(body))
        json_content = json.loads(content)

        if isinstance(json_content, list):

            sort_key = query_params.get('_sort')
            order = query_params.get('_order')
            start = int(query_params.get('_start', 0))
            end = int(query_params.get('_end', len(json_content)))

            if sort_key is not None:
                json_content = sorted(json_content,
                                      key=lambda e: e[sort_key],
                                      reverse=(order == 'DESC'))

            json_content = json_content[start:end]
            final_response = JSONResponse(json_content)
            final_response.headers['X-Total-Count'] = str(len(json_content))
            final_response.headers['Access-Control-Expose-Headers'] = 'X-Total-Count'

        else:
            final_response = JSONResponse(json_content)

    final_response.status_code = response.status_code

    return final_response