Exemple #1
0
def get_active_farms_by_id_list(
        db: Session = Depends(get_db),
        farm_id: List[int] = Query(None),
        farm_access: FarmAccess = Depends(get_farm_access),
):
    # Load all farms if the user can access all farms.
    if farm_id is None and farm_access.all_farms:
        farms = crud.farm.get_multi(db, active=True)
        return farms

    # Load all the farms the user has access to if none are provided.
    if farm_id is None and farm_access.farm_id_list is not None:
        farms = crud.farm.get_by_multi_id(
            db, farm_id_list=farm_access.farm_id_list, active=True)
        return farms

    # Load the requested farm(s) if the user has access.
    if farm_id is not None:
        for id in farm_id:
            if not farm_access.can_access_farm(id):
                raise unauthorized_exception

        farms_by_id = crud.farm.get_by_multi_id(db,
                                                farm_id_list=farm_id,
                                                active=True)

        if len(farms_by_id) > 0:
            return farms_by_id
        else:
            raise farm_not_found_exception
Exemple #2
0
def get_farm_access_allow_public(
        user_access: dict = Depends(get_current_user_farm_access),
        api_token_access: dict = Depends(get_api_token_farm_access),
):
    farm_access = None

    # If open registration is enabled, allow minimal access.
    if settings.AGGREGATOR_OPEN_FARM_REGISTRATION is True:
        farm_access = FarmAccess(scopes=[], farm_id_list=[], all_farms=False)

    # Still check for a request with higher permissions.
    # This is the same as the get_farm_access dependency above.
    if user_access is not None:
        logger.debug(f"Request has user_access: {user_access}")
        farm_access = user_access

    if api_token_access is not None:
        logger.debug(f"Request has api_token access: {api_token_access}")
        farm_access = api_token_access

    if farm_access is None:
        logger.debug(f"Request has no farm access.")
        raise HTTPException(status_code=HTTP_401_UNAUTHORIZED,
                            detail="Could not validate credentials")

    return farm_access
Exemple #3
0
def get_api_token_farm_access(
        security_scopes: SecurityScopes,
        settings=Depends(get_settings),
        api_token: str = Security(api_token_header),
):
    # Right now, api-tokens are only used for Invite Farm Registration (if enabled)
    # Don't authorize requests with valid api-tokens if this setting is not enabled.
    if settings.AGGREGATOR_INVITE_FARM_REGISTRATION and api_token is not None:
        try:
            token_data = _validate_token(api_token)
        except (PyJWTError, ValidationError) as e:
            raise HTTPException(
                status_code=HTTP_401_UNAUTHORIZED,
                detail="Could not validate credentials",
            )

        for scope in security_scopes.scopes:
            if scope not in token_data.scopes:
                raise HTTPException(status_code=HTTP_401_UNAUTHORIZED,
                                    detail="Not enough permissions.")

        return FarmAccess(scopes=token_data.scopes,
                          farm_id_list=token_data.farm_id,
                          all_farms=False)

    return None
Exemple #4
0
def get_farm_by_id(farm_id: int,
                   db: Session = Depends(get_db),
                   farm_access: FarmAccess = Depends(get_farm_access)):
    if not farm_access.can_access_farm(farm_id):
        raise unauthorized_exception

    farm = crud.farm.get_by_id(db, farm_id=farm_id)

    if not farm:
        raise farm_not_found_exception

    return farm
Exemple #5
0
def get_active_farm_by_url(db: Session = Depends(get_db),
                           farm_url: str = Query(None),
                           farm_access: FarmAccess = Depends(get_farm_access)):
    farm = None
    if farm_url is not None:
        farm = crud.farm.get_by_url(db, farm_url=farm_url, active=True)

        if farm is None:
            raise farm_not_found_exception

        if not farm_access.can_access_farm(farm.id):
            raise unauthorized_exception

    return farm
Exemple #6
0
def get_current_user_farm_access(security_scopes: SecurityScopes,
                                 db: Session = Depends(get_db),
                                 token: str = Security(optional_oauth2)):
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = f"Bearer"

    credentials_exception = HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )

    if token is None:
        # Make this an optional dependency. Don't raise an error if no user is logged in.
        return None
    else:
        try:
            token_data = _validate_token(token)
        except (PyJWTError, ValidationError) as e:
            raise credentials_exception

        user = crud.user.get(db, user_id=token_data.user_id)
        if user is None:
            raise credentials_exception

        for scope in security_scopes.scopes:
            if scope not in token_data.scopes:
                raise HTTPException(status_code=HTTP_401_UNAUTHORIZED,
                                    detail="Not enough permissions.")

        all_farms = False
        if crud.user.is_superuser(user):
            all_farms = True

        return FarmAccess(scopes=token_data.scopes,
                          user_id=token_data.user_id,
                          all_farms=all_farms)
Exemple #7
0
def get_api_key_farm_access(
        security_scopes: SecurityScopes,
        db: Session = Depends(get_db),
        api_key: str = Security(api_key_header),
):
    if api_key is None:
        return None
    else:
        try:
            token_data = _validate_token(api_key)
        except (PyJWTError, ValidationError) as e:
            raise HTTPException(
                status_code=HTTP_401_UNAUTHORIZED,
                detail="Could not validate api key.",
            )

        for scope in security_scopes.scopes:
            if scope not in token_data.scopes:
                raise HTTPException(
                    status_code=HTTP_401_UNAUTHORIZED,
                    detail="Not enough permissions.",
                )

        key_in_db = crud.api_key.get_by_key(db, key=api_key.encode())

        if key_in_db is None:
            raise HTTPException(
                status_code=HTTP_401_UNAUTHORIZED,
                detail="API Key doesn't exist.",
            )

        if not key_in_db.enabled:
            raise HTTPException(status_code=HTTP_401_UNAUTHORIZED,
                                detail="API Key is not enabled.")

        return FarmAccess(scopes=token_data.scopes,
                          farm_id_list=token_data.farm_id,
                          all_farms=token_data.all_farms)
Exemple #8
0
def get_api_token_farm_access(
        security_scopes: SecurityScopes,
        api_token: str = Security(api_key_header),
):
    if api_token is None:
        return None
    else:
        try:
            token_data = _validate_token(api_token)
        except (PyJWTError, ValidationError) as e:
            raise HTTPException(
                status_code=HTTP_401_UNAUTHORIZED,
                detail="Could not validate credentials",
            )

        for scope in security_scopes.scopes:
            if scope not in token_data.scopes:
                raise HTTPException(status_code=HTTP_401_UNAUTHORIZED,
                                    detail="Not enough permissions.")

        return FarmAccess(scopes=token_data.scopes,
                          farm_id_list=token_data.farm_id,
                          all_farms=False)