def on_product_acquisition(self, asset, contract, order):
        # Extract related information from the asset
        #parsed_url = urlparse(asset.download_link)

        try:
            keystone_client = KeystoneClient(KEYSTONE_USER, KEYSTONE_PWD,
                                             ADMIN_DOMAIN, KEYSTONE_PROTOCOL,
                                             KEYSTONE_HOST, KEYSTONE_PORT)

            # Check the customer user
            customer_id = order.owner_organization.name  #self._get_user_id(keystone_client, asset.meta_info['domain_id'], order.owner_organization.name)

            role_id = keystone_client.get_role_by_name(
                asset.meta_info['application_id'], asset.meta_info['role'])
            if role_id:
                # Give the user the new role
                keystone_client.grant_role(asset.meta_info['application_id'],
                                           customer_id, role_id)
            else:
                raise PluginError(
                    'It has not been possible to use this role: ' +
                    asset.meta_info['role'] + ' with Keystone')

        except HTTPError as e:
            if e.response.status_code == 409:
                raise ConflictError('You already own the offered role')
            else:
                raise PluginError(
                    'It has not been possible to connect with Keystone')
    def _validate_product(self, provider, asset_t, media_type, url):

        asset_type, assets = self._get_asset_resouces(asset_t, url)

        if len(assets):
            # The asset is already registered
            asset = assets[0]

            if asset.product_id is not None:
                raise ConflictError(
                    'There is already an existing product specification defined for the given digital asset'
                )

            self._validate_product_characteristics(asset, provider, asset_t,
                                                   media_type)

            asset.has_terms = self._has_terms
            asset.save()
        else:
            # The asset is not yet included, this option is only valid for URL assets without metadata
            site = settings.SITE
            if 'FILE' in asset_type.formats and (
                ('URL' not in asset_type.formats) or
                ('URL' in asset_type.formats and url.startswith(site))):

                raise ProductError(
                    'The URL specified in the location characteristic does not point to a valid digital asset'
                )

            if asset_type.form:
                raise ProductError(
                    'Automatic creation of digital assets with expected metadata is not supported'
                )

            # Validate media type
            if len(asset_type.media_types) and media_type.lower() not in [
                    media.lower() for media in asset_type.media_types
            ]:
                raise ProductError(
                    'The media type characteristic included in the product specification is not valid for the given asset type'
                )

            # Create the new asset model
            asset = Resource.objects.create(has_terms=self._has_terms,
                                            resource_path='',
                                            download_link=url,
                                            provider=provider,
                                            content_type=media_type)

        # The asset model is included to the rollback list so if an exception is raised in the plugin post validation
        # the asset model would be deleted
        self.rollback_logger['models'].append(asset)

        return asset
Exemple #3
0
    def _check_url_conflict(self, data, current_organization):
        # Check that the download link is not already being used
        existing_assets = Resource.objects.filter(download_link=data['content'], provider=current_organization)
        is_conflict = False
        for asset in existing_assets:
            if asset.product_id is not None:
                is_conflict = True
            else:
                asset.delete()

        if is_conflict:
            raise ConflictError('The provided digital asset already exists')
    def on_product_acquisition(self, asset, contract, order):
        # Extract related information from the asset
        #parsed_url = urlparse(asset.download_link)

        try:
            keystone_client = KeystoneClient(KEYSTONE_USER, KEYSTONE_PWD, ADMIN_DOMAIN, 'http', 'idm.docker')

            
            # Check the customer user
            customer_id = self._get_user_id(keystone_client, asset.meta_info['domain_id'], 'mario')

            role_id = keystone_client.get_role_id_by_name(asset.meta_info['application_id'], asset.meta_info['role'])
            if role_id:
                # Give the user the new role
                keystone_client.grant_role(asset.meta_info['application_id'], customer_id, role_id)
            else:
                raise PluginError('It has not been possible to use this role: ' + asset.meta_info['role'] + ' with Keystone')

        except HTTPError as e:
            if e.response.status_code == 409:
                raise ConflictError('You already own the offered role')
            else:
                raise PluginError('It has not been possible to connect with Keystone')

        
        
        
        # # If the model is usage, send usage notification
        # if 'pay_per_use' in contract.pricing_model:
        #     self._notify_accounting(asset, order, contract, 'add')

    #def on_product_suspension(self, asset, contract, order):
        # parsed_url = urlparse(asset.download_link)

        # try:
        #     keystone_client = KeystoneClient(KEYSTONE_USER, KEYSTONE_PWD, ADMIN_DOMAIN, parsed_url.scheme, parsed_url.hostname)

        #     # Check the customer user
        #     customer_id = self._get_user_id(keystone_client, asset.meta_info['domain_id'], order.owner_organization.name)

        #     # Remove the role from the user
        #     keystone_client.revoke_role(asset.meta_info['project_id'], customer_id, asset.meta_info['role_id'])

        # except HTTPError:
        #     raise PluginError('It has not been possible to connect with Keystone')

        # # If the model is usage, send usage notification
        # if 'pay_per_use' in contract.pricing_model:
        #     self._notify_accounting(asset, order, contract, 'remove')
Exemple #5
0
    def _save_resource_file(self, provider, file_):
        # Load file contents
        if isinstance(file_, dict):
            file_name = file_['name']
            content = base64.b64decode(file_['data'])
        else:
            file_name = file_.name
            file_.seek(0)
            content = file_.read()

        # Check file name
        if not is_valid_file(file_name):
            raise ValueError('Invalid file name format: Unsupported character')

        # Create provider dir for assets if it does not exists
        provider_dir = os.path.join(settings.MEDIA_ROOT, 'assets', provider)

        if not os.path.isdir(provider_dir):
            os.mkdir(provider_dir)

        file_path = os.path.join(provider_dir, file_name)
        resource_path = file_path[file_path.index(settings.MEDIA_DIR):]

        if resource_path.startswith('/'):
            resource_path = resource_path[1:]

        # Check if the file already exists
        if os.path.exists(file_path):
            res = Resource.objects.get(resource_path=resource_path)
            if res.product_id is not None:
                # If the resource has product_id field, it means that a product
                # spec has been created, so it cannot be overridden
                raise ConflictError('The provided digital asset file (' +
                                    file_name + ') already exists')
            res.delete()

        # Create file
        with open(file_path, "wb") as f:
            f.write(content)

        self.rollback_logger['files'].append(file_path)

        site = settings.SITE
        return resource_path, url_fix(
            urljoin(site, '/charging/' + resource_path))
def register_on_market(user, name, host, api_version, credentials, site):

    if host[-1] != '/':
        host += '/'

    # Check if the marketplace already exists
    if len(
            Marketplace.objects.filter(name=name)
            | Marketplace.objects.filter(host=host)) > 0:
        raise ConflictError('Marketplace already registered')

    store_name = settings.STORE_NAME

    username = None
    passwd = None

    if credentials:
        username = credentials['username']
        passwd = credentials['passwd']

    cred = MarketCredentials(username=username, passwd=passwd)

    marketplace = Marketplace(name=name,
                              host=host,
                              api_version=api_version,
                              credentials=cred)

    marketadaptor = marketadaptor_factory(marketplace, user)

    store_info = {
        'store_name': store_name,
        'store_uri': site,
    }

    store_id = marketadaptor.add_store(store_info)

    try:
        marketplace.store_id = store_id
        marketplace.save()
    except Exception as e:
        # If the marketplace model creation fails it is necesary to unregister the store
        # in order to avoid an inconsistent state
        marketadaptor.delete_store()
        raise e
def _validate_resource_info(provider, data, file_=None):

    # Check if the resource already exists
    existing = True
    current_organization = provider.userprofile.current_organization
    try:
        Resource.objects.get(name=data['name'], provider=current_organization)
    except:
        existing = False

    if existing:
        raise ConflictError(
            'The resource ' + data['name'] +
            ' already exists. Please upgrade the resource if you want to provide new content'
        )

    # Check contents
    if 'name' not in data or 'version' not in data or\
            'description' not in data or 'content_type' not in data or\
            'resource_type' not in data:
        raise ValueError('Invalid request: Missing required field')

    # Create version object to validate resource version format
    Version(data['version'])

    # Check name format
    if not is_valid_id(data['name']):
        raise ValueError('Invalid name format')

    return ({
        'name': data['name'],
        'version': data['version'],
        'description': data['description'],
        'content_type': data['content_type'],
        'resource_type': data['resource_type'],
        'open': data.get('open', False)
    }, current_organization)
 def _prod_val_conflict(self):
     self.validator_instance.validate.side_effect = ConflictError('Conflict')
 def side(ref):
     method.side_effect = ConflictError('Resource exists')
Exemple #10
0
 def _existing(self):
     views.register_resource.side_effect = ConflictError('Resource exists')
Exemple #11
0
 def _existing(self):
     self.am_instance.upload_asset.side_effect = ConflictError(
         'Resource exists')
Exemple #12
0
 def _existing(self):
     views.register_on_market.side_effect = ConflictError('Existing Marketplace')