Example #1
0
def patch_project(
        project: dict,
        name: str,
        patch_mode: schemas.PatchMode = fastapi.Header(
            schemas.PatchMode.replace, alias=schemas.HeaderNames.patch_mode),
        projects_role: typing.Optional[schemas.ProjectsRole] = fastapi.Header(
            None, alias=schemas.HeaderNames.projects_role),
        # TODO: we're in a http request context here, therefore it doesn't make sense that by default it will hold the
        #  request until the process will be completed - after UI supports waiting - change default to False
        wait_for_completion: bool = fastapi.Query(True,
                                                  alias="wait-for-completion"),
        iguazio_session: typing.Optional[str] = fastapi.Cookie(
            None, alias="session"),
        db_session: Session = fastapi.Depends(deps.get_db_session),
):
    project, is_running_in_background = get_project_member().patch_project(
        db_session,
        name,
        project,
        patch_mode,
        projects_role,
        iguazio_session,
        wait_for_completion=wait_for_completion,
    )
    if is_running_in_background:
        return fastapi.Response(status_code=HTTPStatus.ACCEPTED.value)
    return project
Example #2
0
def delete_project(
        name: str,
        deletion_strategy: schemas.DeletionStrategy = fastapi.Header(
            schemas.DeletionStrategy.default(),
            alias=schemas.HeaderNames.deletion_strategy),
        projects_role: typing.Optional[schemas.ProjectsRole] = fastapi.Header(
            None, alias=schemas.HeaderNames.projects_role),
        # TODO: we're in a http request context here, therefore it doesn't make sense that by default it will hold the
        #  request until the process will be completed - after UI supports waiting - change default to False
        wait_for_completion: bool = fastapi.Query(True,
                                                  alias="wait-for-completion"),
        auth_verifier: deps.AuthVerifier = fastapi.Depends(deps.AuthVerifier),
        db_session: Session = fastapi.Depends(deps.get_db_session),
):
    is_running_in_background = get_project_member().delete_project(
        db_session,
        name,
        deletion_strategy,
        projects_role,
        auth_verifier.auth_info.session,
        wait_for_completion=wait_for_completion,
    )
    if is_running_in_background:
        return fastapi.Response(status_code=HTTPStatus.ACCEPTED.value)
    return fastapi.Response(status_code=HTTPStatus.NO_CONTENT.value)
Example #3
0
def patch_project(
    project: dict,
    name: str,
    patch_mode: mlrun.api.schemas.PatchMode = fastapi.Header(
        mlrun.api.schemas.PatchMode.replace,
        alias=mlrun.api.schemas.HeaderNames.patch_mode,
    ),
    # TODO: we're in a http request context here, therefore it doesn't make sense that by default it will hold the
    #  request until the process will be completed - after UI supports waiting - change default to False
    wait_for_completion: bool = fastapi.Query(True,
                                              alias="wait-for-completion"),
    auth_verifier: mlrun.api.api.deps.AuthVerifierDep = fastapi.Depends(
        mlrun.api.api.deps.AuthVerifierDep),
    db_session: sqlalchemy.orm.Session = fastapi.Depends(
        mlrun.api.api.deps.get_db_session),
):
    project, is_running_in_background = get_project_member().patch_project(
        db_session,
        name,
        project,
        patch_mode,
        auth_verifier.auth_info.projects_role,
        auth_verifier.auth_info.session,
        wait_for_completion=wait_for_completion,
    )
    if is_running_in_background:
        return fastapi.Response(status_code=http.HTTPStatus.ACCEPTED.value)
    return project
Example #4
0
async def read_item(user_name: str, user_agent: str = fastapi.Header(None)):
    my_list = ["justin", "walter", "bryan"]
    print(my_list)
    print(user_name)
    if user_name in my_list:
        return {"user_name": user_name, "user_agent": user_agent}
    raise fastapi.HTTPException(status_code=404, detail="Invalid user name")
Example #5
0
def verify_webhook_origin_twitter(
    config,
    request: fastapi.Request,
    x_twitter_webhooks_signature: typing.Optional[str] = fastapi.Header(None),
) -> None:
    """Verify the origin of a request is Twitter based.

    Twitter will send a header `x-twitter-webhooks-signature` which contains
    the HMAC SHA256 hash of the resource payload signed using our
    `CONSUMER_SECRET`. This dependency will raise a `400 BAD REQUEST`
    exception if it does not find that header."""

    if "=" not in x_twitter_webhooks_signature:
        raise fastapi.HTTPException(
            status_code=fastapi.status.HTTP_400_BAD_REQUEST,
            message="Twitter signature did not match",
        )

    # get the digests from the request
    expected_digest = hmac.new(
        config.twitter_auth.CONSUMER_KEY_SECRET.encode("utf8"),
        msg=request.body(),
        digestmod=hashlib.sha256,
    ).digest()
    actual_digest = base64.b64decode(
        x_twitter_webhooks_signature.split("=", 1)[-1].encode("utf8"))

    # compare the digests to check they match
    digests_match = hmac.compare_digest(expected_digest, actual_digest)

    if not digests_match:
        raise fastapi.HTTPException(
            status_code=fastapi.status.HTTP_400_BAD_REQUEST,
            detail="Twitter signature did not match",
        )
Example #6
0
async def recorded_video(video_id: str, range: str = fastapi.Header(None)):
    log.info(f"Recorded video requested : '{video_id}'")

    video_path = pintu.config.recordings_dir / video_id
    if not video_path.is_file():
        log.error(f"No such file: '{video_path}'")
        raise FileNotFoundError(video_id)
    if range:
        start_str, end_str = range.replace("bytes=", "").split("-")
        start = int(start_str)
        end = int(end_str) if end_str else start + CHUNK_SIZE
    else:
        start = 0
        end = video_path.stat().st_size

    with video_path.open("rb") as video:
        video.seek(start)
        data = video.read(end - start)
        filesize = str(video_path.stat().st_size)
        headers = {
            "Content-Range": f"bytes {str(start)}-{str(end)}/{filesize}",
            "Accept-Ranges": "bytes",
        }
        return fastapi.Response(
            data,
            status_code=206,
            headers=headers,
            # media_type="video/mp4",
            media_type="video/webm",
        )
Example #7
0
def delete_project(
    name: str,
    deletion_strategy: mlrun.api.schemas.DeletionStrategy = fastapi.Header(
        mlrun.api.schemas.DeletionStrategy.default(),
        alias=mlrun.api.schemas.HeaderNames.deletion_strategy,
    ),
    # TODO: we're in a http request context here, therefore it doesn't make sense that by default it will hold the
    #  request until the process will be completed - after UI supports waiting - change default to False
    wait_for_completion: bool = fastapi.Query(True,
                                              alias="wait-for-completion"),
    auth_info: mlrun.api.schemas.AuthInfo = fastapi.Depends(
        mlrun.api.api.deps.authenticate_request),
    db_session: sqlalchemy.orm.Session = fastapi.Depends(
        mlrun.api.api.deps.get_db_session),
):
    is_running_in_background = get_project_member().delete_project(
        db_session,
        name,
        deletion_strategy,
        auth_info.projects_role,
        auth_info,
        wait_for_completion=wait_for_completion,
    )
    if is_running_in_background:
        return fastapi.Response(status_code=http.HTTPStatus.ACCEPTED.value)
    return fastapi.Response(status_code=http.HTTPStatus.NO_CONTENT.value)
Example #8
0
def from_authotization_header(
        authorization: str = fastapi.Header(None), ) -> Token:
    """
    Validates an ``Authorization: Bearer`` header and returns a
    :class:`sni.uac.token.Token`. If the token string is invalid, raises a
    ``401``. Should be used as a FastAPI dependency.
    """
    bearer = "Bearer "
    if not authorization or not authorization.startswith(bearer):
        raise fastapi.HTTPException(
            fastapi.status.HTTP_401_UNAUTHORIZED,
            headers={"WWW-Authenticate": "Bearer"},
        )

    try:
        token = get_token_from_jwt(authorization[len(bearer):])
        logging.debug("Successfully validated token %s", token.uuid)
        return token
    except jwt_exceptions.InvalidSignatureError:
        error_msg = "Failed to validate token: invalid signature"
    except jwt_exceptions.ExpiredSignatureError:
        error_msg = "Failed to validate token: expired signature"
    except jwt_exceptions.InvalidAudienceError:
        error_msg = "Failed to validate token: invalid audience"
    except jwt_exceptions.InvalidIssuerError:
        error_msg = "Failed to validate token: invalid issuer"
    except jwt_exceptions.InvalidIssuedAtError:
        error_msg = "Failed to validate token: invalid issuance date"
    except jwt_exceptions.ImmatureSignatureError:
        error_msg = "Failed to validate token: immature signature"
    except jwt_exceptions.InvalidKeyError:
        error_msg = "Failed to validate token: invalid key"
    except jwt_exceptions.InvalidAlgorithmError:
        error_msg = "Failed to validate token: invalid algorithm"
    except jwt_exceptions.MissingRequiredClaimError:
        error_msg = "Failed to validate token: missing claim"
    except jwt_exceptions.DecodeError:
        error_msg = "Failed to validate token: token could not be decoded"
    except jwt_exceptions.InvalidTokenError:
        error_msg = "Failed to validate token: token is invalid"
    except KeyError:
        error_msg = "Failed to validate token: payload is invalid"

    logging.error(error_msg)
    raise fastapi.HTTPException(
        fastapi.status.HTTP_401_UNAUTHORIZED,
        detail=error_msg,
        headers={"WWW-Authenticate": "Bearer"},
    )
Example #9
0
def list_secret_keys(
    project: str,
    provider: schemas.SecretProviderName = schemas.SecretProviderName.vault,
    token: str = fastapi.Header(None, alias=schemas.HeaderNames.secret_store_token),
    auth_verifier: mlrun.api.api.deps.AuthVerifierDep = fastapi.Depends(
        mlrun.api.api.deps.AuthVerifierDep
    ),
):
    mlrun.api.utils.clients.opa.Client().query_project_resource_permissions(
        mlrun.api.schemas.AuthorizationResourceTypes.secret,
        project,
        provider,
        mlrun.api.schemas.AuthorizationAction.read,
        auth_verifier.auth_info,
    )
    return mlrun.api.crud.Secrets().list_secret_keys(project, provider, token)
Example #10
0
def list_secret_keys(
    project: str,
    provider: schemas.SecretProviderName = schemas.SecretProviderName.
    kubernetes,
    token: str = fastapi.Header(None,
                                alias=schemas.HeaderNames.secret_store_token),
    auth_info: mlrun.api.schemas.AuthInfo = fastapi.Depends(
        mlrun.api.api.deps.authenticate_request),
    db_session: Session = fastapi.Depends(mlrun.api.api.deps.get_db_session),
):
    mlrun.api.utils.singletons.project_member.get_project_member().get_project(
        db_session, project, auth_info.session)
    mlrun.api.utils.auth.verifier.AuthVerifier(
    ).query_project_resource_permissions(
        mlrun.api.schemas.AuthorizationResourceTypes.secret,
        project,
        provider,
        mlrun.api.schemas.AuthorizationAction.read,
        auth_info,
    )
    return mlrun.api.crud.Secrets().list_secret_keys(project, provider, token)
Example #11
0
def invitebot(ref: str = "No Referrer",
              dnt: int = fastapi.Header(0),
              perms: int = 0):
    from urllib.parse import quote
    url = "https://discord.com/oauth2/authorize?client_id={}&permissions={}&scope=bot".format(
        619328560141697036, perms)
    url += "&response_type=code&redirect_url=" + quote(
        "https://api.yourapps.cyou/callbacks/authorized")

    async def bg():
        pass  # prevent nameerror

    if dnt == 0:

        async def bg():
            cursor = await app.state.db.execute(
                "SELECT referrals FROM referrers WHERE id=?;", (ref, ))
            count = await cursor.fetchone()
            if not count:
                # This is the first time this source has referred.
                # We need to create a row.
                await app.state.db.execute(
                    """
                    INSERT INTO referrers (id, referrals)
                    VALUES (?, 1);
                    """, (ref, ))
            else:
                # Just need to increment
                await app.state.db.execute(
                    """
                    UPDATE referrers
                    SET referrals=`referrals`+1
                    WHERE id=?;
                    """, (ref, ))
            await app.state.db.commit()

    return fastapi.responses.RedirectResponse(
        url, 308, {"Cache-Control": "max-age=806400"}, BackgroundTask(bg))
Example #12
0
def get_current_user(auth_api_user: dict = fastapi.Depends(get_user_from_auth),
                     account_id: str = fastapi.Header(None)):
    """Parse the provided dict into a User instance."""
    return User(user_id=auth_api_user['keycloakGuid'],
                user_name=auth_api_user['username'],
                account_id=account_id)