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 request_new_organization(self): context = {'model': model, 'session': model.Session, 'user': c.user or c.author} try: tk.check_access('hdx_send_new_org_request',context) except logic.NotAuthorized: base.abort(401, _('Unauthorized to send a new org request')) errors = {} error_summary = {} data = {'from': request.params.get('from','')} from_url = '' if 'save' in request.params: try: data = self._process_new_org_request() self._validate_new_org_request_field(data) tk.get_action('hdx_send_new_org_request')(context, data) #from_url = data.get('from','') data.clear() h.flash_success(_('Request sent successfully')) except hdx_mail.NoRecipientException, e: h.flash_error(_(str(e))) except logic.ValidationError, e: errors = e.error_dict error_summary = e.error_summary
def report(self, dataset_id, issue_number): dataset = self._before_dataset(dataset_id) if request.method == 'POST': if not c.user: msg = _('You must be logged in to report issues') toolkit.abort(401, msg) try: report_info = toolkit.get_action('issue_report')( data_dict={ 'issue_number': issue_number, 'dataset_id': dataset_id } ) if report_info: # we have this info if it is an admin msgs = [_('Report acknowledged.')] if report_info['abuse_status'] == \ issuemodel.AbuseStatus.abuse.value: msgs.append(_('Marked as abuse/spam.')) msgs.append(_('Issue is visible.') if report_info['visibility'] == 'visible' else _('Issue is invisible to normal users.')) h.flash_success(' '.join(msgs)) else: h.flash_success(_('Issue reported to an administrator')) except toolkit.ValidationError: toolkit.abort(404) except toolkit.ObjectNotFound: toolkit.abort(404) except ReportAlreadyExists, e: h.flash_error(e.message) h.redirect_to('issues_show', dataset_id=dataset_id, issue_number=issue_number)
def _listener_route(self, action, id, resource_id): if not c.userobj or not c.userobj.sysadmin: base.abort(404) if action == 'terminate': task = session.query(model.TaskStatus)\ .filter( model.TaskStatus.task_type=='twitter_streaming', model.TaskStatus.entity_id==resource_id)\ .first() if not task: h.flash_error("Can't find listener") if task: pid = task.error or '' if not pid: h.flash_error("Can't get PID of process") else: h.flash_success('Success') toolkit.get_action('task_status_update')(None, { 'entity_id': resource_id, 'task_type': 'twitter_streaming', 'key': 'celery_task_id', 'state': 'Terminated', 'value': 'Ready for start', 'error': pid, 'last_updated': datetime.datetime.now().isoformat(), 'entity_type': 'resource' }) if os.system('kill -9 %s' % pid): toolkit.get_action('celery_revoke')(self.context, {'id': pid, 'resource': resource_id}) base.redirect(h.url_for('getting_tweets', id=id, resource_id=resource_id))
def request_reset(self): context = {"model": model, "session": model.Session, "user": toolkit.c.user, "auth_user_obj": toolkit.c.userobj} data_dict = {"id": toolkit.request.params.get("user")} try: toolkit.check_access("request_reset", context) except toolkit.NotAuthorized: toolkit.abort(401, toolkit._("Unauthorized to request reset password.")) if toolkit.request.method == "POST": id = toolkit.request.params.get("user") context = {"model": model, "user": toolkit.c.user} data_dict = {"id": id} user_obj = None try: toolkit.get_action("user_show")(context, data_dict) user_obj = context["user_obj"] except toolkit.ObjectNotFound: h.flash_error(toolkit._("No such user: %s") % id) if user_obj: try: mailer.send_reset_link(user_obj) h.flash_success(toolkit._("Please check your inbox for " "a reset code.")) h.redirect_to("/") except mailer.MailerException, e: h.flash_error(toolkit._("Could not send reset link: %s") % unicode(e))
def remove_pipe(self, id, pipeline_id): assert id assert pipeline_id try: data_dict = {'id': id} context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj} check_access('package_update', context, data_dict) package = get_action('package_show')(context, data_dict) # id is most probably is package.name so we have to get actual id pipe = Pipelines(package['id'], pipeline_id).get() if not pipe: h.flash_error(_(u"Couldn't remove pipeline, because there is no such pipeline assigned to this dataset.")) base.redirect(h.url_for('pipe_assign', id=id)) else: pipe_id = pipe.pipeline_id pipe.delete() pipe.commit() h.flash_success(_(u'Pipeline removed from dataset successfully')) disable_schedules_for_pipe(pipe_id) except NotFound: abort(404, _(u'Dataset not found')) except NotAuthorized: abort(401, _(u'User {user} not authorized to edit {id}').format(user=c.user, id=id)) base.redirect(h.url_for('pipe_assign', id=id))
def logged_in(self): came_from = request.params.get('came_from', '') if c.user: context = None data_dict = {'id': c.user, 'link_wotkit': True} try: user_dict = get_action('user_show')(context, data_dict) except logic.NotAuthorized as e: return self.login(error=str(e)) h.flash_success(_("%s is now logged in") % user_dict['display_name']) if came_from and "logged_in" not in came_from: """Mark: HACK redirect to ignore the base URL /data. This used to use url_for, but doing so always appends the /data path which we won't want Thus had to change it to redirect_to """ return routes.redirect_to(str(came_from)) return self.me() else: err = _('Login failed. Bad username or password.') if g.openid_enabled: err += _(' (Or if using OpenID, it hasn\'t been associated ' 'with a user account.)') if h.asbool(config.get('ckan.legacy_templates', 'false')): h.flash_error(err) h.redirect_to(locale=lang, controller='user', action='login', came_from=came_from) else: return self.login(error=err)
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))
def request_reset(self): context = {'model': model, 'session': model.Session, 'user': c.user, 'auth_user_obj': c.userobj} data_dict = {'id': request.params.get('user')} try: check_access('request_reset', context) except NotAuthorized: abort(401, _('Unauthorized to request reset password.')) if request.method == 'POST': id = request.params.get('user') context = {'model': model, 'user': c.user} data_dict = {'id': id} user_obj = None try: user_dict = get_action('user_show')(context, data_dict) user_obj = context['user_obj'] except NotFound: # Show success regardless of outcome to prevent scanning h.flash_success(_('Please check your inbox for ' 'a reset code.')) if user_obj: try: mailer.send_reset_link(user_obj) h.flash_success(_('Please check your inbox for ' 'a reset code.')) h.redirect_to('/') except mailer.MailerException, e: h.flash_error(_('Could not send reset link: %s') % unicode(e))
def request_reset(self): context = {'model': model, 'session': model.Session, 'user': c.user, 'auth_user_obj': c.userobj} try: check_access('request_reset', context) except NotAuthorized: abort(401, _('Unauthorized to request reset password.')) if request.method == 'POST': email = request.params.get('email') users = model.User.by_email(email) if not users: h.flash_error(_('Email not registered: %s') % email) else: try: mailer.send_reset_link(users[0]) h.flash_success(_('Please check your inbox for ' 'a reset code.')) h.redirect_to('/') except mailer.MailerException, e: h.flash_error(_('Could not send reset link: %s') % unicode(e))
def remove_project_admin(self): ''' Remove a user from the project Admin list. ''' 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')) if 'cancel' in request.params: tk.redirect_to(controller='ckanext.project.controller:projectController', action='manage_project_admins') user_id = request.params['user'] if request.method == 'POST' and user_id: user_id = request.params['user'] try: get_action('ckanext_project_admin_remove')(data_dict={'username': user_id}) except NotAuthorized: abort(401, _('Unauthorized to perform that action')) except NotFound: h.flash_error(_('The user is not a project Admin')) else: h.flash_success(_('The user is no longer a project Admin')) return redirect(h.url_for(controller='ckanext.project.controller:projectController', action='manage_project_admins')) c.user_dict = get_action('user_show')(data_dict={'id': user_id}) c.user_id = user_id return render('admin/confirm_remove_project_admin.html')
def logged_in(self): # redirect if needed came_from = request.params.get('came_from', '') if self._sane_came_from(came_from): return h.redirect_to(str(came_from)) if c.user: context = None data_dict = {'id': c.user} user_dict = get_action('user_show')(context, data_dict) h.flash_success( _("%s is now logged in") % user_dict['display_name']) return self.me() else: err = _('Login failed. Bad username or password.') if g.openid_enabled: err += _(' (Or if using OpenID, it hasn\'t been associated ' 'with a user account.)') if h.asbool(config.get('ckan.legacy_templates', 'false')): h.flash_error(err) h.redirect_to( controller='user', action='login', came_from=came_from) else: return self.login(error=err)
def dataset_project_list(self, id): ''' Display a list of projects a dataset is associated with, with an option to add to project from a list. ''' context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'for_view': True, 'auth_user_obj': c.userobj} data_dict = {'id': id} try: check_access('package_show', context, data_dict) except NotFound: abort(404, _('Dataset not found')) except NotAuthorized: abort(401, _('Not authorized to see this page')) try: c.pkg_dict = get_action('package_show')(context, data_dict) c.project_list = get_action('ckanext_package_project_list')(context, {'package_id': c.pkg_dict['id']}) except NotFound: abort(404, _('Dataset not found')) except logic.NotAuthorized: abort(401, _('Unauthorized to read package %s') % id) if request.method == 'POST': # Are we adding the dataset to a project? new_project = request.POST.get('project_added') if new_project: data_dict = {"project_id": new_project, "package_id": c.pkg_dict['id']} try: get_action('ckanext_project_package_association_create')(context, data_dict) except NotFound: abort(404, _('project not found')) else: h.flash_success(_("The dataset has been added to the project.")) # Are we removing a dataset from a project? project_to_remove = request.POST.get('remove_project_id') if project_to_remove: data_dict = {"project_id": project_to_remove, "package_id": c.pkg_dict['id']} try: get_action('ckanext_project_package_association_delete')(context, data_dict) except NotFound: abort(404, _('project not found')) else: h.flash_success(_("The dataset has been removed from the project.")) redirect(h.url_for(controller='ckanext.project.controller:projectController', action='dataset_project_list', id=c.pkg_dict['name'])) pkg_project_ids = [project['id'] for project in c.project_list] site_projects = get_action('ckanext_project_list')(context, {}) c.project_dropdown = [[project['id'], project['title']] for project in site_projects if project['id'] not in pkg_project_ids] return render("package/dataset_project_list.html")
def unpublish_ogc(context, data_dict): """ Un-publishes the Geoserver layer based on the resource identifier. Retrieves the Geoserver layer name and package identifier to construct layer and remove it. """ resource_id = data_dict.get("resource_id") layer_name = data_dict.get("layer_name") layer_name = "NGDS:" + resource_id username = context.get('user') file_resource = toolkit.get_action("resource_show")(None, {"id": resource_id}) geoserver = Geoserver.from_ckan_config() package_id = model.Resource.get(resource_id).resource_group.package_id def unpub(): layer = Layer(geoserver=geoserver, layer_name=layer_name, resource_id=resource_id, package_id=package_id, username=username) return layer try: layer = unpub() except socket.error: h.flash_error( _("Error connecting to geoserver. Please contact the site administrator if this problem persists.")) return False layer.remove() h.flash_success( _("This resource has successfully been unpublished.")) return True
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))
def form(self): context = {'model': model, 'user': c.user} if not ckan.new_authz.is_authorized('sysadmin', context, {})['success']: base.abort(401, _('Need to be system administrator')) # get one and only one entry from our extlink table entry = model.Session.query(extlinkmodel.ExtLink).first() if not entry: # create the empty entry for the first time entry = extlinkmodel.ExtLink() entry.save() if base.request.method == "POST": data = logic.clean_dict( df.unflatten( logic.tuplize_dict( logic.parse_params(base.request.params) ))) entry.domains = data.get('white-list') entry.message = data.get('message') entry.save() h.flash_success(_('External link changes saved.')) h.redirect_to(controller=self.controller_path, action='form') c.extlinkdata = { 'white-list': entry.domains, 'message': entry.message, 'placeholder': msg_default, } return p.toolkit.render("form.html")
def logged_in(self): # we need to set the language via a redirect lang = session.pop('lang', None) session.save() came_from = request.params.get('came_from', '') # we need to set the language explicitly here or the flash # messages will not be translated. i18n.set_lang(lang) if c.user: context = None data_dict = {'id': c.user} user_dict = get_action('user_show')(context, data_dict) h.flash_success(_("%s is now logged in") % user_dict['display_name']) if came_from: return h.redirect_to(str(came_from)) return self.me() else: err = _('Login failed. Bad username or password.') if g.openid_enabled: err += _(' (Or if using OpenID, it hasn\'t been associated ' 'with a user account.)') if h.asbool(config.get('ckan.legacy_templates', 'false')): h.flash_error(err) h.redirect_to(locale=lang, controller='user', action='login', came_from=came_from) else: return self.login(error=err)
def _save_new_pending(self, context): params = request.params password = str(binascii.b2a_hex(os.urandom(15))) data = dict( fullname = params['fullname'], name = params['name'], password1 = password, password2 = password, state = model.State.PENDING, email = params['email'], organization_request = params['organization-for-request'], reason_to_access = params['reason-to-access'] ) organization = model.Group.get(data['organization_request']) try: user_dict = logic.get_action('user_create')(context, data) context1 = { 'user': model.Session.query(model.User).filter_by(sysadmin=True).first().name } msg = "Dear Admin,\n\nA request for a new user account has been submitted:\nUsername: "******"\nName: " + data['fullname'] + "\nEmail: " + data['email'] + "\nOrganisation: " + organization.display_name + "\nReason for access: " + data['reason_to_access'] + "\n\nThis request can be approved or rejected at " + g.site_url + h.url_for(controller='ckanext.accessrequests.controller:AccessRequestsController', action='account_requests') mailer.mail_recipient('Admin', config.get('ckanext.accessrequests.approver_email'), 'Account request', msg) h.flash_success('Your request for access to the {0} has been submitted.'.format(config.get('ckan.site_title'))) except ValidationError, e: # return validation failures to the form errors = e.error_dict error_summary = e.error_summary return self.request_account(data, errors, error_summary)
def handle_submit(self, id): data = clean_dict(dict_fns.unflatten(tuplize_dict(parse_params( request.params)))) data['dataset_url'] = toolkit.url_for( controller='package', action='read', id=id, qualified=True ) package = get_action('package_show')(None, {'id': id}) self.fail_if_private(package, data['dataset_url']) # Comma separated config var to_addrs = config['ckanext.ands.support_emails'].split(',') subject = 'DataPortal Support: Request to publish dataset' body = base.render( 'package/doi_email.text', extra_vars=data) for email in to_addrs: mail_recipient('Dataportal support', email, subject, body) data['package_id'] = package['id'] data['user_id'] = c.userobj.id doi_request = DoiRequest(**data) Session.add(doi_request) Session.commit() h.flash_success("DOI Request sent") return toolkit.redirect_to(data['dataset_url'])
def _save_edit(self, id, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') data_dict['id'] = id if data_dict['password1'] and data_dict['password2']: identity = {'login': c.user, 'password': data_dict['old_password']} auth = authenticator.UsernamePasswordAuthenticator() if auth.authenticate(request.environ, identity) != c.user: raise UsernamePasswordError # MOAN: Do I really have to do this here? if 'activity_streams_email_notifications' not in data_dict: data_dict['activity_streams_email_notifications'] = False user = get_action('user_update')(context, data_dict) h.flash_success(_('Profile updated')) h.redirect_to(controller='user', action='read', id=user['name']) except NotAuthorized: abort(401, _('Unauthorized to edit user %s') % id) except NotFound, e: abort(404, _('User not found'))
def _package_after_update(self, context, pkg_dict): log.debug(u"Updating package {}".format(pkg_dict['name'])) if 'authors' in pkg_dict: update_authors(context, pkg_dict, pkg_dict['authors']) if 'oa_funder' in pkg_dict: update_oa_tag(context, pkg_dict, 'oa_funders', pkg_dict['oa_funder']) if 'oa_funding_program' in pkg_dict: update_oa_tag(context, pkg_dict, 'oa_funding_programs', pkg_dict['oa_funding_program']) update_ancestral_license(context, pkg_dict, pkg_dict['ancestral_license'] if 'ancestral_license' in pkg_dict else None) update_moderation_status(context['session'], pkg_dict['id'], pkg_dict['moderationStatus'] if 'moderationStatus' in pkg_dict else 'private', pkg_dict['moderationNotes'] if 'moderationNotes' in pkg_dict else '') if pkg_dict.get('state', 'active') == 'active' and not pkg_dict.get('private', False): orig_pkg_dict = toolkit.get_action('package_show')(context, {'id': pkg_dict['id']}) pkg_dict['metadata_created'] = orig_pkg_dict['metadata_created'] package_doi = get_package_doi(pkg_dict['id']) if not package_doi: package_doi = create_package_doi(pkg_dict) # TODO verify if crucial metadata has been changed and only then # send updates to DataCite. But the truth is that in our case # almost every change in metadata is crucial, so let's skip that # check for a while. if package_doi.published: update_package_doi(pkg_dict) h.flash_success(_('DataCite DOI metadata updated')) else: publish_package_doi(pkg_dict) h.flash_success(_('DataCite DOI has been created')) return pkg_dict
def post(self, id): context, user_dict = self._prepare(id) context[u'reset_password'] = True user_state = user_dict[u'state'] try: new_password = self._get_form_password() user_dict[u'password'] = new_password username = request.form.get(u'name') if (username is not None and username != u''): user_dict[u'name'] = username user_dict[u'reset_key'] = g.reset_key user_dict[u'state'] = model.State.ACTIVE logic.get_action(u'user_update')(context, user_dict) mailer.create_reset_key(context[u'user_obj']) h.flash_success(_(u'Your password has been reset.')) return h.redirect_to(u'home.index') except logic.NotAuthorized: h.flash_error(_(u'Unauthorized to edit user %s') % id) except logic.NotFound: h.flash_error(_(u'User not found')) except dictization_functions.DataError: h.flash_error(_(u'Integrity Error')) except logic.ValidationError as e: h.flash_error(u'%r' % e.error_dict) except ValueError as e: h.flash_error(text_type(e)) user_dict[u'state'] = user_state return base.render(u'user/perform_reset.html', { u'user_dict': user_dict })
def unfollow(package_type, id): """Stop following this dataset. """ context = { u'model': model, u'session': model.Session, u'user': g.user, u'auth_user_obj': g.userobj } data_dict = {u'id': id} try: get_action(u'unfollow_dataset')(context, data_dict) package_dict = get_action(u'package_show')(context, data_dict) id = package_dict['name'] except ValidationError as e: error_message = (e.message or e.error_summary or e.error_dict) h.flash_error(error_message) except (NotFound, NotAuthorized) as e: error_message = e.message h.flash_error(error_message) else: h.flash_success( _(u"You are no longer following {0}").format( package_dict[u'title'] ) ) return h.redirect_to(u'dataset.read', id=id)
def review(self, id): """ sends review notification to all journal admins """ context = self._context() try: tk.check_access('package_update', context, {'id': id}) except tk.NotAuthorized: tk.abort(403, 'Unauthorized') c.pkg_dict = tk.get_action('package_show')(context, {'id': id}) # avoid multiple notifications (eg. when someone calls review directly) if c.pkg_dict.get('dara_edawax_review', 'false') == 'true': h.flash_error("Package has already been sent to review") redirect(id) user_name = tk.c.userobj.fullname or tk.c.userobj.email admins = get_group_or_org_admin_ids(c.pkg_dict['owner_org']) addresses = map(lambda admin_id: model.User.get(admin_id).email, admins) note = n.review(addresses, user_name, id) if note: c.pkg_dict['dara_edawax_review'] = 'true' tk.get_action('package_update')(context, c.pkg_dict) h.flash_success('Notification to Editors sent.') else: h.flash_error('ERROR: Mail could not be sent. Please try again later or contact the site admin.') redirect(id)
def logged_in(self): # we need to set the language via a redirect lang = session.pop("lang", None) session.save() came_from = request.params.get("came_from", "") # we need to set the language explicitly here or the flash # messages will not be translated. i18n.set_lang(lang) if c.user: context = None data_dict = {"id": c.user} user_dict = get_action("user_show")(context, data_dict) h.flash_success(_("%s is now logged in") % user_dict["display_name"]) if came_from: return h.redirect_to(str(came_from)) return self.me() else: err = _("Login failed. Bad username or password.") if g.openid_enabled: err += _(" (Or if using OpenID, it hasn't been associated " "with a user account.)") if h.asbool(config.get("ckan.legacy_templates", "false")): h.flash_error(err) h.redirect_to(locale=lang, controller="user", action="login", came_from=came_from) else: return self.login(error=err)
def report_comment(self, dataset_id, issue_number, comment_id): dataset = self._before_dataset(dataset_id) if request.method == 'POST': if not c.user: msg = _('You must be logged in to report comments') toolkit.abort(401, msg) try: toolkit.get_action('issue_comment_report')( data_dict={ 'comment_id': comment_id, 'issue_number': issue_number, 'dataset_id': dataset_id } ) h.flash_success( _('Comment has been reported to an administrator') ) h.redirect_to('issues_show', dataset_id=dataset_id, issue_number=issue_number) except toolkit.ValidationError: toolkit.abort(404) except ReportAlreadyExists, e: h.flash_error(e.message) h.redirect_to('issues_show', dataset_id=dataset_id, issue_number=issue_number)
def trash(self): c.deleted_revisions = model.Session.query( model.Revision).filter_by(state=model.State.DELETED) c.deleted_packages = model.Session.query( model.Package).filter_by(state=model.State.DELETED) if not request.params or (len(request.params) == 1 and '__no_cache__' in request.params): return base.render('admin/trash.html') else: # NB: we repeat retrieval of of revisions # this is obviously inefficient (but probably not *that* bad) # but has to be done to avoid (odd) sqlalchemy errors (when doing # purge packages) of form: "this object already exists in the # session" msgs = [] if ('purge-packages' in request.params) or ('purge-revisions' in request.params): if 'purge-packages' in request.params: revs_to_purge = [] for pkg in c.deleted_packages: revisions = [x[0] for x in pkg.all_related_revisions] # ensure no accidental purging of other(non-deleted) # packages initially just avoided purging revisions # where non-deleted packages were affected # however this lead to confusing outcomes e.g. # we succesfully deleted revision in which package # was deleted (so package now active again) but no # other revisions problem = False for r in revisions: affected_pkgs = set(r.packages).\ difference(set(c.deleted_packages)) if affected_pkgs: msg = _('Cannot purge package %s as ' 'associated revision %s includes ' 'non-deleted packages %s') msg = msg % (pkg.id, r.id, [pkg.id for r in affected_pkgs]) msgs.append(msg) problem = True break if not problem: revs_to_purge += [r.id for r in revisions] model.Session.remove() else: revs_to_purge = [rev.id for rev in c.deleted_revisions] revs_to_purge = list(set(revs_to_purge)) for id in revs_to_purge: revision = model.Session.query(model.Revision).get(id) try: # TODO deleting the head revision corrupts the edit # page Ensure that whatever 'head' pointer is used # gets moved down to the next revision model.repo.purge_revision(revision, leave_record=False) except Exception, inst: msg = _('Problem purging revision %s: %s') % (id, inst) msgs.append(msg) h.flash_success(_('Purge complete')) else:
def after_update(self, context, pkg_dict): """ Dataset has been created / updated Check status of the dataset to determine if we should publish DOI to datacite network @param pkg_dict: @return: pkg_dict """ # Is this active and public? If so we need to make sure we have an active DOI if pkg_dict.get('state', 'active') == 'active' and not pkg_dict.get('private', False): package_id = pkg_dict['id'] # Load the original package, so we can determine if user has changed any fields orig_pkg_dict = get_action('package_show')(context, {'id': package_id}) # Metadata created isn't populated in pkg_dict - so copy from the original pkg_dict['metadata_created'] = orig_pkg_dict['metadata_created'] # Load the local DOI doi = get_doi(package_id) # If we don't have a DOI, create one # This could happen if the DOI module is enabled after a dataset has been creates if not doi: doi = create_unique_identifier(package_id) # Build the metadata dict to pass to DataCite service metadata_dict = self.build_metadata(pkg_dict, doi) # Perform some basic checks against the data - we require at the very least # title and author fields - they're mandatory in the DataCite Schema # This will only be an issue if another plugin has removed a mandatory field self.validate_metadata(metadata_dict) # Is this an existing DOI? Update it if doi.published: # Before updating, check if any of the metadata has been changed - otherwise # We end up sending loads of revisions to DataCite for minor edits # Load the current version orig_metadata_dict = self.build_metadata(orig_pkg_dict, doi) # Check if the two dictionaries are the same if cmp(orig_metadata_dict, metadata_dict) != 0: # Not the same, so we want to update the metadata update_doi(package_id, **metadata_dict) h.flash_success('DataCite DOI metadata updated') # TODO: If editing a dataset older than 5 days, create DOI revision # New DOI - publish to datacite else: h.flash_success('DataCite DOI created') publish_doi(package_id, **metadata_dict) return pkg_dict
def _edit_or_new(self, id, related_id, is_edit): """ Edit and New were too similar and so I've put the code together and try and do as much up front as possible. """ context = {"model": model, "session": model.Session, "user": c.user or c.author, "for_view": True} data_dict = {} if is_edit: tpl = "related/edit.html" auth_name = "related_update" auth_dict = {"id": related_id} action_name = "related_update" try: related = logic.get_action("related_show")(context, {"id": related_id}) except logic.NotFound: base.abort(404, _("Related item not found")) else: tpl = "related/new.html" auth_name = "related_create" auth_dict = {} action_name = "related_create" try: logic.check_access(auth_name, context, auth_dict) except logic.NotAuthorized: base.abort(401, base._("Not authorized")) try: c.pkg_dict = logic.get_action("package_show")(context, {"id": id}) except logic.NotFound: base.abort(404, _("Package not found")) data, errors, error_summary = {}, {}, {} if base.request.method == "POST": try: data = logic.clean_dict(df.unflatten(logic.tuplize_dict(logic.parse_params(base.request.params)))) if is_edit: data["id"] = related_id else: data["dataset_id"] = id data["owner_id"] = c.userobj.id related = logic.get_action(action_name)(context, data) if not is_edit: h.flash_success(_("Related item was successfully created")) else: h.flash_success(_("Related item was successfully updated")) h.redirect_to(controller="related", action="list", id=c.pkg_dict["name"]) except df.DataError: base.abort(400, _(u"Integrity Error")) except logic.ValidationError, e: errors = e.error_dict error_summary = e.error_summary
def send(self): if not 'email' in request.params: abort(400,_('Please provide an email address')) email = request.params['email'] row = {'email':email,'signedup': datetime.now().isoformat()} self.table.AddRecord(row) h.flash_success(_('Your email has been stored. Thank you for your interest.')) redirect('/')
def unfollow(self, id): '''Stop following this user.''' context = { 'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj } data_dict = {'id': id, 'include_num_followers': True} try: get_action('unfollow_user')(context, data_dict) user_dict = get_action('user_show')(context, data_dict) h.flash_success( _("You are no longer following {0}").format( user_dict['display_name'])) except (NotFound, NotAuthorized) as e: error_message = e.message h.flash_error(error_message) except ValidationError as e: error_message = (e.error_summary or e.message or e.error_dict) h.flash_error(error_message) h.redirect_to(controller='user', action='read', id=id)
def unfollow(id: str, group_type: str, is_organization: bool) -> Response: u'''Stop following this group.''' set_org(is_organization) context = cast(Context, { u'model': model, u'session': model.Session, u'user': g.user }) data_dict = {u'id': id} try: get_action(u'unfollow_group')(context, data_dict) group_dict = get_action(u'group_show')(context, data_dict) h.flash_success( _(u"You are no longer following {0}").format(group_dict['title'])) id = group_dict['name'] except ValidationError as e: error_message = (e.message or e.error_summary or e.error_dict) h.flash_error(error_message) except (NotFound, NotAuthorized) as e: error_message = e.message or '' h.flash_error(error_message) return h.redirect_to(u'group.read', id=id)
def comment_report_clear(dataset_id, issue_number, comment_id): dataset = _before_dataset(dataset_id) if request.method == 'POST': try: toolkit.get_action('issue_comment_report_clear')( data_dict={ 'comment_id': comment_id, 'issue_number': issue_number, 'dataset_id': dataset_id }) h.flash_success(_('Spam/abuse report cleared')) return p.toolkit.redirect_to('issues.show_issue', dataset_id=dataset_id, issue_number=issue_number) except toolkit.NotAuthorized: msg = _('You must be logged in to clear abuse reports').format( issue_number) toolkit.abort(401, msg) except toolkit.ValidationError: toolkit.abort(404) except toolkit.ObjectNotFound: toolkit.abort(404)
def remove_pipe(self, id, pipeline_id): assert id assert pipeline_id try: data_dict = {'id': id} context = { 'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj } check_access('package_update', context, data_dict) package = get_action('package_show')(context, data_dict) # id is most probably is package.name so we have to get actual id pipe = Pipelines(package['id'], pipeline_id).get() if not pipe: h.flash_error( _(u"Couldn't remove pipeline, because there is no such pipeline assigned to this dataset." )) base.redirect(h.url_for('pipe_assign', id=id)) else: pipe_id = pipe.pipeline_id pipe.delete() pipe.commit() h.flash_success( _(u'Pipeline removed from dataset successfully')) disable_schedules_for_pipe(pipe_id) except NotFound: abort(404, _(u'Dataset not found')) except NotAuthorized: abort( 401, _(u'User {user} not authorized to edit {id}').format( user=c.user, id=id)) base.redirect(h.url_for('pipe_assign', id=id))
def follow(self, id): '''Start following this user.''' context = { 'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj } data_dict = {'id': id} try: get_action('follow_user')(context, data_dict) user_dict = get_action('user_show')(context, data_dict) h.flash_success( _("You are now following {0}").format( user_dict['display_name'])) except ValidationError as e: error_message = (e.extra_msg or e.message or e.error_summary or e.error_dict) h.flash_error(error_message) except NotAuthorized as e: h.flash_error(e.extra_msg) h.redirect_to(controller='user', action='read', id=id)
def report_comment(self, dataset_id, issue_number, comment_id): dataset = self._before_dataset(dataset_id) if request.method == 'POST': if not c.user: msg = _('You must be logged in to report comments') toolkit.abort(401, msg) try: report_info = toolkit.get_action('issue_comment_report')( data_dict={ 'comment_id': comment_id, 'issue_number': issue_number, 'dataset_id': dataset_id }) if report_info: # we have this info if it is an admin msgs = [_('Report acknowledged.')] if report_info['abuse_status'] == \ issuemodel.AbuseStatus.abuse.value: msgs.append(_('Marked as abuse/spam.')) msgs.append( _('Comment is visible.' ) if report_info['visibility'] == 'visible' else _( 'Comment is invisible to normal users.')) h.flash_success(' '.join(msgs)) else: h.flash_success( _('Comment has been reported to an administrator')) p.toolkit.redirect_to('issues_show', dataset_id=dataset_id, issue_number=issue_number) except toolkit.ValidationError: toolkit.abort(404) except toolkit.ObjectNotFound: toolkit.abort(404) except ReportAlreadyExists, e: h.flash_error(e.message) p.toolkit.redirect_to('issues_show', dataset_id=dataset_id, issue_number=issue_number)
def unfollow(self, id): '''Stop following this group.''' context = { 'model': model, 'session': model.Session, 'user': c.user or c.author } data_dict = {'id': id} try: get_action('unfollow_group')(context, data_dict) group_dict = get_action('group_show')(context, data_dict) h.flash_success( _("You are no longer following {0}").format( group_dict['title'])) except ValidationError as e: error_message = (e.extra_msg or e.message or e.error_summary or e.error_dict) h.flash_error(error_message) except (NotFound, NotAuthorized) as e: error_message = e.extra_msg or e.message h.flash_error(error_message) h.redirect_to(controller='group', action='read', id=id)
def _save_new(self, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') captcha.check_recaptcha(request) user = get_action('user_create')(context, data_dict) except NotAuthorized: abort(403, _('Unauthorized to create user %s') % '') except NotFound as e: abort(404, _('User not found')) except DataError: abort(400, _(u'Integrity Error')) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.new(data_dict) except ValidationError as e: errors = e.error_dict error_summary = e.error_summary return self.new(data_dict, errors, error_summary) if not c.user: # log the user in programatically set_repoze_user(data_dict['name']) h.redirect_to(controller='user', action='me') else: # #1799 User has managed to register whilst logged in - warn user # they are not re-logged in as new user. h.flash_success(_('User "%s" is now registered but you are still ' 'logged in as "%s" from before') % (data_dict['name'], c.user)) if authz.is_sysadmin(c.user): # the sysadmin created a new user. We redirect him to the # activity page for the newly created user h.redirect_to(controller='user', action='activity', id=data_dict['name']) else: return render('user/logout_first.html')
def unfollow(id): u'''Stop following this user.''' context = { u'model': model, u'session': model.Session, u'user': g.user, u'auth_user_obj': g.userobj } data_dict = {u'id': id, u'include_num_followers': True} try: logic.get_action(u'unfollow_user')(context, data_dict) user_dict = logic.get_action(u'user_show')(context, data_dict) h.flash_success( _(u'You are no longer following {0}').format( user_dict[u'display_name'])) except (logic.NotFound, logic.NotAuthorized) as e: error_message = e.message h.flash_error(error_message) except logic.ValidationError as e: error_message = (e.error_summary or e.message or e.error_dict) h.flash_error(error_message) return h.redirect_to(u'user.read', id=id)
def manage(self): context = { 'model': model, 'session': model.Session, 'user': toolkit.c.user or toolkit.c.author } try: toolkit.check_access('sysadmin', context, {}) except toolkit.NotAuthorized: toolkit.abort(401, toolkit._('User not authorized to view page')) controller = 'ckanext.cadastaroles.controller:CadastaAdminController' username = toolkit.request.params.get('username') if toolkit.request.method == 'POST' and username: try: toolkit.get_action('cadasta_admin_create')(data_dict={ 'username': username }) except toolkit.NotAuthorized: toolkit.abort(401, toolkit._('Unauthorized to perform that action')) except toolkit.ObjectNotFound: helpers.flash_error( toolkit._("User '{0}' not found.").format(username)) except toolkit.ValidationError as e: helpers.flash_notice(e.error_summary) else: helpers.flash_success( toolkit._('The user is now a Cadasta Admin')) return toolkit.redirect_to( toolkit.url_for(controller=controller, action='manage')) cadasta_admin_list = toolkit.get_action('cadasta_admin_list')() return toolkit.render('admin/manage_cadasta_admin.html', extra_vars={ 'cadasta_admin_list': cadasta_admin_list, })
def post(self, id): context = {u'model': model} data_dict = logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params(request.form)))) data_dict[u'user'] = id try: token = logic.get_action(u'api_token_create')( context, data_dict )[u'token'] except logic.NotAuthorized: base.abort(403, _(u'Unauthorized to create API tokens.')) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary return self.get(id, data_dict, errors, error_summary) copy_btn = dom_tags.button(dom_tags.i(u'', { u'class': u'fa fa-copy' }), { u'type': u'button', u'class': u'btn btn-default btn-xs', u'data-module': u'copy-into-buffer', u'data-module-copy-value': ensure_str(token) }) h.flash_success( _( u"API Token created: <code style=\"word-break:break-all;\">" u"{token}</code> {copy}<br>" u"Make sure to copy it now, " u"you won't be able to see it again!" ).format(token=ensure_str(token), copy=copy_btn), True ) return h.redirect_to(u'user.api_tokens', id=id)
def request_reset(self): context = { 'model': model, 'session': model.Session, 'user': toolkit.c.user, 'auth_user_obj': toolkit.c.userobj } data_dict = {'id': toolkit.request.params.get('user')} try: toolkit.check_access('request_reset', context) except toolkit.NotAuthorized: toolkit.abort(401, toolkit._('Unauthorized to request reset password.')) if toolkit.request.method == 'POST': id = toolkit.request.params.get('user') context = {'model': model, 'user': toolkit.c.user} data_dict = {'id': id} user_obj = None try: toolkit.get_action('user_show')(context, data_dict) user_obj = context['user_obj'] except toolkit.ObjectNotFound: h.flash_error(toolkit._('No such user: %s') % id) if user_obj: try: mailer.send_reset_link(user_obj) h.flash_success( toolkit._('Please check your inbox for ' 'a reset code.')) h.redirect_to('/') except mailer.MailerException, e: h.flash_error( toolkit._('Could not send reset link: %s') % unicode(e))
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, e: h.flash_error( _('Cannot create new harvest jobs on inactive ' 'sources. First, please change the source status ' 'to \'active\'.'))
def follow(package_type, id): """Start following this dataset. """ context = { u'model': model, u'session': model.Session, u'user': g.user, u'auth_user_obj': g.userobj } data_dict = {u'id': id} try: get_action(u'follow_dataset')(context, data_dict) package_dict = get_action(u'package_show')(context, data_dict) except ValidationError as e: error_message = (e.message or e.error_summary or e.error_dict) h.flash_error(error_message) except NotAuthorized as e: h.flash_error(e.message) else: h.flash_success( _(u"You are now following {0}").format(package_dict[u'title'])) return h.redirect_to(u'dataset.read', id=id)
def delete_view(id): try: context = {'model': model, 'user': tk.c.user} context['clear_source'] = tk.request.params.get('clear', '').lower() in ( u'true', u'1', ) tk.get_action('harvest_source_delete')(context, {'id': id}) if context['clear_source']: h.flash_success(_('Harvesting source successfully cleared')) else: h.flash_success(_('Harvesting source successfully inactivated')) return h.redirect_to( h.url_for('{0}_admin'.format(DATASET_TYPE_NAME), id=id)) except tk.ObjectNotFound: return tk.abort(404, _('Harvest source not found')) except tk.NotAuthorized: return tk.abort(401, _not_auth_message())
def reauthor(self, id): """reset dataset to private and leave review state. Should also send email to author """ context = self._context() msg = tk.request.params.get('msg', '') c.pkg_dict = tk.get_action('package_show')(context, {'id': id}) creator_mail = model.User.get(c.pkg_dict['creator_user_id']).email note = n.reauthor(id, creator_mail, msg, context) if note: c.pkg_dict.update({ 'private': True, 'dara_edawax_review': 'reauthor' }) tk.get_action('package_update')(context, c.pkg_dict) h.flash_success( 'Notification sent. Dataset can now be re-edited by author') else: h.flash_error( 'ERROR: Mail could not be sent. Please try again later or contact the site admin.' ) redirect(id)
def generate_apikey(self, id): '''Cycle the API key of a user''' context = {'model': model, 'session': model.Session, 'user': c.user, 'auth_user_obj': c.userobj, } if id is None: if c.userobj: id = c.userobj.id else: abort(400, _('No user specified')) data_dict = {'id': id} try: result = get_action('user_generate_apikey')(context, data_dict) except NotAuthorized: abort(403, _('Unauthorized to edit user %s') % '') except NotFound: abort(404, _('User not found')) h.flash_success(_('Profile updated')) h.redirect_to(controller='user', action='read', id=result['name'])
def member_request_membership_cancel(context, data_dict): ''' Cancel ACTIVE organization membership (not request) from logged in user. Organization_id must be provided. :param organization_id: id of the organization :type member: string ''' logic.check_access('member_request_membership_cancel', context, data_dict) organization_id = data_dict.get("organization_id") query = model.Session.query(model.Member) \ .filter(model.Member.state == 'active') \ .filter(model.Member.table_name == 'user') \ .filter(model.Member.table_id == c.userobj.id) \ .filter(model.Member.group_id == organization_id) member = query.first() if not member or not member.group.is_organization: raise logic.NotFound flash_success(_("Membership cancelled")) return _process_request(context, organization_id, member, 'active')
def sync_irods(params, id): """ Fetches a resource from database with the same path as user specified and that matches an existing resource in CKAN. """ from irods import getFileUserMetadata, rcModAccessControl rev = model.repo.new_revision() conn = get_connection_from_params(params) resource = Resource.get(id) path = params['path'] extras = {} # Lets handle only resources with file names if resource.name: fname = "%s/%s" % (path, resource.name.split('/')[-1]) log.debug(fname) i = 0 access = rcModAccessControl() log.debug(access.getPath()) if conn: for met in getFileUserMetadata(conn, fname): i += 1 key, value, _ = met extras[key] = value resource.extras = extras Session.add(resource) conn.disconnect() model.repo.commit() rev.message = "Update from iRODS, matched file %s" % fname h.flash_success( "iRODS import to resource OK! Imported %s metadatas" % i) else: h.flash_error("Could not connect to iRODS!") else: h.flash_error("Resource is an URL, cannot import!") h.redirect_to(controller='package', action='resource_read', \ id=resource.resource_group.package.name, \ resource_id=resource.id)
def post_slack_form(self, action, context, **kwargs): if request.POST: data_dict = dict() data_dict['webhook_url'] = request.POST.get('webhook_url', '') data_dict['slack_channel'] = request.POST.get('slack_channel', '').lower() data_dict['organization_id'] = request.POST.get( 'organization_id', '') if action == constants.SLACK_CHANNEL_UPDATE: data_dict['id'] = kwargs['id'] try: toolkit.get_action(action)(context, data_dict) if action == constants.DATAREQUEST_REGISTER_SLACK: helpers.flash_success( toolkit. _('You have successfully added a slack notification channel' )) else: helpers.flash_success( toolkit. _('You have successfully updated a slack notification channel' )) toolkit.redirect_to('organization_channels', id=data_dict['organization_id']) except toolkit.ValidationError as e: log.warning(e) # Fill the fields that will display some information in the page c.slack_data = { 'organization_id': data_dict.get('organization_id', ''), 'webhook_url': data_dict.get('webhook_url', ''), 'slack_channel': data_dict.get('slack_channel', '') } c.errors = e.error_dict c.errors_summary = _get_errors_summary(c.errors)
def remove_showcase_admin(self): ''' Remove a user from the Showcase Admin list. ''' 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')) if 'cancel' in request.params: tk.redirect_to( controller='ckanext.showcase.controller:ShowcaseController', action='manage_showcase_admins') user_id = request.params['user'] if request.method == 'POST' and user_id: user_id = request.params['user'] try: get_action('ckanext_showcase_admin_remove')( data_dict={'username': user_id}) except NotAuthorized: abort(401, _('Unauthorized to perform that action')) except NotFound: h.flash_error(_('The user is not a Showcase Admin')) else: h.flash_success(_('The user is no longer a Showcase Admin')) return redirect(h.url_for( controller='ckanext.showcase.controller:ShowcaseController', action='manage_showcase_admins')) c.user_dict = get_action('user_show')(data_dict={'id': user_id}) c.user_id = user_id return render('admin/confirm_remove_showcase_admin.html')
def post(self, package_type, id): context = {u'model': model, u'user': g.user} try: form_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params(request.form)))) user = get_action(u'user_show')( context, {u'id': form_dict[u'username']} ) data_dict = { u'id': id, u'user_id': user[u'id'], u'capacity': form_dict[u'capacity'] } get_action(u'package_collaborator_create')( context, data_dict) except dict_fns.DataError: return base.abort(400, _(u'Integrity Error')) except NotAuthorized: message = _(u'Unauthorized to edit collaborators {}').format(id) return base.abort(401, _(message)) except NotFound as e: h.flash_error(_('User not found')) return h.redirect_to(u'dataset.new_collaborator', id=id) except ValidationError as e: h.flash_error(e.error_summary) return h.redirect_to(u'dataset.new_collaborator', id=id) else: h.flash_success(_(u'User added to collaborators')) return h.redirect_to(u'dataset.collaborators_read', id=id)
def post(self): if u'cancel' in request.form: return h.redirect_to(u'admin.trash') req_action = request.form.get(u'action') if req_action == u'all': d = { u'dataset_purge': self.deleted_packages, u'group_purge': self.deleted_groups, u'organization_purge': self.deleted_orgs } for action, deleted_entities in d.items(): for ent in deleted_entities: logic.get_action(action)({ u'user': g.user }, { u'id': ent.id }) model.Session.remove() h.flash_success(_(u'Massive purge complete')) elif req_action in (u'package', u'organization', u'group'): entities = self.deleted_entities[req_action] number = entities.count() for ent in entities: logic.get_action(ent.type + u'_purge')({ u'user': g.user }, { u'id': ent.id }) model.Session.remove() h.flash_success( _(self.messages[u'success'][req_action].format(number=number))) else: h.flash_error(_(u'Action not implemented.')) return h.redirect_to(u'admin.trash')
def request_editor_for_org(self, org_id): ''' user_email, name of user, username, organization name, list with org-admins emails, ''' try: msg = _('Please allow me to submit data to this organization ') user = hdx_h.hdx_get_user_info(c.user) context = { 'model': model, 'session': model.Session, 'user': c.user or c.author } org_admins = tk.get_action('member_list')(context, { 'id': org_id, 'capacity': 'admin', 'object_type': 'user' }) admins = [] for admin_tuple in org_admins: admin_id = admin_tuple[0] admins.append(hdx_h.hdx_get_user_info(admin_id)) admins_with_email = [admin for admin in admins if admin['email']] data_dict = { 'display_name': user['display_name'], 'name': user['name'], 'email': user['email'], 'organization': org_id, 'message': msg, 'admins': admins_with_email } tk.get_action('hdx_send_editor_request_for_org')(context, data_dict) h.flash_success(_('Message sent')) except hdx_mail.NoRecipientException, e: h.flash_error(_(str(e)))
def generate_apikey(id=None): u'''Cycle the API key of a user''' context = { u'model': model, u'session': model.Session, u'user': g.user, u'auth_user_obj': g.userobj, } if id is None: if g.userobj: id = g.userobj.id else: base.abort(400, _(u'No user specified')) data_dict = {u'id': id} try: result = logic.get_action(u'user_generate_apikey')(context, data_dict) except logic.NotAuthorized: base.abort(403, _(u'Unauthorized to edit user %s') % u'') except logic.NotFound: base.abort(404, _(u'User not found')) h.flash_success(_(u'Profile updated')) return h.redirect_to(u'user.read', id=result[u'name'])
def post(self): action = request.form.get('action') query_name = request.form.get('q_name') if not action or not query_name: return base.abort(409, _('Missing request parameter')) query = model.Session.query(SearchQuery).filter( SearchQuery.query == query_name).first() if query is None: return base.abort(404, _('Search query not found')) if action == 'delete': model.Session.delete(query) h.flash_success(_('The query has been removed')) elif action == 'update': value = request.form.get('q_value') if value: existing = SearchQuery.get(value) if existing and existing is not query: existing.count += query.count model.Session.delete(query) query = existing query.query = value h.flash_success(_('The query has been updated')) model.Session.commit() return toolkit.redirect_to('search_queries.index')
def post(self, org_id): actions = {'approve': 'approve_access', 'reject': 'reject_access'} act = request.form.get('bulk_action', '') reject_reason = request.form.get('reject-reason') request_ids = self._get_request_ids(request.form) if not request_ids: h.flash_error(_('Select at least one to proceed.')) return self._redirect(org_id) action = actions.get(act) if not action: h.flash_error(_('Action not implemented.')) return self._redirect(org_id) if action == 'reject_access' and not reject_reason: h.flash_error(_('Reject reason isn\'t provided')) return self._redirect(org_id) for _id in request_ids: try: logic.get_action(action)(self.context, { 'request_id': _id, 'user': g.user, 'reject_reason': reject_reason }) except logic.NotFound: abort(404, _('User or pkg not found')) except logic.NotAuthorized: abort(403, _('You need to be sysadmin or data custodian')) h.flash_success(_(self.messages[act].format(number=len(request_ids)))) return self._redirect(org_id)
def run_create(self, context, data_dict, resources_sheet, archive): """Dataset creating proccess.""" data_dict['name'] = munge_title_to_name(data_dict['title']) try: package_id_or_name_exists(data_dict['name'], context) except Invalid: pass else: counter = 0 while True: name = '{0}-{1}'.format(data_dict['name'], counter) try: package_id_or_name_exists(name, context) except Invalid: data_dict['name'] = name break counter += 1 result = self.create_dataset(context, data_dict, resources_sheet, archive) if result: h.flash_success('Dataset was created!')
def close_app(self, id): if c.userobj is None or not c.userobj.sysadmin: tk.redirect_to(tk.url_for(controller='user', action='login')) app = App.get_by_id(id=id) if not app: tk.redirect_to(tk.url_for('apps_activity')) form = CloseAppForm(tk.request.POST) if tk.request.POST: if form.validate(): form.populate_obj(app) app.status = "close" app.save() log.debug("Closed app") jobs.enqueue( send_notifications_on_change_app_status, [app, 'close', tk.request.environ.get('CKAN_LANG')]) flash_success(tk._('You successfully closed app')) tk.redirect_to(tk.url_for('apps_activity')) else: flash_error(tk._('You have errors in form')) log.debug("Validate errors: %s", form.errors) context = {'form': form} return self.__render('close_app.html', context)
def thread_add(self): if not c.userobj: tk.redirect_to( tk.url_for(controller='user', action='login', came_from=full_current_url())) if BannedUser.check_by_id(c.userobj): flash_error(tk._('You are banned')) tk.redirect_to(tk.url_for('forum_index')) form = CreateThreadForm(tk.request.POST) if tk.request.POST: if form.validate(): thread = tk.get_action('forum_create_thread')( { 'auth_user_obj': c.userobj }, form.data) log.debug("Form data is valid. Content: %s", thread.content) flash_success(tk._('You successfully create thread')) tk.redirect_to(thread.get_absolute_url()) else: flash_error(tk._('You have errors in form')) log.error("Validate errors: %s", form.errors) context = {'form': form, 'board_can_post': Board.filter_can_post()} return self.__render('create_thread.html', context)