Ejemplo n.º 1
0
async def _get_record_resonse(
    dataframe: pd.DataFrame,
    accept: Optional[str],
) -> Response:
    if accept == "application/x-numpy":
        from numpy.lib.format import write_array

        stream = io.BytesIO()
        write_array(stream, np.array(dataframe.values.tolist()))

        return Response(
            content=stream.getvalue(),
            media_type=accept,
        )
    if accept == "text/csv":
        return Response(
            content=dataframe.to_csv().encode(),
            media_type=accept,
        )
    if accept == "application/x-parquet":
        stream = io.BytesIO()
        dataframe.to_parquet(stream)
        return Response(
            content=stream.getvalue(),
            media_type=accept,
        )
    else:
        if dataframe.values.shape[0] == 1:
            content = dataframe.values[0].tolist()
        else:
            content = dataframe.values.tolist()
        return Response(
            content=json.dumps(content),
            media_type="application/json",
        )
Ejemplo n.º 2
0
def show_detailed(loan_id: int, authorization: str = Header(None)):
    request_cost = 5
    headers = {'x-request-cost': str(request_cost)}
    with LazyItgs() as itgs:
        user_id, _, perms = users.helper.get_permissions_from_header(
            itgs, authorization,
            (helper.DELETED_LOANS_PERM, helper.VIEW_ADMIN_EVENT_AUTHORS_PERM,
             *ratelimit_helper.RATELIMIT_PERMISSIONS))

        if not ratelimit_helper.check_ratelimit(itgs, user_id, perms,
                                                request_cost):
            return Response(status_code=429, headers=headers)

        basic = helper.get_basic_loan_info(itgs, loan_id, perms)
        if basic is None:
            return Response(status_code=404, headers=headers)

        events = helper.get_loan_events(itgs, loan_id, perms)

        etag = helper.calculate_etag(itgs, loan_id)
        headers['etag'] = etag
        headers['Cache-Control'] = 'public, max-age=604800'
        return JSONResponse(status_code=200,
                            content=models.DetailedLoanResponse(
                                events=events, basic=basic).dict(),
                            headers=headers)
Ejemplo n.º 3
0
def ratelimit(authorization: str = Header(None)):
    """This function returns the current state of the logged in users ratelimit.
    Note that the ratelimit status can and will change as requests come in.
    """
    if authorization is None:
        return Response(status_code=401)

    with LazyItgs() as itgs:
        _, user_id = users.helper.check_permissions_from_header(
            itgs, authorization, [])
        if user_id is None:
            return Response(status_code=403)

        user_specific_settings = lbshared.user_settings.get_settings(
            itgs, user_id)

        default_settings = ratelimit_helper.USER_RATELIMITS
        settings = lbshared.ratelimits.Settings(
            collection_name=default_settings.collection_name,
            max_tokens=user_specific_settings.ratelimit_max_tokens
            or default_settings.max_tokens,
            refill_amount=(user_specific_settings.ratelimit_refill_amount
                           or default_settings.refill_amount),
            refill_time_ms=(user_specific_settings.ratelimit_refill_time_ms
                            or default_settings.refill_time_ms),
            strict=(default_settings.strict
                    if user_specific_settings.ratelimit_strict is None else
                    user_specific_settings.ratelimit_strict))
        return _ratelimit_from_key_and_settings(itgs, str(user_id), settings)
Ejemplo n.º 4
0
async def register(response: Response,
                   email: str = Form(...),
                   password: str = Form(...),
                   confirmPassword: str = Form(...),
                   gender: str = Form(...),
                   phoneNo: str = Form(...),
                   firstname: str = Form(...),
                   lastname: str = Form(...)):
    async with AsyncClient() as client:
        data = await client.post(f"{API_WEBSITE_URL}/register",
                                 json={
                                     "firstname": firstname,
                                     "lastname": lastname,
                                     "email": email,
                                     "phoneNo": phoneNo,
                                     "gender": gender,
                                     "confirmPassword": confirmPassword,
                                     "password": password,
                                     "email_verify_url": WEBSITE_URL
                                 })
        if data.status_code == 201:
            response = RedirectResponse("/login", status_code=302)
            response.set_cookie(key="message", value=data.text, max_age=1)
            return response
        response = RedirectResponse("/register", status_code=302)
        response.set_cookie(key="error", value=data.text, max_age=1)
        return response
Ejemplo n.º 5
0
async def get_ensemble_record(
    *,
    res: LibresFacade = Depends(get_res),
    name: str,
    ensemble_id: UUID,
    accept: str = Header("application/json"),
    realization_index: Optional[int] = None,
    label: Optional[str] = None,
) -> Any:
    ensemble_name = get_name("ensemble", ensemble_id)
    dataframe = data_for_key(ensemble_name, name, realization_index)
    if realization_index is not None:
        # dataframe.loc returns a Series, and when we reconstruct a DataFrame from a Series, it defaults to be
        # oriented the wrong way, so we must transpose it
        dataframe = pd.DataFrame(dataframe.loc[realization_index]).T

    if accept == "application/x-parquet":
        dataframe.columns = [str(s) for s in dataframe.columns]
        stream = io.BytesIO()
        dataframe.to_parquet(stream)
        return Response(
            content=stream.getvalue(),
            media_type=accept,
        )
    else:
        return Response(
            content=dataframe.to_csv().encode(),
            media_type="text/csv",
        )
Ejemplo n.º 6
0
def show_user_history_event(req_user_id: int,
                            event_id: int,
                            authorization=Header(None)):
    if authorization is None:
        return Response(status_code=401)

    request_cost = 1
    headers = {'x-request-cost': str(request_cost)}
    with LazyItgs() as itgs:
        user_id, _, perms = helper.get_permissions_from_header(
            itgs, authorization,
            (settings_helper.VIEW_OTHERS_SETTINGS_PERMISSION,
             settings_helper.VIEW_SETTING_CHANGE_AUTHORS_PERMISSION,
             *ratelimit_helper.RATELIMIT_PERMISSIONS))

        if not ratelimit_helper.check_ratelimit(itgs, user_id, perms,
                                                request_cost):
            return Response(status_code=429, headers=headers)

        if user_id is None:
            return Response(status_code=404, headers=headers)

        can_see_others_settings = settings_helper.VIEW_OTHERS_SETTINGS_PERMISSION in perms
        can_see_change_authors = settings_helper.VIEW_SETTING_CHANGE_AUTHORS_PERMISSION in perms

        changer_users = Table('users').as_('changer_users')
        events = Table('user_settings_events')
        query = (Query.from_(events).join(changer_users).on(
            changer_users.id == events.changer_user_id).select(
                events.user_id, events.changer_user_id, changer_users.username,
                events.property_name, events.old_value, events.new_value,
                events.created_at).where(events.id == Parameter('%s')))
        args = [event_id]
        if not can_see_others_settings:
            query = query.where(events.user_id == Parameter('%s'))
            args.append(user_id)

        itgs.read_cursor.execute(query.get_sql(), args)

        row = itgs.read_cursor.fetchone()
        if row is None:
            return Response(status_code=404, headers=headers)

        (event_user_id, event_changer_user_id, event_changer_username,
         event_property_name, event_old_value, event_new_value,
         event_created_at) = row

        event = settings_models.UserSettingsEvent(
            name=event_property_name,
            old_value=json.loads(event_old_value),
            new_value=json.loads(event_new_value),
            username=(event_changer_username if
                      (event_changer_user_id == user_id
                       or can_see_change_authors) else None),
            occurred_at=event_created_at.timestamp())

        headers['Cache-Control'] = 'private, max-age=604800, immutable'
        return JSONResponse(status_code=200,
                            content=event.dict(),
                            headers=headers)
Ejemplo n.º 7
0
def index_permissions(id: int, authorization=Header(None)):
    if authorization is None:
        return Response(status_code=401)

    request_cost = 50
    with LazyItgs() as itgs:
        user_id, _, perms = users.helper.get_permissions_from_header(
            itgs, authorization,
            (helper.VIEW_OTHERS_AUTHENTICATION_METHODS_PERM,
             helper.CAN_VIEW_DELETED_AUTHENTICATION_METHODS_PERM,
             *ratelimit_helper.RATELIMIT_PERMISSIONS))

        if not ratelimit_helper.check_ratelimit(itgs, user_id, perms,
                                                request_cost):
            return Response(status_code=429,
                            headers={'x-request-cost': str(request_cost)})

        if user_id is None:
            return Response(status_code=403,
                            headers={'x-request-cost': str(request_cost)})

        can_view_others_auth_methods = helper.VIEW_OTHERS_AUTHENTICATION_METHODS_PERM in perms
        can_view_deleted_auth_methods = helper.CAN_VIEW_DELETED_AUTHENTICATION_METHODS_PERM in perms

        auth_methods = Table('password_authentications')
        auth_perms = Table('password_auth_permissions')
        permissions = Table('permissions')

        query = (Query.from_(auth_methods).select(
            permissions.name).join(auth_perms).on(
                auth_perms.password_authentication_id == auth_methods.id).join(
                    permissions).on(
                        permissions.id == auth_perms.permission_id).where(
                            auth_methods.deleted.eq(False)).where(
                                auth_methods.id == Parameter('%s')))
        args = [id]

        if not can_view_others_auth_methods:
            query = query.where(auth_methods.user_id == Parameter('%s'))
            args.append(user_id)

        if not can_view_deleted_auth_methods:
            query = query.where(auth_methods.deleted.eq(False))

        itgs.read_cursor.execute(query.get_sql(), args)

        result = []
        row = itgs.read_cursor.fetchone()
        while row is not None:
            result.append(row[0])
            row = itgs.read_cursor.fetchone()

        return JSONResponse(
            status_code=200,
            headers={
                'x-request-cost': str(request_cost),
                'Cache-Control':
                'private, max-age=60, stale-while-revalidate=540'
            },
            content=models.AuthMethodPermissions(granted=result).dict())
Ejemplo n.º 8
0
def token_endpoint(request: Request, response: Response):
    message = json.loads(request.body)
    grant_type = message.get("grant_type")
    if not grant_type or grant_type != "authorization_code":
        response.status_code = status.HTTP_400_BAD_REQUEST
        return response

    session_id = message.get("code")
    if not session_id:
        response.status_code = status.HTTP_400_BAD_REQUEST
        return response

    session = get_object_or_404(AuthSession, id=session_id)

    if not session.presentation_request_satisfied:
        response.status_code = status.HTTP_400_BAD_REQUEST
        return response

    try:
        token = create_id_token(session)
        session.delete()
    except Exception as e:
        LOGGER.warning(f"Error creating token for {session_id}: {e}")
        response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
        return response

    # Add CorsOrigin with cors_allow_any?

    data = {
        "access_token": "invalid",
        "id_token": token,
        "token_type": "Bearer"
    }
    return JSONResponse(data)
Ejemplo n.º 9
0
def document_download(
        document_id: str,
        patient_record: PatientRecord = Depends(_get_patientrecord),
        audit: Auditer = Depends(get_auditer),
):
    """Retreive a specific patient's document file"""
    document: Optional[Document] = patient_record.documents.filter(
        Document.id == document_id).first()
    if not document:
        raise HTTPException(404, detail="Document not found")

    audit.add_event(
        Resource.DOCUMENT,
        document_id,
        RecordOperation.READ,
        parent=audit.add_event(Resource.PATIENT_RECORD, patient_record.pid,
                               RecordOperation.READ),
    )

    media_type: str
    stream: bytes
    filename: str
    if not document.filetype:
        media_type = "text/csv"
        stream = (document.notetext or "").encode()
        filename = f"{document.documentname}.txt"
    else:
        media_type = document.filetype
        stream = document.stream or b""
        filename = document.filename or document.documentname or "NoFileName"

    response = Response(content=stream, media_type=media_type)
    response.headers[
        "Content-Disposition"] = f"attachment; filename={filename}"
    return response
Ejemplo n.º 10
0
def index(authorization=Header(None)):
    request_cost = 25

    with LazyItgs() as itgs:
        user_id, provided, perms = users.helper.get_permissions_from_header(
            itgs, authorization, ratelimit_helper.RATELIMIT_PERMISSIONS)

        if not ratelimit_helper.check_ratelimit(itgs, user_id, perms,
                                                request_cost):
            return Response(status_code=429,
                            headers={'x-request-cost': str(request_cost)})

        if provided and user_id is None:
            return Response(status_code=403,
                            headers={'x-request-cost': str(request_cost)})

        permissions = Table('permissions')
        itgs.read_cursor.execute(
            Query.from_(permissions).select(permissions.name).get_sql(), [])

        result = []
        row = itgs.read_cursor.fetchone()
        while row is not None:
            result.append(row[0])
            row = itgs.read_cursor.fetchone()

        return JSONResponse(
            status_code=200,
            content=models.PermissionsList(permissions=result).dict(),
            headers={
                'x-request-cost':
                str(request_cost),
                'cache-control':
                'public, max-age=604800, stale-while-revalidate=604800'
            })
Ejemplo n.º 11
0
def show(id: int, authorization=Header(None)):
    if authorization is None:
        return Response(status_code=401)

    request_cost = 1
    with LazyItgs() as itgs:
        user_id, _, perms = users.helper.get_permissions_from_header(
            itgs, authorization,
            (helper.VIEW_OTHERS_AUTHENTICATION_METHODS_PERM,
             helper.CAN_VIEW_DELETED_AUTHENTICATION_METHODS_PERM,
             *ratelimit_helper.RATELIMIT_PERMISSIONS))

        if not ratelimit_helper.check_ratelimit(itgs, user_id, perms,
                                                request_cost):
            return Response(status_code=429,
                            headers={'x-request-cost': str(request_cost)})

        if user_id is None:
            return Response(status_code=403,
                            headers={'x-request-cost': str(request_cost)})

        can_view_others_auth_methods = helper.VIEW_OTHERS_AUTHENTICATION_METHODS_PERM in perms
        can_view_deleted_auth_methods = helper.CAN_VIEW_DELETED_AUTHENTICATION_METHODS_PERM in perms

        auth_methods = Table('password_authentications')
        query = (Query.from_(auth_methods).select(
            auth_methods.human,
            auth_methods.deleted).where(auth_methods.id == Parameter('%s')))
        args = [id]

        if not can_view_others_auth_methods:
            query = query.where(auth_methods.user_id == Parameter('%s'))
            args.append(user_id)

        if not can_view_deleted_auth_methods:
            query = query.where(auth_methods.deleted.eq(False))

        itgs.read_cursor.execute(query.get_sql(), args)
        row = itgs.read_cursor.fetchone()
        if row is None:
            return Response(status_code=404,
                            headers={'x-request-cost': str(request_cost)})

        (main, deleted) = row

        authtokens = Table('authtokens')
        itgs.read_cursor.execute(
            Query.from_(authtokens).select(Count(
                Star())).where(authtokens.expires_at < Now()).where(
                    authtokens.source_type == Parameter('%s')).where(
                        authtokens.source_id == Parameter('%s')).get_sql(),
            ('password_authentication', id))
        (active_grants, ) = itgs.read_cursor.fetchone()

        return JSONResponse(status_code=200,
                            content=models.AuthMethod(
                                main=main,
                                deleted=deleted,
                                active_grants=active_grants).dict(),
                            headers={'x-request-cost': str(request_cost)})
Ejemplo n.º 12
0
async def trivia_end(key: str = None):
    if key != web_api_key:
        return Response(status_code=403)

    print("Trivia ended")
    await send_command_to_bot("trivia", ["end"])
    return Response(status_code=204)
Ejemplo n.º 13
0
def me(user_id: int, authorization: str = Header(None)):
    """Get an extremely small amount of information about the user specified
    in the token. This endpoint is expected to be used for the client verifying
    tokens and will indicate so in the cache-control."""
    authtoken = helper.get_authtoken_from_header(authorization)
    if authtoken is None:
        return Response(status_code=403)

    with LazyItgs() as itgs:
        info = helper.get_auth_info_from_token_auth(
            itgs,
            models.TokenAuthentication(token=authtoken),
            require_user_id=user_id)
        if info is None:
            return Response(status_code=403)
        auth_id, authed_user_id, expires_at = info[:3]

        users = Table('users')
        itgs.read_cursor.execute(
            Query.from_(users).select(
                users.username).where(users.id == Parameter('%s')).get_sql(),
            (authed_user_id, ))
        (username, ) = itgs.read_cursor.fetchone()

        return JSONResponse(
            status_code=200,
            content=models.UserShowSelfResponse(username=username).dict(),
            headers={
                'Cache-Control':
                helper.cache_control_for_expires_at(expires_at,
                                                    try_refresh_every=60)
            })
Ejemplo n.º 14
0
async def get_media(path: str, request: Request):
    path = Path('/media').joinpath(path)
    if not path.exists():
        return Response(status_code=HTTPStatus.NOT_FOUND)
    if range_header := request.headers.get('Range'):
        size = path.stat().st_size

        try:
            start, end = range_header.strip('bytes=').split('-')
            start = int(start)
            end = size - 1 if end == '' else int(end)
            chunk_size = end - start + 1
            if chunk_size <= 0:
                raise ValueError
        except ValueError:
            return Response(status_code=HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)

        async with aiofiles.open(path, mode='rb') as file:
            await file.seek(start)
            chunk = await file.read(chunk_size)
            return Response(chunk, status_code=HTTPStatus.PARTIAL_CONTENT, headers={
                'Accept-Ranges': 'bytes',
                'Content-Range': f'bytes {start}-{end}/{size}',
                'Content-Length': str(chunk_size),
            })
Ejemplo n.º 15
0
async def discovery_response(
        version: str,
        xds_type: discovery.DiscoveryTypes,
        discovery_request: DiscoveryRequest = Body(...),
        host: str = Header("no_host_provided"),
) -> Response:
    discovery_request.desired_controlplane = host
    response = await perform_discovery(discovery_request,
                                       version,
                                       xds_type,
                                       skip_auth=False)
    logs.queue_log_fields(
        XDS_RESOURCES=discovery_request.resource_names,
        XDS_ENVOY_VERSION=discovery_request.envoy_version,
        XDS_CLIENT_VERSION=discovery_request.version_info,
        XDS_SERVER_VERSION=response.version,
    )
    headers = response_headers(discovery_request, response, xds_type)

    if response.version == discovery_request.version_info:
        return not_modified(headers)
    elif getattr(response, "resources", None) == []:
        return Response(status_code=404, headers=headers)
    elif response.version != discovery_request.version_info:
        return Response(response.rendered,
                        headers=headers,
                        media_type="application/json")
    return Response(content="Resources could not be determined",
                    status_code=500)
Ejemplo n.º 16
0
async def add_user(
    user: UserIn_Pydantic,
    response: Response,
):
    user = await models.User.create(**user.dict())
    response.set_cookie(settings.USER_COOKIES_NAME, user.id)
    return await User_Pydantic.from_tortoise_orm(user)
Ejemplo n.º 17
0
def test_amqp():
    with LazyItgs() as itgs:
        itgs.channel.queue_declare(queue='hello')

        pub_body = secrets.token_urlsafe(16)
        itgs.channel.basic_publish(exchange='',
                                   routing_key='hello',
                                   body=pub_body.encode('utf-8'),
                                   mandatory=True)
        for mf, props, body_bytes in itgs.channel.consume(
                'hello', inactivity_timeout=1):
            if mf is None:
                itgs.logger.print(Level.WARN,
                                  'test_amqp reached inactivity timeout')
                itgs.channel.cancel()
                return Response(
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
            itgs.channel.basic_ack(mf.delivery_tag)
            con_body = body_bytes.decode('utf-8')
            if con_body != pub_body:
                itgs.logger.print(Level.WARN,
                                  'test_amqp expected response {} but got {}',
                                  pub_body, con_body)
                continue
            itgs.channel.cancel()
            return Response(status_code=status.HTTP_200_OK)
Ejemplo n.º 18
0
def show(permission: str, authorization=Header(None)):
    request_cost = 1

    with LazyItgs() as itgs:
        user_id, provided, perms = users.helper.get_permissions_from_header(
            itgs, authorization, ratelimit_helper.RATELIMIT_PERMISSIONS)

        if not ratelimit_helper.check_ratelimit(itgs, user_id, perms,
                                                request_cost):
            return Response(status_code=429,
                            headers={'x-request-cost': str(request_cost)})

        if provided and user_id is None:
            return Response(status_code=403,
                            headers={'x-request-cost': str(request_cost)})

        permissions = Table('permissions')
        itgs.read_cursor.execute(
            Query.from_(permissions).select(permissions.description).where(
                permissions.name == Parameter('%s')).get_sql(), (permission, ))
        row = itgs.read_cursor.fetchone()
        if row is None:
            return Response(status_code=400,
                            headers={'x-request-cost': str(request_cost)})

        return JSONResponse(
            status_code=200,
            headers={
                'x-request-cost':
                str(request_cost),
                'cache-control':
                'public, max-age=604800, stale-while-revalidate=604800'
            },
            content=models.Permission(description=row[0]).dict())
Ejemplo n.º 19
0
async def set_cookie(response: Response, key, value, expires, path, domain,
                     secure, http_only, same_site):
    response.delete_cookie(key)  # Delete earlier cookies
    if CookieConfig.get_instance().cookie_domain is not None:
        domain = CookieConfig.get_instance().cookie_domain
    if CookieConfig.get_instance().cookie_secure is not None:
        secure = CookieConfig.get_instance().cookie_secure
    if CookieConfig.get_instance().cookie_same_site is not None:
        same_site = CookieConfig.get_instance().cookie_same_site
    handshake_info = await HandshakeInfo.get_instance()
    if path in {
            handshake_info.refresh_token_path, handshake_info.access_token_path
    }:
        if path == handshake_info.access_token_path and CookieConfig.get_instance(
        ).access_token_path is not None:
            path = CookieConfig.get_instance().access_token_path
        elif path == handshake_info.refresh_token_path and CookieConfig.get_instance(
        ).refresh_token_path is not None:
            path = CookieConfig.get_instance().refresh_token_path
    response.set_cookie(key=key,
                        value=quote(value, encoding='utf-8'),
                        expires=((expires - get_timestamp_ms()) // 1000),
                        path=path,
                        domain=domain,
                        secure=secure,
                        httponly=http_only,
                        samesite=same_site)
Ejemplo n.º 20
0
def lookup(q: str, authorization=Header(None)):
    """Allows looking up a user id by a username. q is the username to lookup"""
    request_cost = 1

    headers = {'x-request-cost': str(request_cost)}
    with LazyItgs() as itgs:
        user_id, _, perms = helper.get_permissions_from_header(
            itgs, authorization, ratelimit_helper.RATELIMIT_PERMISSIONS)

        if not ratelimit_helper.check_ratelimit(itgs, user_id, perms,
                                                request_cost):
            return Response(status_code=429, headers=headers)

        users = Table('users')
        itgs.read_cursor.execute(
            Query.from_(users).select(
                users.id).where(users.username == Parameter('%s')).get_sql(),
            (q.lower(), ))
        row = itgs.read_cursor.fetchone()
        if row is None:
            return Response(status_code=404, headers=headers)

        headers['Cache-Control'] = 'public, max-age=604800, immutable'
        return JSONResponse(
            status_code=200,
            content=models.UserLookupResponse(id=row[0]).dict(),
            headers=headers)
Ejemplo n.º 21
0
def logout(response: Response, session_token: str = Cookie(None)):
    if session_token not in app.session_tokens:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
    response.status_code = 302
    response.headers["Location"] = '/'
    app.session_tokens.remove(session_token)
    return response
Ejemplo n.º 22
0
def show(name: str, authorization: str = Header(None)):
    with LazyItgs() as itgs:
        if not users_helper.check_permissions_from_header(
                itgs, authorization, 'responses')[0]:
            return Response(status_code=403)
        responses = Table('responses')
        itgs.read_cursor.execute(
            Query.from_(responses).select(
                responses.id, responses.name, responses.response_body,
                responses.description, responses.created_at,
                responses.updated_at).where(
                    responses.name == Parameter('%s')).get_sql(), (name, ))
        row = itgs.read_cursor.fetchone()
        if row is None:
            return Response(status_code=404)
        return JSONResponse(status_code=200,
                            content=models.ResponseShow(
                                id=row[0],
                                name=row[1],
                                body=row[2],
                                desc=row[3],
                                created_at=int(row[4].timestamp()),
                                updated_at=int(row[5].timestamp())).dict(),
                            headers={
                                'Cache-Control':
                                'public, max-age=86400, stale-if-error=2629746'
                            })
Ejemplo n.º 23
0
def login_page(username: str = Form(...), password: str = Form(...)):

    user = users.get(username)
    if not user or user['password'] != password:
        return Response("Я вас не знаю!", media_type="text/html")
    else:
        return Response(
            f"Привееет, {user['name']}!<br>Баланс: {user['balance']}",
            media_type="text/html")
Ejemplo n.º 24
0
def update_response(name: str,
                    change: models.ResponseEditArgs,
                    authorization: str = Header(None)):
    if len(change.edit_reason) < 5:
        return JSONResponse(status_code=422,
                            content={
                                'detail': {
                                    'loc': ['body', 'edit_reason']
                                },
                                'msg': 'minimum 5 characters',
                                'type': 'too_short'
                            })

    with LazyItgs(no_read_only=True) as itgs:
        authed, user_id = users_helper.check_permissions_from_header(
            itgs, authorization, 'responses')
        if not authed:
            return Response(status_code=403)
        users = Table('users')
        itgs.write_cursor.execute(
            Query.from_(users).select(
                users.id).where(users.id == Parameter('%s')).get_sql() +
            ' FOR SHARE', (user_id, ))
        row = itgs.write_cursor.fetchone()
        if row is None:
            itgs.write_conn.rollback()
            return Response(status_code=403)
        responses = Table('responses')
        itgs.write_cursor.execute(
            Query.from_(responses).select(
                responses.id, responses.response_body,
                responses.description).where(
                    responses.name == Parameter('%s')).get_sql() +
            ' FOR UPDATE', (name, ))
        row = itgs.write_cursor.fetchone()
        if row is None:
            itgs.write_conn.rollback()
            return Response(status_code=404)
        (resp_id, old_body, old_desc) = row
        resp_hists = Table('response_histories')
        itgs.write_cursor.execute(
            Query.into(resp_hists).columns(
                resp_hists.response_id, resp_hists.user_id, resp_hists.old_raw,
                resp_hists.new_raw, resp_hists.reason, resp_hists.old_desc,
                resp_hists.new_desc).insert(
                    *[Parameter('%s') for _ in range(7)]).get_sql(),
            (resp_id, user_id, old_body, change.body, change.edit_reason,
             old_desc, change.desc))
        itgs.write_cursor.execute(
            Query.update(responses).set(
                responses.response_body, Parameter('%s')).set(
                    responses.description, Parameter('%s')).set(
                        responses.updated_at, ppfns.Now()).where(
                            responses.id == Parameter('%s')).get_sql(),
            (change.body, change.desc, resp_id))
        itgs.write_conn.commit()
        return Response(status_code=200)
Ejemplo n.º 25
0
 async def preflight_handler(request: Request, rest_of_path: str) -> Response:
     """
     Handles CORS preflight requests.
     """
     response = Response()
     response.headers["Access-Control-Allow-Origin"] = "*"
     response.headers["Access-Control-Allow-Methods"] = "POST, GET, DELETE, PATCH, OPTIONS"
     response.headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type"
     return response
Ejemplo n.º 26
0
def show_patient(id: int,
                 response: Response,
                 session_token: str = Cookie(None)):
    if session_token not in app.session_tokens:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
    response.set_cookie(key="session_token", value=session_token)
    if id in app.patients.keys():
        return app.patients[id]
    return status.HTTP_204_NO_CONTENT
Ejemplo n.º 27
0
 async def dispatch(self, request: Request,
                    call_next: RequestResponseEndpoint):
     response = Response("Internal server error", status_code=500)
     token = _request_id_ctx_var.set(str(uuid4()))
     try:
         response: Response = await call_next(request)
     finally:
         response.headers['X-Request-ID'] = get_request_id()
         _request_id_ctx_var.reset(token)
     return response
Ejemplo n.º 28
0
async def verify_email(userId: str, response: Response):
    async with AsyncClient() as client:
        data = await client.post(f"{API_WEBSITE_URL}/user/{userId}/activate")
        if data.status_code == 200:
            response = RedirectResponse("/login", status_code=302)
            response.set_cookie(key="message", value=data.text, max_age=1)
            return response
        response = RedirectResponse("/login", status_code=302)
        response.set_cookie(key="error", value=data.text, max_age=1)
        return response
Ejemplo n.º 29
0
def set_auth(response: Response, user_id: int):
    val = serializer.dumps(user_id)
    response.set_cookie(
        AUTH_COOKIE_NAME,
        val,
        secure=False,
        expires=ACCESS_TOKEN_EXPIRE_MINUTES * 60,
        httponly=True,
        samesite="Lax",
    )
Ejemplo n.º 30
0
def add_patient(response: Response,
                patient: Patient,
                session_token: str = Cookie(None)):
    if session_token not in app.session_tokens:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
    id = counter()
    app.patients[id] = patient.dict()
    response.set_cookie(key="session_token", value=session_token)
    response.status_code = 302
    response.headers["Location"] = f'/patient/{id}'