Exemple #1
0
    def refresh(self, id):
        try:
            context = {'model': model, 'user': c.user, 'session': model.Session}
            p.toolkit.get_action('harvest_job_create')(
                context, {'source_id': id, 'run': True}
            )
            h.flash_success(
                _('Harvest will start shortly. Refresh this page for updates.')
            )
        except p.toolkit.ObjectNotFound:
            abort(404, _('Harvest source not found'))
        except p.toolkit.NotAuthorized:
            abort(401, self.not_auth_message)
        except HarvestSourceInactiveError:
            h.flash_error(
                _(
                    'Cannot create new harvest jobs on inactive '
                    'sources. First, please change the source status '
                    'to "active".'
                )
            )
        except HarvestJobExists:
            h.flash_notice(
                _('A harvest job has already been scheduled for ' 'this source')
            )
        except Exception as e:
            msg = 'An error occurred: [%s]' % str(e)
            h.flash_error(msg)

        h.redirect_to(h.url_for('{0}_admin'.format(DATASET_TYPE_NAME), id=id))
Exemple #2
0
    def member_delete(self, id):
        if 'cancel' in request.params:
            self._redirect_to(controller='group', action='members', id=id)

        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author
        }

        try:
            self._check_access('group_member_delete', context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete group %s members') % '')

        try:
            user_id = request.params.get('user')
            if request.method == 'POST':
                self._action('group_member_delete')(context, {
                    'id': id,
                    'user_id': user_id
                })
                h.flash_notice(_('Group member has been deleted.'))
                self._redirect_to(controller='group', action='members', id=id)
            c.user_dict = self._action('user_show')(context, {'id': user_id})
            c.user_id = user_id
            c.group_id = id
        except NotAuthorized:
            abort(401, _('Unauthorized to delete group %s') % '')
        except NotFound:
            abort(404, _('Group not found'))
        return self._render_template('group/confirm_delete_member.html')
Exemple #3
0
    def delete(self, id, related_id):

        if 'cancel' in base.request.params:
            h.redirect_to(controller='related', action='edit',
                          id=id, related_id=related_id)

        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author}

        try:
            logic.check_access('related_delete', context, {'id': id})
        except logic.NotAuthorized:
            base.abort(401, _('Unauthorized to delete package %s') % '')

        try:
            if base.request.method == 'POST':
                logic.get_action('related_delete')(context, {'id': related_id})
                h.flash_notice(_('Related item has been deleted.'))
                h.redirect_to(controller='package', action='read', id=id)
            c.related_dict = logic.get_action('related_show')(context, {'id': related_id})
            c.pkg_id = id
        except logic.NotAuthorized:
            base.abort(401, _('Unauthorized to delete related item %s') % '')
        except logic.NotFound:
            base.abort(404, _('Related item not found'))
        return base.render('related/confirm_delete.html')
Exemple #4
0
def remove_disabled_languages(key, data, errors, context):
    '''
    If `langdis == 'True'`, remove all languages.

    Expecting language codes in `data['key']`.

    :param key: key
    :param data: data
    :param errors: validation errors
    :param context: context
    '''
    langdis = data.get(('langdis', ))

    langs = data.get(key).split(',')

    if langdis == 'False':
        # Language enabled

        if langs == [u'']:
            errors[key].append(_('No language given'))
    else:
        # Language disabled

        # Display flash message if user is loading a page.
        if 'session' in globals():
            h.flash_notice(
                _("Language is disabled, removing languages: '%s'" %
                  data[key]))

        # Remove languages.
        del data[key]
        data[key] = u''
Exemple #5
0
def delete_view(id):
    if 'cancel' in tk.request.params:
        tk.redirect_to('showcase_blueprint.edit' if tk.check_ckan_version(
            min_version='2.9.0') else 'showcase_edit',
                       id=id)

    context = {
        'model': model,
        'session': model.Session,
        'user': c.user or c.author,
        'auth_user_obj': c.userobj
    }

    try:
        tk.check_access('ckanext_showcase_delete', context, {'id': id})
    except tk.NotAuthorized:
        return tk.abort(401, _('Unauthorized to delete showcase'))

    if tk.check_ckan_version(min_version='2.9.0'):
        index_route = 'showcase_blueprint.index'
    else:
        index_route = 'showcase_index'

    try:
        if tk.request.method == 'POST':
            tk.get_action('ckanext_showcase_delete')(context, {'id': id})
            h.flash_notice(_('Showcase has been deleted.'))
            return tk.redirect_to(index_route)
        c.pkg_dict = tk.get_action('package_show')(context, {'id': id})
    except tk.NotAuthorized:
        tk.abort(401, _('Unauthorized to delete showcase'))
    except tk.ObjectNotFound:
        tk.abort(404, _('Showcase not found'))
    return tk.render('showcase/confirm_delete.html',
                     extra_vars={'dataset_type': DATASET_TYPE_NAME})
    def member_delete(self, id):
        ''' This is a modified version of the member_delete from the 
            ckan group controller. 
            The changes are: ( if you modify this function please add below)
            - flash msg changed to reflect it's an org member ( not group member )
            - the delete confirmation is done with js ( DHTML )
        '''
        if 'cancel' in request.params:
            self._redirect_to(controller='group', action='members', id=id)

        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author}

        try:
            self._check_access('group_member_delete', context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete group %s members') % '')

        try:
            user_id = request.params.get('user')
            if request.method == 'POST':
                self._action('group_member_delete')(
                    context, {'id': id, 'user_id': user_id})
                # modified by HDX
                h.flash_notice(_('Organization member has been deleted.'))
                self._redirect_to(controller='group', action='members', id=id)
            c.user_dict = self._action('user_show')(context, {'id': user_id})
            c.user_id = user_id
            c.group_id = id
        except NotAuthorized:
            abort(401, _('Unauthorized to delete group %s') % '')
        except NotFound:
            abort(404, _('Group not found'))
        # modified by HDX
        self._redirect_to(controller='group', action='members', id=id)
def update_publication_package(id):
    """Update the metadata for a dataset by the admin through the datacite API.
    """
    context = _get_context()

    log.debug("controller: update_publication_package: {0}".format(id))

    try:
        result = toolkit.get_action('datacite_update_publication_package')(
            context, {
                'id': id
            })
    except toolkit.ObjectNotFound:
        toolkit.abort(404, 'Dataset not found')
    except toolkit.NotAuthorized:
        toolkit.abort(403, 'Not authorized')
    except toolkit.ValidationError:
        toolkit.abort(400, 'Validation error')

    if result.get('success', True):
        h.flash_notice('DOI metadata updated.')
    else:
        error_message = 'Error updating dataset: \n' + result.get(
            'error', 'Internal Exception, please contact the portal admin.')
        h.flash_error(error_message)
        # toolkit.abort(500, error_message)
    return toolkit.redirect_to(controller='dataset', action='read', id=id)
def manual_finish_publication_package(id):
    """Finish manually the publication process for a dataset by the admin.
    """
    context = _get_context()

    log.debug("controller: manual_finish_publication_package: {0}".format(id))

    try:
        result = toolkit.get_action(
            'datacite_manual_finish_publication_package')(context, {
                'id': id
            })
    except toolkit.ObjectNotFound:
        toolkit.abort(404, 'Dataset not found')
    except toolkit.NotAuthorized:
        toolkit.abort(403, 'Not authorized')
    except toolkit.ValidationError:
        toolkit.abort(400, 'Validation error')

    if result.get('success', True):
        h.flash_notice('DOI publication finished.')
    else:
        error_message = 'Error finishing dataset publication: \n' + result.get(
            'error', 'Internal Exception, please contact '
            'the portal admin.')
        h.flash_error(error_message)
        # toolkit.abort(500, error_message)
    return toolkit.redirect_to(controller='dataset', action='read', id=id)
Exemple #9
0
    def convertToCSV(self):
        losd = LocalCKAN()
        try:
            resource_id = request.params.get('resource_id', u'')

            print("\n\n\n\n\n\n\n")
            print(request.params)

            # dataset = losd.action.package_show(id=pkg_id)
            resource_jsonstat = losd.action.resource_show(id=resource_id)

            Source_URL = resource_jsonstat['url']

            # read from json-stat
            dataset_jsonStat = pyjstat.Dataset.read(Source_URL)

            # write to dataframe
            df = dataset_jsonStat.write('dataframe')
            filename = '/var/lib/ckan/storage/uploads/' + unicode(
                uuid.uuid4()) + '.csv'
            df.to_csv(filename, sep=',', encoding='utf-8', index=False)

            losd.action.resource_create(
                package_id=request.params.get('pkg_id', u''),
                format='csv',
                name='csv ' + resource_jsonstat['name'],
                description='CSV file converted from json-stat resource:' +
                resource_jsonstat['name'],
                upload=open(filename))
            os.remove(filename)
            id = request.params.get('pkg_id', u'')
            h.flash_notice(_('A new CSV resource has been created.'))
            tk.redirect_to(controller='package', action='read', id=id)
        except NotFound:
            print('not found')
    def index(self, dsname):

        context = {'model': ckan.model,
                   'session': ckan.model.Session,
                   'user': pylons.c.user or pylons.c.author}

        pk_info = package_info(dsname, context)

        #flash messages
        no_view_msg = dsname + ', might not exist or you might not have permission to view or edit this dataset'
        no_edit_msg = 'you do not have permission or need to be logged-in to reorder this dataset'

        #if package doesn't exist
        if not pk_info:
            flash_error(no_view_msg)

        #package exists
        else:
            if not pk_info['edit']:
                flash_notice(no_edit_msg)

            if pk_info['view']:
                    plugins.toolkit.c.name = dsname
                    plugins.toolkit.c.view = pk_info['view']
                    plugins.toolkit.c.edit = pk_info['edit']
                    plugins.toolkit.c.resources = [item['name'] for item in pk_info['package']['resources']]

        return plugins.toolkit.render('index.html')
Exemple #11
0
    def admin(self):
        # Redirect to /news if not authorized:
        try:
            context = {'user': c.user}
            toolkit.check_access('blog_admin', context)
        except toolkit.NotAuthorized:
            h.redirect_to('/news')

        c.title = ''
        c.content = ''
        if request.method == 'POST':

            try:
                title, content = _validate_blog_post(request.POST)
            except ValidationError as err:
                return toolkit.render('blog/admin.html',
                                      extra_vars={'data_dict': request.POST,
                                                  'error': err.args})

            # We assume nothing will go wrong here, since the data has been
            # validated.
            from ckanext.sweden.blog.model.post import Post
            newPost = Post(title, content, c.userobj.id)
            model.Session.add(newPost)
            model.Session.commit()
            flash_notice(toolkit._("Your blog post has been saved!"))

            controller = 'ckanext.sweden.blog.controllers.blog:BlogController'
            h.redirect_to(controller=controller, action='admin_index')

        return toolkit.render('blog/admin.html',
                              extra_vars={'data_dict': {}, 'error': ''})
Exemple #12
0
    def resource_delete(self, id, resource_id):

        if 'cancel' in request.params:
            h.redirect_to(controller='package', action='resource_edit',
                          resource_id=resource_id, id=id)

        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'auth_user_obj': c.userobj}

        try:
            check_access('package_delete', context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete package %s') % '')

        try:
            if request.method == 'POST':
                #check against csrf attacks
                custom_base.csrf_check(self)
                get_action('resource_delete')(context, {'id': resource_id})
                h.flash_notice(_('Resource has been deleted.'))
                h.redirect_to(controller='package', action='read', id=id)
            c.resource_dict = get_action('resource_show')(
                context, {'id': resource_id})
            c.pkg_id = id
        except NotAuthorized:
            abort(401, _('Unauthorized to delete resource %s') % '')
        except NotFound:
            abort(404, _('Resource not found'))
        return render('package/confirm_delete_resource.html',
                      {'dataset_type': self._get_package_type(id)})
    def index(self, dsname):

        context = {
            'model': ckan.model,
            'session': ckan.model.Session,
            'user': pylons.c.user or pylons.c.author
        }

        pk_info = package_info(dsname, context)

        #flash messages
        no_view_msg = dsname + ', might not exist or you might not have permission to view or edit this dataset'
        no_edit_msg = 'you do not have permission or need to be logged-in to reorder this dataset'

        #if package doesn't exist
        if not pk_info:
            flash_error(no_view_msg)

        #package exists
        else:
            if not pk_info['edit']:
                flash_notice(no_edit_msg)

            if pk_info['view']:
                plugins.toolkit.c.name = dsname
                plugins.toolkit.c.view = pk_info['view']
                plugins.toolkit.c.edit = pk_info['edit']
                plugins.toolkit.c.resources = [
                    item['name'] for item in pk_info['package']['resources']
                ]

        return plugins.toolkit.render('index.html')
    def delete(self, id):
        if 'cancel' in request.params:
            tk.redirect_to(
                controller='ckanext.showcase.controller:ShowcaseController',
                action='edit', id=id)

        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'auth_user_obj': c.userobj}

        try:
            check_access('ckanext_showcase_delete', context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete showcase'))

        try:
            if request.method == 'POST':
                get_action('ckanext_showcase_delete')(context, {'id': id})
                h.flash_notice(_('Showcase has been deleted.'))
                tk.redirect_to(
                    controller='ckanext.showcase.controller:ShowcaseController',
                    action='search')
            c.pkg_dict = get_action('package_show')(context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete showcase'))
        except NotFound:
            abort(404, _('Showcase not found'))
        return render('showcase/confirm_delete.html',
                      extra_vars={'dataset_type': DATASET_TYPE_NAME})
    def manage_showcase_admins(self):
        '''
        A ckan-admin page to list and add showcase admin users.
        '''
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author}

        try:
            check_access('sysadmin', context, {})
        except NotAuthorized:
            abort(401, _('User not authorized to view page'))

        # We're trying to add a user to the showcase admins list.
        if request.method == 'POST' and request.params['username']:
            username = request.params['username']
            try:
                get_action('ckanext_showcase_admin_add')(
                    data_dict={'username': username})
            except NotAuthorized:
                abort(401, _('Unauthorized to perform that action'))
            except NotFound:
                h.flash_error(_("User '{user_name}' not found.").format(
                    user_name=username))
            except ValidationError as e:
                h.flash_notice(e.error_summary)
            else:
                h.flash_success(_("The user is now a Showcase Admin"))

            return redirect(h.url_for(
                controller='ckanext.showcase.controller:ShowcaseController',
                action='manage_showcase_admins'))

        c.showcase_admins = get_action('ckanext_showcase_admin_list')()

        return render('admin/manage_showcase_admins.html')
    def publish_package(self, package_id):
        '''Start publication process for a dataset.
        '''
        context = {
            'model': model,
            'session': model.Session,
            'user': toolkit.c.user,
        }

        try:
            result = toolkit.get_action('datacite_publish_package')(
                context, {
                    'id': package_id
                })
        except toolkit.ObjectNotFound:
            toolkit.abort(404, 'Dataset not found')
        except toolkit.NotAuthorized:
            toolkit.abort(403, 'Not authorized')

        if result.get('success', True):
            h.flash_notice(
                'DOI successfully reserved. Your publication request will be approved by an EnviDat admin as soon as possible.'
            )
        else:
            error_message = 'Error publishing dataset: \n' + result.get(
                'error',
                'Internal Exception, please contact the portal admin.')
            h.flash_error(error_message)
            #toolkit.abort(500, error_message)
        return toolkit.redirect_to(controller='package',
                                   action='read',
                                   id=package_id)
    def approve_publication_package(self, package_id):
        '''Approve publication process for a dataset by the admin.
        '''
        context = {
            'model': model,
            'session': model.Session,
            'user': toolkit.c.user,
        }

        log.debug(
            "controller: approve_publication_package: {0}".format(package_id))

        try:
            result = toolkit.get_action(
                'datacite_approve_publication_package')(context, {
                    'id': package_id
                })
        except toolkit.ObjectNotFound:
            toolkit.abort(404, 'Dataset not found')
        except toolkit.NotAuthorized:
            toolkit.abort(403, 'Not authorized')
        except toolkit.ValidationError:
            toolkit.abort(400, 'Validation error')

        if result.get('success', True):
            h.flash_notice('DOI publication approved.')
        else:
            error_message = 'Error approving dataset publication: \n' + result.get(
                'error',
                'Internal Exception, please contact the portal admin.')
            h.flash_error(error_message)
            #toolkit.abort(500, error_message)
        return toolkit.redirect_to(controller='package',
                                   action='read',
                                   id=package_id)
Exemple #18
0
    def before_commit(self, session):
        """
        Before we commit a session we will check to see if any of the new
        items are users so we can notify them to apply for publisher access.
        """
        from pylons.i18n import _
        from ckan.model.group import User

        session.flush()
        if not hasattr(session, '_object_cache'):
            return

        pubctlr = 'ckanext.dgu.controllers.publisher:PublisherController'
        for obj in set(session._object_cache['new']):
            if isinstance(obj, (User)):
                url = url_for(controller=pubctlr, action='apply')
                msg = "You can now <a href='%s'>apply for publisher access</a>" % url
                try:
                    flash_notice(_(msg), allow_html=True)
                except TypeError:
                    # Raised when there is no session registered, and this is
                    # the case when using the paster commands.
                    log.warning(
                        'Failed to add a flash message due to a missing session: %s'
                        % msg)
    def make_public_package(self, package_id):
        '''Make public a dataset.
        '''
        context = {
            'model': model,
            'session': model.Session,
            'user': toolkit.c.user,
        }

        try:
            result = toolkit.get_action('datacite_make_public_package')(
                context, {
                    'id': package_id
                })
        except toolkit.ObjectNotFound:
            toolkit.abort(404, 'Dataset not found')
        except toolkit.NotAuthorized:
            toolkit.abort(403, 'Not authorized')

        if result.get('success', True):
            h.flash_notice('Dataset is now public.')
        else:
            error_message = 'Error making dataset public: \n' + result.get(
                'error',
                'Internal Exception, please contact the portal admin.')
            h.flash_error(error_message)
            #toolkit.abort(500, error_message)
        return toolkit.redirect_to(controller='package',
                                   action='read',
                                   id=package_id)
Exemple #20
0
    def post(self, group_type, is_organization, id=None):
        set_org(is_organization)
        context = self._prepare(id)
        try:
            _action(u'group_delete')(context, {u'id': id})
            group_label = h.humanize_entity_type(
                u'group',
                group_type,
                u'has been deleted') or _(u'Group')
            h.flash_notice(
                _(u'%s has been deleted.') % _(group_label))
            group_dict = _action(u'group_show')(context, {u'id': id})
        except NotAuthorized:
            base.abort(403, _(u'Unauthorized to delete group %s') % u'')
        except NotFound:
            base.abort(404, _(u'Group not found'))
        except ValidationError as e:
            h.flash_error(e.error_dict['message'])
            return h.redirect_to(u'organization.read', id=id)

            return h.redirect_to(u'{}.read'.format(group_type), id=id)
        # TODO: Remove
        g.group_dict = group_dict

        return h.redirect_to(u'{}.index'.format(group_type))
Exemple #21
0
    def delete(self, id):
        if 'cancel' in request.params:
            self._redirect_to(controller='group', action='edit', id=id)

        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author}

        try:
            self._check_access('group_delete', context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete group %s') % '')

        try:
            if request.method == 'POST':
                self._action('group_delete')(context, {'id': id})
                if self.group_type == 'organization':
                    h.flash_notice(_('Organization has been deleted.'))
                else:
                    h.flash_notice(_('Group has been deleted.'))
                self._redirect_to(controller='group', action='index')
            c.group_dict = self._action('group_show')(context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete group %s') % '')
        except NotFound:
            abort(404, _('Group not found'))
        return self._render_template('group/confirm_delete.html')
Exemple #22
0
    def before_commit(self, session):
        """
        Before we commit a session we will check to see if any of the new
        items are users so we can notify them to apply for publisher access.
        """
        from pylons.i18n import _
        from ckan.model import User

        session.flush()
        if not hasattr(session, '_object_cache'):
            return

        pubctlr = 'ckanext.dgu.controllers.publisher:PublisherController'
        for obj in set(session._object_cache['new']):
            if isinstance(obj, (User)):
                try:
                    url = url_for(controller=pubctlr, action='apply')
                except CkanUrlException:
                    # This occurs when Routes has not yet been initialized
                    # yet, which would be before a WSGI request has been
                    # made. In this case, there will be no flash message
                    # required anyway.
                    return
                msg = "You can now <a href='%s'>apply for publisher access</a>" % url
                try:
                    flash_notice(_(msg), allow_html=True)
                except TypeError:
                    # Raised when there is no session registered, and this is
                    # the case when using the paster commands.
                    #log.debug('Did not add a flash message due to a missing session: %s' % msg)
                    pass
    def resource_delete(self, id, resource_id):

        if 'cancel' in request.params:
            h.redirect_to(controller='package', action='resource_edit',
                          resource_id=resource_id, id=id)

        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'auth_user_obj': c.userobj}

        try:
            check_access('package_delete', context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete package %s') % '')

        try:
            if request.method == 'POST':
                # check against csrf attacks
                custom_base.csrf_check(self)
                get_action('resource_delete')(context, {'id': resource_id})
                h.flash_notice(_('Resource has been deleted.'))
                h.redirect_to(controller='package', action='read', id=id)
            c.resource_dict = get_action('resource_show')(
                context, {'id': resource_id})
            c.pkg_id = id
        except NotAuthorized:
            abort(401, _('Unauthorized to delete resource %s') % '')
        except NotFound:
            abort(404, _('Resource not found'))
        return render('package/confirm_delete_resource.html',
                      {'dataset_type': self._get_package_type(id)})
Exemple #24
0
    def delete(self, id):
        if 'cancel' in request.params:
            self._redirect_to_this_controller(action='edit', id=id)

        context = {'model': model, 'session': model.Session, 'user': c.user}

        try:
            tk.check_access('basket_purge', context, {'id': id})
        except NotAuthorized:
            abort(403, _('Unauthorized to delete basket %s') % '')

        try:
            if request.method == 'POST':
                tk.get_action('basket_purge')(context, {'id': id})
                h.flash_notice(_('Basket has been deleted.'))
                url = h.url_for(
                    controller=
                    'ckanext.basket.controllers.basket:BasketController',
                    action='index')
                redirect(url)
            c.group_dict = tk.get_action('basket_show')(context, {'id': id})
        except NotAuthorized:
            abort(403, _('Unauthorized to delete basket %s') % '')
        except NotFound:
            abort(404, _('Basket not found'))
        return tk.render('basket/confirm_delete.html', vars)
Exemple #25
0
    def member_delete(self, id):
        group_type = self._ensure_controller_matches_group_type(id)

        if 'cancel' in request.params:
            self._redirect_to_this_controller(action='members', id=id)

        context = {'model': model, 'session': model.Session,
                   'user': c.user}

        try:
            self._check_access('group_member_delete', context, {'id': id})
        except NotAuthorized:
            abort(403, _('Unauthorized to delete group %s members') % '')

        try:
            user_id = request.params.get('user')
            if request.method == 'POST':
                self._action('group_member_delete')(
                    context, {'id': id, 'user_id': user_id})
                h.flash_notice(_('Group member has been deleted.'))
                self._redirect_to_this_controller(action='members', id=id)
            c.user_dict = self._action('user_show')(context, {'id': user_id})
            c.user_id = user_id
            c.group_id = id
        except NotAuthorized:
            abort(403, _('Unauthorized to delete group %s members') % '')
        except NotFound:
            abort(404, _('Group not found'))
        return self._render_template('group/confirm_delete_member.html',
                                     group_type)
Exemple #26
0
    def delete(self, id):
        if 'cancel' in request.params:
            self._redirect_to(controller='group', action='edit', id=id)

        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author
        }

        try:
            self._check_access('group_delete', context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete group %s') % '')

        try:
            if request.method == 'POST':
                self._action('group_delete')(context, {'id': id})
                if self.group_type == 'organization':
                    h.flash_notice(_('Organization has been deleted.'))
                else:
                    h.flash_notice(_('Group has been deleted.'))
                self._redirect_to(controller='group', action='index')
            c.group_dict = self._action('group_show')(context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete group %s') % '')
        except NotFound:
            abort(404, _('Group not found'))
        return self._render_template('group/confirm_delete.html')
    def delete(self, id):
        group_type = self._ensure_controller_matches_group_type(id)

        if 'cancel' in request.params:
            self._redirect_to_this_controller(action='edit', id=id)

        context = {'model': model, 'session': model.Session, 'user': c.user}

        try:
            self._check_access('group_delete', context, {'id': id})
        except NotAuthorized:
            abort(403, _('Unauthorized to delete group %s') % '')

        try:
            if request.method == 'POST':
                self._action('group_delete')(context, {'id': id})
                h.flash_notice(_('Collection has been deleted.'))
                self._redirect_to_this_controller(action='index')
            c.group_dict = self._action('group_show')(context, {'id': id})
        except NotAuthorized:
            abort(403, _('Unauthorized to delete collection %s') % '')
        except NotFound:
            abort(404, _('Collection not found'))
        return render('collection/confirm_delete.html',
                      extra_vars={'group_type': group_type})
Exemple #28
0
def remove_disabled_languages(key, data, errors, context):
    '''
    If `langdis == 'True'`, remove all languages.

    Expecting language codes in `data['key']`.

    :param key: key
    :param data: data
    :param errors: validation errors
    :param context: context
    '''
    langdis = data.get(('langdis',))

    langs = data.get(key).split(',')

    if langdis == 'False':
        # Language enabled

        if langs == [u'']:
            errors[key].append(_('No language given'))
    else:
        # Language disabled

        # Display flash message if user is loading a page.
        if 'session' in globals():
            h.flash_notice(_("Language is disabled, removing languages: '%s'" % data[key]))

        # Remove languages.
        del data[key]
        data[key] = u''
Exemple #29
0
    def refresh(self, id):
        try:
            context = {
                'model': model,
                'user': c.user,
                'session': model.Session}
            p.toolkit.get_action('harvest_job_create')(
                context, {'source_id': id})
            h.flash_success(
                _('Refresh requested, harvesting will take place within 15 minutes.'))
        except p.toolkit.ObjectNotFound:
            abort(404, _('Harvest source not found'))
        except p.toolkit.NotAuthorized:
            abort(401, self.not_auth_message)
        except Exception as e:
            if 'Can not create jobs on inactive sources' in str(e):
                h.flash_error(_('Cannot create new harvest jobs on inactive sources.' +
                                ' First, please change the source status to \'active\'.'))
            elif 'There already is an unrun job for this source' in str(e):
                h.flash_notice(
                    _('A harvest job has already been scheduled for this source'))
            else:
                msg = 'An error occurred: [%s]' % str(e)
                h.flash_error(msg)

        redirect(h.url_for('{0}_admin'.format(DATASET_TYPE_NAME), id=id))
Exemple #30
0
    def delete(self, id):
        if 'cancel' in request.params:
            tk.redirect_to(
                controller='ckanext.showcase.controller:ShowcaseController',
                action='edit',
                id=id)

        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'auth_user_obj': c.userobj
        }

        try:
            check_access('ckanext_showcase_delete', context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete showcase'))

        try:
            if request.method == 'POST':
                get_action('ckanext_showcase_delete')(context, {'id': id})
                h.flash_notice(_('Showcase has been deleted.'))
                tk.redirect_to(
                    controller='ckanext.showcase.controller:ShowcaseController',
                    action='search')
            c.pkg_dict = get_action('package_show')(context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete showcase'))
        except NotFound:
            abort(404, _('Showcase not found'))
        return render('showcase/confirm_delete.html',
                      extra_vars={'dataset_type': DATASET_TYPE_NAME})
Exemple #31
0
    def delete(self, id, related_id):
        if 'cancel' in base.request.params:
            h.redirect_to(controller='related',
                          action='edit',
                          id=id,
                          related_id=related_id)

        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'auth_user_obj': c.userobj
        }

        try:
            if base.request.method == 'POST':
                logic.get_action('related_delete')(context, {'id': related_id})
                h.flash_notice(_('Related item has been deleted.'))
                h.redirect_to(controller='package', action='read', id=id)
            c.related_dict = logic.get_action('related_show')(context, {
                'id': related_id
            })
            c.pkg_id = id
        except logic.NotAuthorized:
            base.abort(401, _('Unauthorized to delete related item %s') % '')
        except logic.NotFound:
            base.abort(404, _('Related item not found'))
        return base.render('related/confirm_delete.html')
def delete(id):
    data_dict = {"id": id}
    context = _get_context()

    try:
        tk.check_access(constants.DELETE_DATAREQUEST, context, data_dict)
        datarequest = tk.get_action(constants.DELETE_DATAREQUEST)(context,
                                                                  data_dict)
        helpers.flash_notice(
            tk._("Data Request {title} has been deleted").format(
                title=datarequest.get("title", "")))
        tk.redirect_to(
            helpers.url_for(
                controller="datarequests",
                action="index",
            ))
    except tk.ObjectNotFound as e:
        log.warn(e)
        tk.abort(404, tk._("Data Request {id} not found").format(id=id))
    except tk.NotAuthorized as e:
        log.warn(e)
        tk.abort(
            403,
            tk._("You are not authorized to delete the Data Request {id}").
            format(id=id),
        )
Exemple #33
0
    def post(self, package_type, id, resource_id):
        if u'cancel' in request.form:
            return h.redirect_to(
                u'{}_resource.edit'.format(package_type),
                resource_id=resource_id, id=id
            )
        context = self._prepare(id)

        try:
            get_action(u'resource_delete')(context, {u'id': resource_id})
            h.flash_notice(_(u'Resource has been deleted.'))
            pkg_dict = get_action(u'package_show')(None, {u'id': id})
            if pkg_dict[u'state'].startswith(u'draft'):
                return h.redirect_to(
                    u'{}_resource.new'.format(package_type),
                    id=id
                )
            else:
                return h.redirect_to(u'{}.read'.format(package_type), id=id)
        except NotAuthorized:
            return base.abort(
                403,
                _(u'Unauthorized to delete resource %s') % u''
            )
        except NotFound:
            return base.abort(404, _(u'Resource not found'))
Exemple #34
0
    def before_commit(self, session):
        """
        Before we commit a session we will check to see if any of the new
        items are users so we can notify them to apply for publisher access.
        """
        from pylons.i18n import _
        from ckan.model import User

        session.flush()
        if not hasattr(session, '_object_cache'):
            return

        pubctlr = 'ckanext.dgu.controllers.publisher:PublisherController'
        for obj in set(session._object_cache['new']):
            if isinstance(obj, (User)):
                try:
                    url = url_for(controller=pubctlr, action='apply')
                except CkanUrlException:
                    # This occurs when Routes has not yet been initialized
                    # yet, which would be before a WSGI request has been
                    # made. In this case, there will be no flash message
                    # required anyway.
                    return
                msg = "You can now <a href='%s'>apply for publisher access</a>" % url
                try:
                    flash_notice(_(msg), allow_html=True)
                except TypeError:
                    # Raised when there is no session registered, and this is
                    # the case when using the paster commands.
                    #log.debug('Did not add a flash message due to a missing session: %s' % msg)
                    pass
Exemple #35
0
    def delete(self, dataset_id, issue_number):
        dataset = self._before_dataset(dataset_id)
        if 'cancel' in request.params:
            p.toolkit.redirect_to('issues_show',
                                  dataset_id=dataset_id,
                                  issue_number=issue_number)

        if request.method == 'POST':
            try:
                toolkit.get_action('issue_delete')(data_dict={
                    'issue_number': issue_number,
                    'dataset_id': dataset_id
                })
            except toolkit.NotAuthorized:
                msg = _(u'Unauthorized to delete issue {0}').format(
                    issue_number)
                toolkit.abort(401, msg)

            h.flash_notice(_(u'Issue has been deleted.'))
            p.toolkit.redirect_to('issues_dataset', dataset_id=dataset_id)
        else:
            return render('issues/confirm_delete.html',
                          extra_vars={
                              'issue_number': issue_number,
                              'pkg': dataset,
                          })
Exemple #36
0
    def delete(self, id):
        data_dict = {'id': id}
        context = self._get_context()

        try:
            tk.check_access(constants.DATAREQUEST_DELETE, context, data_dict)
            datarequest = tk.get_action(constants.DATAREQUEST_DELETE)(
                context, data_dict)
            helpers.flash_notice(
                tk._('Data Request %s has been deleted') %
                datarequest.get('title', ''))
            base.redirect(
                helpers.url_for(
                    controller=
                    'ckanext.datarequests.controllers.ui_controller:DataRequestsUI',
                    action='index'))
        except tk.ObjectNotFound as e:
            log.warn(e)
            tk.abort(404, tk._('Data Request %s not found') % id)
        except tk.NotAuthorized as e:
            log.warn(e)
            tk.abort(
                403,
                tk._('You are not authorized to delete the Data Request %s' %
                     id))
    def delete(self, dataset_id, issue_number):
        dataset = self._before_dataset(dataset_id)
        if 'cancel' in request.params:
            h.redirect_to('issues_show',
                          dataset_id=dataset_id,
                          issue_number=issue_number)

        if request.method == 'POST':
            try:
                toolkit.get_action('issue_delete')(
                    data_dict={'issue_number': issue_number,
                               'dataset_id': dataset_id}
                )
            except toolkit.NotAuthorized:
                msg = _('Unauthorized to delete issue {0}'.format(
                    issue_number))
                toolkit.abort(401, msg)

            h.flash_notice(
                _('Issue {0} has been deleted.'.format(issue_number))
            )
            h.redirect_to('issues_dataset', dataset_id=dataset_id)
        else:
            return render('issues/confirm_delete.html',
                          extra_vars={
                              'issue_number': issue_number,
                              'pkg': dataset,
                          })
Exemple #38
0
    def report_abuse(self, id):
        """
        When a user reports something as offensive, this action will mark it
        ready for moderation.  If the user reporting is a system administrator
        it will be marked, but also made invisible so that it no longer shows up
        """
        import ckan.model as model
        from ckanext.dgu.model.feedback import Feedback

        fb = Feedback.get(id)
        if fb:
            fb.moderated = False
            fb.moderation_required = True
            if is_sysadmin():
                fb.visible = False
                flash_notice(
                    "Queued. As you are an administrator, this item has been hidden"
                )
            else:
                flash_notice(
                    "Thank you for your feedback, the item has been queued for moderation"
                )
            model.Session.add(fb)
            model.Session.commit()

        h.redirect_to(request.referer or '/data')
Exemple #39
0
    def delete(self, id):
        if "cancel" in request.params:
            self._redirect_to(controller="group", action="edit", id=id)

        context = {"model": model, "session": model.Session, "user": c.user or c.author}

        try:
            self._check_access("group_delete", context, {"id": id})
        except NotAuthorized:
            abort(401, _("Unauthorized to delete group %s") % "")

        try:
            if request.method == "POST":
                self._action("group_delete")(context, {"id": id})
                if self.group_type == "organization":
                    h.flash_notice(_("Organization has been deleted."))
                else:
                    h.flash_notice(_("Group has been deleted."))
                self._redirect_to(controller="group", action="index")
            c.group_dict = self._action("group_show")(context, {"id": id})
        except NotAuthorized:
            abort(401, _("Unauthorized to delete group %s") % "")
        except NotFound:
            abort(404, _("Group not found"))
        return self._render_template("group/confirm_delete.html")
Exemple #40
0
    def member_delete(self, id):
        if "cancel" in request.params:
            self._redirect_to(controller="group", action="members", id=id)

        context = {"model": model, "session": model.Session, "user": c.user or c.author}

        try:
            self._check_access("group_member_delete", context, {"id": id})
        except NotAuthorized:
            abort(401, _("Unauthorized to delete group %s members") % "")

        try:
            user_id = request.params.get("user")
            if request.method == "POST":
                self._action("group_member_delete")(context, {"id": id, "user_id": user_id})
                h.flash_notice(_("Group member has been deleted."))
                self._redirect_to(controller="group", action="members", id=id)
            c.user_dict = self._action("user_show")(context, {"id": user_id})
            c.user_id = user_id
            c.group_id = id
        except NotAuthorized:
            abort(401, _("Unauthorized to delete group %s") % "")
        except NotFound:
            abort(404, _("Group not found"))
        return self._render_template("group/confirm_delete_member.html")
Exemple #41
0
 def refresh(self, id):
     try:
         context = {
             'model': model,
             'user': c.user,
             'session': model.Session
         }
         p.toolkit.get_action('harvest_job_create')(context, {
             'source_id': id
         })
         h.flash_success(
             _('Refresh requested, harvesting will take place within 15 minutes.'
               ))
     except p.toolkit.ObjectNotFound:
         abort(404, _('Harvest source not found'))
     except p.toolkit.NotAuthorized:
         abort(401, self.not_auth_message)
     except Exception, e:
         if 'Can not create jobs on inactive sources' in str(e):
             h.flash_error(
                 _('Cannot create new harvest jobs on inactive sources.' +
                   ' First, please change the source status to \'active\'.')
             )
         elif 'There already is an unrun job for this source' in str(e):
             h.flash_notice(
                 _('A harvest job has already been scheduled for this source'
                   ))
         else:
             msg = 'An error occurred: [%s]' % str(e)
             h.flash_error(msg)
Exemple #42
0
def refresh_view(id):
    try:
        context = {'model': model, 'user': tk.c.user, 'session': model.Session}
        tk.get_action('harvest_job_create')(context, {
            'source_id': id,
            'run': True
        })
        h.flash_success(
            _('Harvest will start shortly. Refresh this page for updates.'))
    except tk.ObjectNotFound:
        return tk.abort(404, _('Harvest source not found'))
    except tk.NotAuthorized:
        return tk.abort(401, _not_auth_message())
    except HarvestSourceInactiveError:
        h.flash_error(
            _('Cannot create new harvest jobs on inactive '
              'sources. First, please change the source status '
              'to "active".'))
    except HarvestJobExists:
        h.flash_notice(
            _('A harvest job has already been scheduled for '
              'this source'))
    except Exception as e:
        msg = 'An error occurred: [%s]' % str(e)
        h.flash_error(msg)

    return h.redirect_to(
        h.url_for('{0}_admin'.format(DATASET_TYPE_NAME), id=id))
    def post(self, name=None):
        context = self._prepare(name)
        sub_theme = context['sub_theme']

        try:
            data_dict = logic.clean_dict(
                dictization_functions.unflatten(
                    logic.tuplize_dict(logic.parse_params(request.form))))
            data_dict.pop('save', '')
        except dictization_functions.DataError:
            base.abort(400, _(u'Integrity Error'))

        data_dict['id'] = sub_theme.get('id')

        try:
            st = logic.get_action(u'sub_theme_update')(context, data_dict)
            h.flash_notice(_(u'Sub-Theme has been updated.'))
        except logic.NotAuthorized:
            base.abort(403, _(u'Unauthorized to update the sub-theme'))
        except logic.ValidationError as e:
            errors = e.error_dict
            error_summary = e.error_summary
            return self.get(name, data_dict, errors, error_summary)

        try:
            kwh_data = {
                'type': 'sub-theme',
                'old_content': sub_theme.get('title'),
                'new_content': st.get('title')
            }
            logic.get_action(u'kwh_data_update')(context, kwh_data)
        except Exception as e:
            log.debug('Error while storing KWH data: %s' % str(e))

        return h.redirect_to(u'sub_theme.read', name=sub_theme.get(u'name'))
 def sync_all_ext(self, id):
     self._load(id)
     if not c.pkg_dict['private']:
         sync(c.pkg_dict, False)
         h.flash_notice(_('Synchronization with external catalogs ended.'))
     else:
         h.flash_notice(_("Synchronization not started, the dataset isn't public."))
     base.redirect(h.url_for('dataset_publishing', id=id))
    def verify(self, id, data, vars):
        cat_id, type, url, auth_req, auth, org_id, create_as_private = data
        has_errors = len(vars) > 0
            
        vars['cat_id'] = cat_id
        vars['type'] = type
        vars['url_val'] = url
        vars['req_auth'] = auth_req
        vars['auth'] = auth
        vars['org_id'] = org_id
        vars['create_as_private'] = create_as_private
        
        log.debug("CREATE AS PRIVATE = {0}".format(create_as_private))
        
        if has_errors :
            return self._edit(id, vars)
        
        self._load(id)
        if type == 'CKAN':
            if auth_req:
                ext_cat = CkanAPIWrapper(url, auth)
            else:
                ext_cat = CkanAPIWrapper(url, None)
            
            # check if catalog is available
            read_ok, redirected_to = ext_cat.site_read()
            if not read_ok:
                vars['url_error'] = [_('Could not connect to this catalog.')]
                return self._edit(id, vars, False)
            
            if redirected_to:
                h.flash_notice(_('The verification was redirected to \'{0}\'. '
                    'The synchronization may not function properly. Try to '
                    'replace URL for the redirected url.').format(redirected_to))
            
            # check organization
            check_org = org_id or c.pkg_dict.get('owner_org', None)
            org = ext_cat.organization_show2(check_org)
            if not org:
                vars['org_error'] = [_('Organization with this id or name was not found.')]
                return self._edit(id, vars, False)
            
            # chech authorization
            if not ext_cat.has_edit_rights(check_org):
                if auth_req:
                    vars['auth_error'] = [_('User with this API key is not authorized to edit datasets for organization {0}').format(org['name'])]
                else:
                    vars['auth_req_error'] = [_('This catalog requires authorization for organization {0}.').format(org['name'])]
                return self._edit(id, vars, False)

            vars['verified'] = True
            h.flash_success(_("External catalog verification was successful."))
            return self._edit(id, vars, False)
        else:
            h.flash_notice(_("Verify is not supported for type {0}").format(type))
            return self._edit(id, vars, False)
Exemple #46
0
 def _update_metadata(self, pkg):
     try:
         self._post_metadata(pkg)
     except rems_client.RemsException as e:
         h.flash_notice(
             _('Dataset saved but REMS application creation failed. To '
               'retry, save dataset later without changes.')
         )
         # TODO: Add failed item to retry queue
         log.debug(str(e))
         log.debug('Adding failed item to retry queue (unimplemented)')
Exemple #47
0
    def resource_delete(self, id, resource_id):
        # TODO: This whole method is a workaround for a core ckan issue
        # that can be removed when the issue is resolved
        # https://github.com/ckan/ckan/issues/2651

        #Back to the resource edit if user has chosen cancel on delete confirmation
        if 'cancel' in request.params:
            h.redirect_to(controller='package',
                          action='resource_edit',
                          resource_id=resource_id,
                          id=id)

        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'auth_user_obj': c.userobj
        }

        #Check if user is authorized to delete the resourec
        try:
            check_access('package_delete', context, {'id': id})
        except NotAuthorized:
            abort(401, _('Unauthorized to delete package %s') % '')

        #Get the package containing the resource
        try:
            pkg = get_action('package_show')(context, {'id': id})
        except NotFound:
            abort(404, _('Resource dataset not found'))

        #Deleting the resource
        try:
            if request.method == 'POST':
                get_action('resource_delete')(context, {'id': resource_id})
                h.flash_notice(_('Resource has been deleted.'))

                #Redirect to a new resource page if we are creating a new dataset
                if pkg.get('state').startswith('draft'):
                    h.redirect_to(controller='package',
                                  action='new_resource',
                                  id=id)

                h.redirect_to(controller='package', action='read', id=id)
            c.resource_dict = get_action('resource_show')(context, {
                'id': resource_id
            })
            c.pkg_id = id
        except NotAuthorized:
            abort(401, _('Unauthorized to delete resource %s') % '')
        except NotFound:
            abort(404, _('Resource not found'))
        return render('package/confirm_delete_resource.html')
Exemple #48
0
def package_show(context, data_dict):
    user = context.get('user')
    user_obj = context.get('auth_user_obj')
    package = logic_auth.get_package_object(context, data_dict)

    # datasets can be read by its creator
    if package and user_obj and package.creator_user_id == user_obj.id:
        return {'success': True}

    # Not active packages can only be seen by its owners
    if package.state == 'active':
        # anyone can see a public package
        if package.private:

            acquired = False

            if package.owner_org:
                acquired = authz.has_user_permission_for_group_or_org(
                    package.owner_org, user, 'read')

            if not acquired:
                # Init the model
                db.init_db(context['model'])

                # Branch not executed if the database return an empty list
                if db.AllowedUser.get(package_id=package.id, user_name=user):
                    acquired = True

            if not acquired:

                # Show a flash message with the URL to acquire the dataset
                # This message only can be shown when the user tries to access the dataset via its URL (/dataset/...)
                # The message cannot be displayed in other pages that uses the package_show function such as
                # the user profile page

                if hasattr(package, 'extras') and 'acquire_url' in package.extras and request.path.startswith(
                        '/dataset/') \
                        and package.extras['acquire_url'] != '':
                    helpers.flash_notice(_(
                        'This private dataset can be acquired. To do so, please click '
                        + '<a target="_blank" href="%s">here</a>') %
                                         package.extras['acquire_url'],
                                         allow_html=True)

        return {'success': True}
    else:
        return {
            'success':
            False,
            'msg':
            _('User %s not authorized to read package %s') % (user, package.id)
        }
    def resource_version_delete(self, dataset, resource, version=0):

        data_dict = {
            'id': resource
        }
        if version:
            data_dict['version_id'] = version

        p.toolkit.get_action('file_request_delete')({}, data_dict)

        helpers.flash_notice('Deletion of File version {0} was requested'.format(version))

        p.toolkit.redirect_to('resource_version')
    def topicsubscription_delete(self, subscription_id):
        ''' Delete a WSO2 ESB Topic's subscription. Note that no relation to CKAN is required! '''
        
        if not new_authz.is_sysadmin(c.user):
            abort(401, _('Unauthorized to delete WSO2 ESB Topic subscriptions'))

        brokerclient = getBrokerClient()
        brokerclient.unsubscribe(subscription_id)

        log.info(_('WSO2 ESB Topic subscription with an id {id} was deleted.').format(id=subscription_id))
        h.flash_notice(_('WSO2 ESB Topic subscription with an id {id} was deleted.').format(id=subscription_id))

        h.redirect_to(controller='admin', action='wso2esb')
Exemple #51
0
    def _login_failed(self, notice=None, error=None):
        """Handle login failures

        Redirect to /user/login and flash an optional message

        @param notice: Optional notice for the user
        @param error: Optional error message for the user
        """
        if notice:
            flash_notice(notice)
        if error:
            flash_error(error)
        p.toolkit.redirect_to(controller='user', action='login')
 def delete_comment(self, datarequest_id, comment_id):
     try:
         context = self._get_context()
         data_dict = {'id': comment_id}
         tk.check_access(constants.DELETE_DATAREQUEST_COMMENT, context, data_dict)
         tk.get_action(constants.DELETE_DATAREQUEST_COMMENT)(context, data_dict)
         helpers.flash_notice(tk._('Comment has been deleted'))
         tk.redirect_to(helpers.url_for(controller='ckanext.datarequests.controllers.ui_controller:DataRequestsUI', action='comment', id=datarequest_id))
     except tk.ObjectNotFound as e:
         log.warn(e)
         tk.abort(404, tk._('Comment %s not found') % comment_id)
     except tk.NotAuthorized as e:
         log.warn(e)
         tk.abort(403, tk._('You are not authorized to delete this comment'))
def package_show(context, data_dict):
    user = context.get('user')
    user_obj = context.get('auth_user_obj')
    package = logic_auth.get_package_object(context, data_dict)

    # datasets can be read by its creator
    if package and user_obj and package.creator_user_id == user_obj.id:
        return {'success': True}

    # Not active packages can only be seen by its owners
    if package.state == 'active':
        # anyone can see a public package
        if not package.private:
            return {'success': True}

        # if the user has rights to read in the organization or in the group
        if package.owner_org:
            authorized = new_authz.has_user_permission_for_group_or_org(
                package.owner_org, user, 'read')
        else:
            authorized = False

        # if the user is not authorized yet, we should check if the
        # user is in the allowed_users object
        if not authorized:
            # Init the model
            db.init_db(context['model'])

            # Branch not executed if the database return an empty list
            if db.AllowedUser.get(package_id=package.id, user_name=user):
                authorized = True

        if not authorized:
            # Show a flash message with the URL to acquire the dataset
            # This message only can be shown when the user tries to access the dataset via its URL (/dataset/...)
            # The message cannot be displayed in other pages that uses the package_show function such as
            # the user profile page

            if hasattr(package, 'extras') and 'acquire_url' in package.extras and request.path.startswith('/dataset/')\
                    and package.extras['acquire_url'] != '':
                helpers.flash_notice(_('This private dataset can be acquired. To do so, please click ' +
                                       '<a target="_blank" href="%s">here</a>') % package.extras['acquire_url'],
                                     allow_html=True)

            return {'success': False, 'msg': _('User %s not authorized to read package %s') % (user, package.id)}
        else:
            return {'success': True}
    else:
        return {'success': False, 'msg': _('User %s not authorized to read package %s') % (user, package.id)}
 def sync_ext(self, id, cat_id):
     self._load(id)
     log.debug("syncronizing specific ext catalog {0}".format(cat_id))
     if not c.pkg_dict['private']:
         from_ckan = CkanAPIWrapper(src_ckan, None)
         ext_cat = ExternalCatalog.by_id(cat_id)
         errors = []
         errs = sync_ext_catalog(from_ckan, ext_cat, c.pkg_dict)
         for err in errs:
             errors.append('{0} - {1}'.format(ext_cat.url, err))
         flash_errors_for_ext_cat(errors)
         h.flash_notice(_('Synchronization with public catalog ended.'))
     else:
         h.flash_notice(_("Synchronization not started, the dataset isn't public."))
     base.redirect(h.url_for('dataset_publishing', id=id))
Exemple #55
0
    def post(self, package_type, id):
        if u'cancel' in request.form:
            return h.redirect_to(u'dataset.edit', id=id)
        context = self._prepare()
        try:
            get_action(u'package_delete')(context, {u'id': id})
        except NotFound:
            return base.abort(404, _(u'Dataset not found'))
        except NotAuthorized:
            return base.abort(
                403,
                _(u'Unauthorized to delete package %s') % u''
            )

        h.flash_notice(_(u'Dataset has been deleted.'))
        return h.redirect_to(package_type + u'.search')
    def delete(self, id):
        data_dict = {'id': id}
        context = self._get_context()

        try:
            tk.check_access(constants.DELETE_DATAREQUEST, context, data_dict)
            datarequest = tk.get_action(constants.DELETE_DATAREQUEST)(context, data_dict)
            helpers.flash_notice(tk._('Data Request %s has been deleted') % datarequest.get('title', ''))
            tk.redirect_to(helpers.url_for(controller='ckanext.datarequests.controllers.ui_controller:DataRequestsUI', action='index'))
        except tk.ObjectNotFound as e:
            log.warn(e)
            tk.abort(404, tk._('Data Request %s not found') % id)
        except tk.NotAuthorized as e:
            log.warn(e) 
            tk.abort(403, tk._('You are not authorized to delete the Data Request %s'
                               % id))
Exemple #57
0
    def index(self):
        try:
            # package search
            context = {'model': model, 'session': model.Session,
                       'user': c.user, 'auth_user_obj': c.userobj}
            data_dict = {
                'q': '*:*',
                'facet.field': g.facets,
                'rows': 4,
                'start': 0,
                'sort': 'views_recent desc',
                'fq': 'capacity:"public"'
            }
            query = logic.get_action('package_search')(
                context, data_dict)
            c.search_facets = query['search_facets']
            c.package_count = query['count']
            c.datasets = query['results']

            c.facets = query['facets']
            maintain.deprecate_context_item(
                'facets',
                'Use `c.search_facets` instead.')

            c.search_facets = query['search_facets']

            c.facet_titles = {
                'organization': _('Organizations'),
                'groups': _('Groups'),
                'tags': _('Tags'),
                'res_format': _('Formats'),
                'license': _('Licenses'),
            }

        except search.SearchError:
            c.package_count = 0

        if c.userobj and not c.userobj.email:
            url = h.url_for(controller='user', action='edit')
            msg = _('Please <a href="%s">update your profile</a>'
                    ' and add your email address. ') % url + \
                _('%s uses your email address'
                    ' if you need to reset your password.') \
                % g.site_title
            h.flash_notice(msg, allow_html=True)

        return base.render('home/index.html', cache_force=True)
    def delete(self, id):
        data_dict = {'id': id}
        context = self._get_context()

        try:
            tk.check_access(constants.DATAREQUEST_DELETE, context, data_dict)
            datarequest = tk.get_action(constants.DATAREQUEST_DELETE)(context, data_dict)
            tk.response.status_int = 302
            tk.response.location = '/%s' % constants.DATAREQUESTS_MAIN_PATH
            helpers.flash_notice(tk._('Data Request %s deleted correctly') % datarequest.get('title', ''))
        except tk.ObjectNotFound as e:
            log.warn(e)
            tk.abort(404, tk._('Data Request %s not found') % id)
        except tk.NotAuthorized as e:
            log.warn(e) 
            tk.abort(403, tk._('You are not authorized to delete the Data Request %s'
                               % id))
def validate_language(key, data, errors, context):
    value = data[key]
    langdis = data.get(('langdis',), None)
    if langdis == 'True':
        value = data.pop(key, None)
        h.flash_notice(_("Language was deleted as it is disabled. Value was: %s" % value))
        return
    for lang in value.split(','):
        lang = lang.strip()
        try:
            if lang:
                pycountry.languages.get(alpha2=lang)
            elif langdis == 'False':
                errors[key].append(_('No language given.'))
        except KeyError:
            if not ('langdis',) in data and 'save' in context:
                errors[key].append(_('Invalid language %s, not in ISO 639.' % lang))