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 _save_new(self, context): model = context['model'] context['ignore_auth'] = True 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) organization = get_action('inventory_organization_by_inventory_id')( context, {'id': data_dict['inventory_organization_id']}) password = str(random.SystemRandom().random()) data_dict['password1'] = password data_dict['password2'] = password data_dict['state'] = model.State.PENDING user = get_action('user_create')(context, data_dict) data_dict = { 'id': organization['id'], 'role': 'editor', 'username': user['name'] } logic.get_action('organization_member_create')(context, data_dict) except NotAuthorized: abort(401, _('Unauthorized to create user %s') % '') except NotFound, e: abort(404, _('User or organization not found'))
def member_new(self, id): context = {'model': model, 'session': model.Session, 'user': c.user or c.author} #self._check_access('group_delete', context, {'id': id}) try: if request.method == 'POST': data_dict = clean_dict(unflatten( tuplize_dict(parse_params(request.params)))) data_dict['id'] = id c.group_dict = self._action('group_member_create')(context, data_dict) self._redirect_to(controller='group', action='members', id=id) else: user = request.params.get('user') if user: c.user_dict = get_action('user_show')(context, {'id': user}) c.user_role = ckan.new_authz.users_role_for_group_or_org(id, user) or 'member' else: c.user_role = 'member' c.group_dict = self._action('group_show')(context, {'id': id}) c.roles = self._action('member_roles_list')(context, {}) except NotAuthorized: abort(401, _('Unauthorized to add member to group %s') % '') except NotFound: abort(404, _('Group not found')) return self._render_template('group/member_new.html')
def resource_edit(self, id, resource_id, data=None, errors=None, error_summary=None): if request.method == 'POST' and not data: data = data or clean_dict(unflatten(tuplize_dict(parse_params( request.POST)))) # we don't want to include save as it is part of the form del data['save'] context = {'model': model, 'session': model.Session, 'api_version': 3, 'for_edit': True, 'user': c.user or c.author, 'auth_user_obj': c.userobj} data['package_id'] = id try: if resource_id: data['id'] = resource_id get_action('resource_update')(context, data) else: get_action('resource_create')(context, data) except ValidationError, e: errors = e.error_dict error_summary = e.error_summary return self.resource_edit(id, resource_id, data, errors, error_summary) except NotAuthorized: abort(401, _('Unauthorized to edit this resource'))
def config(self): items = self._get_config_form_items() data = request.POST if 'save' in data: try: # really? data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params( request.POST, ignore_keys=CACHE_PARAMETERS)))) del data_dict['save'] data = logic.get_action('config_option_update')( {'user': c.user}, data_dict) except logic.ValidationError, e: errors = e.error_dict error_summary = e.error_summary vars = {'data': data, 'errors': errors, 'error_summary': error_summary, 'form_items': items} return base.render('admin/config.html', extra_vars=vars) h.redirect_to(controller='admin', action='config')
def new(self, data=None, errors=None, error_summary=None): """ This overrides the PackageController method to redirect to the show dataset view without having to go to the add data view. The difference is the inclusion of what the dataset type is. If the save param finish is included or any exceptions happen it will either abort or call the super new method. """ log.info('ckanext-bcgov.controllers.package:EDCPackageController.new overriding ckan\'s method') save_action = toolkit.request.params.get('save') data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params(toolkit.request.POST, ignore_keys=CACHE_PARAMETERS)))) log.debug('EDCPackageController data from toolkit.request.POST %s' % data_dict) is_an_update = data_dict.get('pkg_name', False) if data and 'type' in data and data['type']: package_type = data['type'] else: package_type = self._guess_package_type(True) if save_action == 'finish' and not is_an_update and package_type == 'Geographic': return self._new_dataset_only(package_type, data_dict, errors, error_summary) elif save_action == 'add_data' and not is_an_update and package_type == 'Geographic': return self._new_dataset_only(package_type, data_dict, errors, error_summary, 'resources') else: return super(EDCPackageController, self).new(data, errors, error_summary)
def _save_edit(self, id, context): try: data_dict = clean_dict(unflatten( tuplize_dict(parse_params(request.POST)))) self._check_data_dict(data_dict) context['message'] = data_dict.get('log_message', '') if not context['moderated']: context['pending'] = False data_dict['id'] = id pkg = get_action('package_update')(context, data_dict) if request.params.get('save', '') == 'Approve': update.make_latest_pending_package_active(context, data_dict) c.pkg = context['package'] c.pkg_dict = pkg if context['preview']: c.is_preview = True PackageSaver().render_package(pkg, context) c.preview = render('package/read_core.html') return self.edit(id, data_dict) self._form_save_redirect(pkg['name'], 'edit') except NotAuthorized: abort(401, _('Unauthorized to read package %s') % id) except NotFound, e: abort(404, _('Package not found'))
def post(self): try: req = request.form.copy() req.update(request.files.to_dict()) data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params( req, ignore_keys=CACHE_PARAMETERS)))) del data_dict['save'] data = logic.get_action(u'config_option_update')({ u'user': g.user }, data_dict) except logic.ValidationError as e: items = _get_config_options() data = request.form errors = e.error_dict error_summary = e.error_summary vars = dict( data=data, errors=errors, error_summary=error_summary, form_items=items, **items) return base.render(u'admin/config.html', extra_vars=vars) return h.redirect_to(u'admin.config')
def _add_users( self, group, parameters ): if not group: h.flash_error(_("There was a problem with your submission, " "please correct it and try again")) errors = {"reason": ["No reason was supplied"]} return self.apply(group.id, errors=errors, error_summary=action.error_summary(errors)) data_dict = logic.clean_dict(dict_func.unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) data_dict['id'] = group.id # Temporary fix for strange caching during dev l = data_dict['users'] for d in l: d['capacity'] = d.get('capacity','editor') context = { "group" : group, "schema": schema.default_group_schema(), "model": model, "session": model.Session } # Temporary cleanup of a capacity being sent without a name users = [d for d in data_dict['users'] if len(d) == 2] data_dict['users'] = users model.repo.new_revision() model_save.group_member_save(context, data_dict, 'users') model.Session.commit() h.redirect_to( controller='group', action='edit', id=group.name)
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 edit(self, dataset_id, comment_id): context = {'model': model, 'user': c.user} # Auth check to make sure the user can see this package data_dict = {'id': dataset_id} check_access('package_show', context, data_dict) try: c.pkg_dict = get_action('package_show')(context, {'id': dataset_id}) c.pkg = context['package'] except: abort(403) if request.method == 'POST': data_dict = clean_dict(unflatten( tuplize_dict(parse_params(request.POST)))) data_dict['id'] = comment_id success = False try: res = get_action('comment_update')(context, data_dict) success = True except ValidationError, ve: log.debug(ve) except Exception, e: log.debug(e) abort(403)
def _save_new(self, context): try: data_dict = logic.clean_dict(df.unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') captcha.check_recaptcha(request) # Extra: Create username from email email = data_dict.get('email', '') email_user = email.split('@')[0] name = re.sub('[^a-z0-9_\-]', '_', email_user) # Append num so it becames unique (search inside deleted as well) session = context['session'] user_names = model.User.search(name, session.query(model.User)).all() user_names = map(lambda u: u.name, user_names) while name in user_names: m = re.match('^(.*?)(\d+)$', name) if m: name = m.group(1) + str(int(m.group(2)) + 1) else: name = name + '2' data_dict['name'] = name user = get_action('user_create')(context, data_dict) except NotAuthorized: abort(401, _('Unauthorized to create user %s') % '') except NotFound, e: abort(404, _('User not found'))
def _add_or_reply(self, dataset_name): """ Allows the user to add a comment to an existing dataset """ context = {'model': model, 'user': c.user} # Auth check to make sure the user can see this package ctx = context ctx['id'] = dataset_name check_access('package_show', ctx, {'id': dataset_name}) try: c.pkg_dict = get_action('package_show')(context, {'id': dataset_name}) c.pkg = context['package'] except: abort(401, _('Unauthorized')) if not c.user: abort(401, _('Unauthorized')) errors = {} if request.method == 'POST': data_dict = clean_dict(unflatten( tuplize_dict(parse_params(request.POST)))) data_dict['parent_id'] = c.parent.id if c.parent else None data_dict['url'] = '/dataset/%s' % c.pkg.name data_dict['comment'] = data_dict['comment'][:5000] success = False try: res = get_action('comment_create')(context, data_dict) success = True except ValidationError, ve: errors = ve.error_dict except Exception, e: abort(401, _('Unauthorized'))
def _add_or_reply(self, dataset_id): """ Allows the user to add a comment to an existing dataset """ context = {'model': model, 'user': c.user} # Auth check to make sure the user can see this package data_dict = {'id': dataset_id} check_access('package_show', context, data_dict) try: c.pkg_dict = get_action('package_show')(context, {'id': dataset_id}) c.pkg = context['package'] except: abort(403) if request.method == 'POST': data_dict = clean_dict(unflatten( tuplize_dict(parse_params(request.POST)))) data_dict['parent_id'] = c.parent.id if c.parent else None data_dict['url'] = '/dataset/%s' % c.pkg.name success = False try: res = get_action('comment_create')(context, data_dict) success = True except ValidationError, ve: log.debug(ve) except Exception, e: log.debug(e) abort(403)
def new_resource(self, id, data=None, errors=None, error_summary=None): ''' Before creating a resource into CKAN, we request WSO2 ESB to add a subscription to the related Topic. ''' if request.method == 'POST' and not data: # Recogniced new resource form POST, extract variables. postdata = data or clean_dict(unflatten(tuplize_dict(parse_params(request.POST)))) if 'save' in postdata and 'url' in postdata: package_data = get_action('package_show')({'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj}, {'id': id}) topic = getTopicFromPackageData(package_data) # Add a new subscription for the topic named after the dataset, pointing to the URL given. brokerclient = getBrokerClient() try: result = brokerclient.subscribe(topic, postdata['url']) except Py4JJavaError, e: # Errors are propagated to the CKAN controller below to prevent new resource creation. error_message = str(e) if 'Error While Subscribing :Cannot initialize URI with empty parameters.' in error_message: error_message = _('Error While Subscribing: Cannot initialize URI with empty parameters.') if 'org.apache.axis2.AxisFault: Connection refused' in error_message: error_message = _('Error While Subscribing: Cannot connect to WSO2 ESB.') if errors and isinstance(errors, dict): errors.update({ 'error': error_message }) else: errors = { 'error': error_message } data = postdata error_summary = { _('WSO2 ESB'): error_message }
def new(self, data=None, errors=None, error_summary=None): package_type = self._guess_package_type(True) context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'extras_as_string': True, 'save': 'save' in request.params,} # Package needs to have a organization group in the call to check_access # and also to save it try: check_access('package_create',context) except NotAuthorized: abort(401, _('Unauthorized to create a package')) if context['save'] and not data: return self._save_new(context) data = data or clean_dict(unflatten(tuplize_dict(parse_params( request.params, ignore_keys=[CACHE_PARAMETER])))) c.resources_json = json.dumps(data.get('resources',[])) errors = errors or {} error_summary = error_summary or {} vars = {'data': data, 'errors': errors, 'error_summary': error_summary} c.errors_json = json.dumps(errors) self._setup_template_variables(context, {'id': id}) # TODO: This check is to maintain backwards compatibility with the old way of creating # custom forms. This behaviour is now deprecated. if hasattr(self, 'package_form'): c.form = render(self.package_form, extra_vars=vars) else: c.form = render(self._package_form(package_type=package_type), extra_vars=vars) return render( self._new_template(package_type))
def edit(self, id): """ Allows a user to edit an existing feed, potentially changing the URL and in doing so re-triggering validation of the feed. """ self._check_auth("feed_update") data, errors, error_summary = {}, {}, {} c.feed = feedlogic.get_feed(id) if not c.feed: base.abort(404, _("Feed {name} does not exist".format(name=id))) if base.request.method == "POST": try: data = logic.clean_dict( df.unflatten( logic.tuplize_dict( logic.parse_params(base.request.params) ))) feed = feedlogic.edit_feed(c.feed, data) h.redirect_to(controller=self.controller_path, action='read', id=feed.name) except feedmodels.FeedException: error = {'url': [u'Failed to load feed']} error_summary = {u'URL': u'Failed to load feed'} data = c.feed.as_dict() except df.DataError: base.abort(400, _(u'Integrity Error')) except logic.ValidationError, e: errors = e.error_dict error_summary = e.error_summary
def new(self): """ Allows the user to create a new feed and performs an initial fetch of the feed during validation. """ self._check_auth("feed_create") data, errors, error_summary = {}, {}, {} if base.request.method == "POST": try: dd = logic.clean_dict( df.unflatten( logic.tuplize_dict( logic.parse_params(base.request.params) ) ) ) feed = feedlogic.create_feed(dd) h.redirect_to( controller=self.controller_path, action='read', id=feed.name) except feedmodels.FeedException: error = {'url': [u'Failed to load feed']} error_summary = {u'URL': u'Failed to load feed'} data = dd except df.DataError: base.abort(400, _(u'Integrity Error')) except logic.ValidationError, e: errors = e.error_dict error_summary = e.error_summary
def getOGCServices(self): data = clean_dict(unflatten(tuplize_dict(parse_params(request.params)))) url = data.get('url', None) workspace = data.get('workspace', None) #USGIN MODEL WFS Validator add ? if workspace: workspace = workspace.replace('?', '') request_ogc = data.get('request', None) obj = None try: if not request_ogc or (request_ogc and request_ogc == "GetCapabilities"): if url and workspace: oResponse = requests.get(urllib.unquote_plus(url)) obj = oResponse.text #Replace the (#name_workspace) from NamespaceURI #obj = oResponse.text.replace('#'+workspace, '') #Add API URL in all links in order to make system go through it instead of hitting geoserver direclty to remove (#name_workspace) from all ogc services XML #siteUrl = config.get('ckan.site_url', None) #if siteUrl: # newServiceUrl = siteUrl+"/geoserver/get-ogc-services?url=" # match = re.compile('xlink:href=[\'|"](.*?)[\'"]') # matches = match.findall(obj) #loop through all occurrences and replace one by one to add the link API Ckan-Geoserver # for item in matches: # obj = obj.replace(item, newServiceUrl+urllib.quote_plus(item)+"&workspace="+workspace, 1) else: msg = 'An error ocurred: [Bad Request - Missing parameters]' abort(400, msg) elif request_ogc and request_ogc == "GetFeature": service = data.get('service', None) typename = data.get('typename', None) version = data.get('version', None) maxfeatures = data.get('maxfeatures', None) getFeatureURL = urllib.unquote_plus(url)+"?service=%s&request=%s&typename=%s&version=%s" % (service, request_ogc, typename, version) if maxfeatures: getFeatureURL = getFeatureURL+"&maxfeatures=%s" % maxfeatures oResponse = requests.get(getFeatureURL) onj = oResponse.text #Replace the (#name_workspace) from NamespaceURI #obj = oResponse.text.replace('#'+workspace, '') response.content_type = 'application/xml; charset=utf-8' response.headers['Content-Length'] = len(obj) return obj.encode('utf-8') except Exception, e: msg = 'An error ocurred: [%s]' % str(e) abort(500, msg)
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 validate_resource(self): """ Validate a resource to ensure that it conforms to NGDS standards. For ex: if a resource specifies that it conforms to a content model, that validation occurs here. """ data = clean_dict(unflatten(tuplize_dict(parse_params( request.params)))) return toolkit.get_action("validate_resource")(None, data)
def _hdx_edit(self, id, related_id, is_edit): #Taken from ckan/controller/related.py, paired down to just edits """ 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, 'auth_user_obj': c.userobj, 'for_view': True} data_dict = {} 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')) try: logic.check_access(auth_name, context, auth_dict) except logic.NotAuthorized: #If user can edit package, user can edit related item try: logic.check_access('package_update', {'model': model, 'session': model.Session, 'user': c.user or c.author, 'for_view': True, 'auth_user_obj': c.userobj}, {'id': id}) 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)))) data['id'] = related_id related = self.related_update(context, data) h.flash_success(_("Related item was successfully updated")) h.redirect_to( controller='ckanext.hdx_package.controllers.dataset_controller:DatasetController', action='read', 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_suggestion(self, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') c.form = data_dict['name'] captcha.check_recaptcha(request) # return base.render('suggest/form.html') except logic.NotAuthorized: base.abort(401, _('Not authorized to see this page')) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.suggest_form(data_dict) errors = {} error_summary = {} if (data_dict["email"] == ''): errors['email'] = [u'Missing Value'] error_summary['email'] = u'Missing value' if (data_dict["name"] == ''): errors['name'] = [u'Missing Value'] error_summary['name'] = u'Missing value' if (data_dict["suggestion"] == ''): errors['suggestion'] = [u'Missing Value'] error_summary['suggestion'] = u'Missing value' if len(errors) > 0: return self.suggest_form(data_dict, errors, error_summary) else: # #1799 User has managed to register whilst logged in - warn user # they are not re-logged in as new user. mail_to = config.get('email_to') recipient_name = 'CKAN Surrey' subject = 'CKAN - Dataset suggestion' body = 'Submitted by %s (%s)\n' % (data_dict["name"], data_dict["email"]) if (data_dict["category"] != ''): body += 'Category: %s' % data_dict["category"] body += 'Request: %s' % data_dict["suggestion"] try: mailer.mail_recipient(recipient_name, mail_to, subject, body) except mailer.MailerException: raise return base.render('suggest/suggest_success.html')
def post(self, id=None): context, id = self._prepare(id) if not context[u'save']: return self.get(id) if id in (g.userobj.id, g.userobj.name): current_user = True else: current_user = False old_username = g.userobj.name try: data_dict = logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params(request.form)))) except dictization_functions.DataError: base.abort(400, _(u'Integrity Error')) data_dict.setdefault(u'activity_streams_email_notifications', False) context[u'message'] = data_dict.get(u'log_message', u'') data_dict[u'id'] = id email_changed = data_dict[u'email'] != g.userobj.email if (data_dict[u'password1'] and data_dict[u'password2']) or email_changed: identity = { u'login': g.user, u'password': data_dict[u'old_password'] } auth = authenticator.UsernamePasswordAuthenticator() if auth.authenticate(request.environ, identity) != g.user: errors = { u'oldpassword': [_(u'Password entered was incorrect')] } error_summary = {_(u'Old Password'): _(u'incorrect password')} return self.get(id, data_dict, errors, error_summary) try: user = logic.get_action(u'user_update')(context, data_dict) except logic.NotAuthorized: base.abort(403, _(u'Unauthorized to edit user %s') % id) except logic.NotFound: base.abort(404, _(u'User not found')) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary return self.get(id, data_dict, errors, error_summary) h.flash_success(_(u'Profile updated')) resp = h.redirect_to(u'user.read', id=user[u'name']) if current_user and data_dict[u'name'] != old_username: # Changing currently logged in user's name. # Update repoze.who cookie to match set_repoze_user(data_dict[u'name'], resp) return resp
def render_map(self): """ This function is responsible for rendering the Map Search page. """ data = clean_dict(unflatten(tuplize_dict(parse_params(request.params)))) if data.get('query'): c.query = data['query'] return render('map/map.html')
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(401, _("Unauthorized to create user %s") % "") except NotFound, e: abort(404, _("User not found"))
def _save_new(self, context): try: data_dict = clean_dict(unflatten(tuplize_dict(parse_params(request.params)))) context["message"] = data_dict.get("log_message", "") group = get_action("group_create")(context, data_dict) h.redirect_to(controller="group", action="read", id=group["name"]) except NotAuthorized: abort(401, _("Unauthorized to read group %s") % "") except NotFound, e: abort(404, _("Package not found"))
def _send_contact(self, context): try: data_dict = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') c.form = data_dict['name'] captcha.check_recaptcha(request) #return base.render('suggest/form.html') except logic.NotAuthorized: base.abort(401, _('Not authorized to see this page')) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.contact_form(data_dict) errors = {} error_summary = {} if (data_dict["email"] == ''): errors['email'] = [u'Missing Value'] error_summary['email'] = u'Missing value' if (data_dict["name"] == ''): errors['name'] = [u'Missing Value'] error_summary['name'] = u'Missing value' if (data_dict["content"] == ''): errors['content'] = [u'Missing Value'] error_summary['content'] = u'Missing value' if len(errors) > 0: return self.suggest_form(data_dict, errors, error_summary) else: mail_to = config.get('email_to') recipient_name = 'CKAN' subject = 'CKAN - Contact/Question from visitor' body = 'Submitted by %s (%s)\n' % (data_dict["name"], data_dict["email"]) body += 'Request: %s' % data_dict["content"] try: mailer.mail_recipient(recipient_name, mail_to, subject, body) except mailer.MailerException: raise return base.render('contact/success.html')
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, e: abort(404, _('User not found'))
def post(self, id, resource_id, data=None, errors=None, error_summary=None): context = self._prepare() try: data = logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params(request.form)))) except dictization_functions.DataError: base.abort(400, _(u'Integrity Error')) view_dict = _process_post_data(data, resource_id) tags = view_dict.get('tags', '') if tags: for tag in tags.split(','): try: check_access('tag_show', context) tag_obj = get_action('tag_show')(context, {'id': tag}) except NotFound: check_access('tag_create', context) tag_obj = get_action('tag_create')(context, { 'name': tag, }) try: resource_view = \ get_action('resource_view_create')(context, view_dict) except logic.NotAuthorized: base.abort(403, _(u'Unauthorized to edit resource')) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary return self.get(id, resource_id, view_dict, errors, error_summary) return h.redirect_to(controller='package', action='resource_views', id=id, resource_id=resource_id)
def dictionary(self, id, resource_id): u'''data dictionary view: show/edit field labels and descriptions''' try: # resource_edit_base template uses these c.pkg_dict = get_action('package_show')(None, {'id': id}) c.resource = get_action('resource_show')(None, {'id': resource_id}) rec = get_action('datastore_search')(None, { 'resource_id': resource_id, 'limit': 0 }) except (ObjectNotFound, NotAuthorized): abort(404, _('Resource not found')) fields = [f for f in rec['fields'] if not f['id'].startswith('_')] if request.method == 'POST': data = dict_fns.unflatten( tuplize_dict(parse_params(request.params))) info = data.get(u'info') if not isinstance(info, list): info = [] info = info[:len(fields)] get_action('datastore_create')(None, { 'resource_id': resource_id, 'force': True, 'fields': [{ 'id': f['id'], 'type': f['type'], 'info': fi if isinstance(fi, dict) else {} } for f, fi in izip_longest(fields, info)] }) h.redirect_to( controller='ckanext.datastore.controller:DatastoreController', action='dictionary', id=id, resource_id=resource_id) return render('datastore/dictionary.html', extra_vars={'fields': fields})
def _add_users(self, group, parameters): from ckan.logic.schema import default_group_schema from ckan.logic.action import error_summary from ckan.lib.dictization.model_save import group_member_save if not group: h.flash_error(_("There was a problem with your submission, \ please correct it and try again")) errors = {"reason": ["No reason was supplied"]} return self.apply(group.id, errors=errors, error_summary=error_summary(errors)) data_dict = clean_dict(unflatten( tuplize_dict(parse_params(request.params)))) data_dict['id'] = group.id # Temporary fix for strange caching during dev l = data_dict['users'] for d in l: # Form javascript creates d['capacity'] == 'undefined' for # newly added users. # If javascript in users form is not working (such as in tests) # it will not create a capacity value. if 'capacity' not in d or d['capacity'] == 'undefined': # default to 'editor' d['capacity'] = 'editor' context = { "group" : group, "schema": default_group_schema(), "model": model, "session": model.Session } # Temporary cleanup of a capacity being sent without a name users = [d for d in data_dict['users'] if len(d) == 2] data_dict['users'] = users model.repo.new_revision() group_member_save(context, data_dict, 'users') model.Session.commit() h.redirect_to('/publisher/%s' % str(group.name))
def _save_edit(self, id, context): try: if id in (c.userobj.id, c.userobj.name): current_user = True else: current_user = False old_username = c.userobj.name 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 email_changed = data_dict['email'] != c.userobj.email if (data_dict['password1'] and data_dict['password2']) \ or email_changed: 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')) if current_user and data_dict['name'] != old_username: # Changing currently logged in user's name. # Update repoze.who cookie to match set_repoze_user(data_dict['name']) h.redirect_to(controller='user', action='read', id=user['name']) except NotAuthorized: abort(403, _('Unauthorized to edit user %s') % id) except NotFound, e: abort(404, _('User not found'))
def new(self, data=None, errors=None, error_summary=None): package_type = self._guess_package_type(True) context = { 'model': model, 'session': model.Session, 'user': c.user or c.author, 'extras_as_string': True, 'save': 'save' in request.params, } # Package needs to have a organization group in the call to check_access # and also to save it try: check_access('package_create', context) except NotAuthorized: abort(401, _('Unauthorized to create a package')) if context['save'] and not data: return self._save_new(context) data = data or clean_dict( unflatten( tuplize_dict( parse_params(request.params, ignore_keys=[CACHE_PARAMETER ])))) c.resources_json = json.dumps(data.get('resources', [])) errors = errors or {} error_summary = error_summary or {} vars = {'data': data, 'errors': errors, 'error_summary': error_summary} c.errors_json = json.dumps(errors) self._setup_template_variables(context, {'id': id}) # TODO: This check is to maintain backwards compatibility with the old way of creating # custom forms. This behaviour is now deprecated. if hasattr(self, 'package_form'): c.form = render(self.package_form, extra_vars=vars) else: c.form = render(self._package_form(package_type=package_type), extra_vars=vars) return render(self._new_template(package_type))
def __transform_to_data_dict(self, reqest_post): ''' Transform the POST body to data_dict usable by the actions ('package_update', 'package_create', ...) :param the POST body of the request object :return: a dict usable by the actions ''' # Initialize params dictionary data_dict = logic.parse_params(reqest_post) for key in data_dict.keys(): if 'template' in key: data_dict.pop(key, None) # Transform keys like 'group__0__key' to a tuple (like resources, extra fields, ...) try: data_dict = logic.tuplize_dict(data_dict) except Exception, e: log.error(e.message)
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 # 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 _save_attr_map_new(self, id, context): try: data_dict = clean_dict( dict_fns.unflatten( tuplize_dict(parse_params(tk.request.params)))) data_dict['metadata_standard_id'] = id data_dict.setdefault('is_key', False) tk.get_action('metadata_json_attr_map_create')(context, data_dict) tk.h.redirect_to('metadata_standard_attr_maps', id=id) except tk.NotAuthorized: tk.abort(403, tk._('Not authorized to create attribute mappings')) except tk.ObjectNotFound: tk.abort(404, tk._('Metadata standard not found')) except dict_fns.DataError: tk.abort(400, tk._(u'Integrity Error')) except tk.ValidationError, e: errors = e.error_dict error_summary = e.error_summary return self.attr_map_new(id, data_dict, errors, error_summary)
def initiate_search(self): """ This function is responsible for processing requests from the home page to initiate either a map search or library search with a search query that is provided to it. """ data = clean_dict(unflatten(tuplize_dict(parse_params( request.params)))) query = '' if 'query' in data: query = data['query'] if data['search-type'] == 'library': return redirect(h.url_for(controller='package', action='search', q=query, _tags_limit=0)) else: return redirect( h.url_for(controller='ckanext.ngds.ngdsui.controllers.home:HomeController', action='render_map', query=query))
def contact(self, name=None): """ This action allows users to create an issue by filling in a contact form. """ import ckan.model as model from ckanext.redmine.client import RedmineClient print name extra_vars = {"data": {}, "errors": {}} client = RedmineClient(name) c.categories = client.load_categories() c.name = name if request.method == 'POST': data = clean_dict( unflatten(tuplize_dict(parse_params(request.POST)))) context = { 'model': model, 'session': model.Session, 'user': c.user } # Create the issue with the data we were passed. try: newid = get_action('issue_create')(context, data) if newid is None: self._save_on_fail(data) h.flash_success( _('Thank you for contacting us'.format(newid))) else: h.flash_success( _('Thank you for contacting us, please quote #{0} in future correspondence' .format(newid))) h.redirect_to(str(data.get('referer', '/'))) except ValidationError, e: extra_vars["errors"] = e.error_dict extra_vars["error_summary"] = e.error_summary extra_vars["data"] = data c.category_id = data.get('category', '')
def request(self, data=None, errors=None, error_summary=None): ''' The functionality of sending emails with new user requests has been deprecated. Deprecated since hdx 0.3.5 ''' context = {'model': model, 'session': model.Session, 'user': c.user, 'request': 'request' in request.params} # try: # check_access('request_register', context) # except NotAuthorized: # abort(401, _('Unauthorized to request new registration.')) if context['request'] and not data: data = logic.clean_dict(unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) errors = dict() error_summary = dict() self._validate_form(data, errors) try: captcha.check_recaptcha(request) except captcha.CaptchaError: error_msg = _(u'Bad Captcha. Please try again.') error_summary['captcha'] = error_msg errors['captcha'] = [error_msg] if errors == {}: name = data['fullname'] email = data['email'] org = data['org'] reason = data['reason'] h.log.info( 'Request access for {name} ({email}) of {org} with reason: {reason}'.format(name=name, email=email, org=org, reason=reason)) try: # send_mail(name, email, org, reason) h.flash_success(_('We will check your request and we will send you an email!')) h.redirect_to('/') except mailer.MailerException, e: error_summary['sendError'] = _('Could not send request for access: %s') % unicode(e)
def _save_new(self, context): print(request.params) try: data_dict = logic.clean_dict( unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) self._validate_academic_email(request.params['email']) self._validate_eula_accept(data_dict) context['message'] = data_dict.get('log_message', '') captcha.check_recaptcha(request) user = get_action('user_create')(context, data_dict) self._after_signup(user) except NotAuthorized: abort(403, _('Unauthorized to create user %s') % '') except NotFound, e: abort(404, _('User not found'))
def follow_details(self, data=None, errors=None, error_summary=None): ''' Step 4: user follows key entities :param data: :param errors: :param error_summary: :return: ''' data_dict = logic.clean_dict(unflatten(logic.tuplize_dict(logic.parse_params(request.params)))) name = c.user or data_dict['id'] user_obj = model.User.get(name) user_id = user_obj.id context = {'model': model, 'session': model.Session, 'user': user_obj.name, 'auth_user_obj': c.userobj} try: ue_dict = self._get_ue_dict(user_id, user_model.HDX_ONBOARDING_FOLLOWS) get_action('user_extra_update')(context, ue_dict) except NotAuthorized: return OnbNotAuth except NotFound, e: return OnbUserNotFound
def _save_edit(self, id, context): try: data_dict = clean_dict(unflatten( tuplize_dict(parse_params(request.POST)))) self._check_data_dict(data_dict) context['message'] = data_dict.get('log_message', '') if not context['moderated']: context['pending'] = False data_dict['id'] = id pkg = get_action('package_update')(context, data_dict) if request.params.get('save', '') == 'Approve': get_action('make_latest_pending_package_active')(context, data_dict) c.pkg = context['package'] c.pkg_dict = pkg self._form_save_redirect(pkg['name'], 'edit') except NotAuthorized: abort(401, _('Unauthorized to read package %s') % id) except NotFound, e: abort(404, _('Package not found'))
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 RateDataset(self): context = { 'model': model, 'session': model.Session, 'user': c.user or c.author, 'auth_user_obj': c.userobj, 'for_view': True } rating = logic.clean_dict( df.unflatten( logic.tuplize_dict(logic.parse_params(base.request.params)))) logging.warning(rating) try: dataset_id = rating['dataset_id'] except KeyError: base.abort(400, _('Missing value') + ": dataset_id") try: rating = rating['value'] except KeyError: base.abort(400, _('Missing value') + ": value") if rating < 1: rating = 1 if rating > 5: rating = 5 if c.userobj == None: base.abort(401) data_dict = { 'rating': rating, 'dataset_id': dataset_id, 'user_id': c.userobj.id } if can_rate(c.userobj.id): new_rating(context, data_dict) return h.redirect_to(controller='package', action='read', id=dataset_id)
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 #HO Change to implement a pattern form passwords if data_dict['password2']: if plugin.search_password(data_dict['password2']): print("Password matched") else: print("It didn't") abort( 400, _('Password does not match the required pattern, needs at least one lower case, one upper case, a number and one of ' + plugin.special_chars)) print("checking password fits regex" + data_dict['password2']) #End of HO Change 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 _save_new(self, context, group_type=None): try: data_dict = clean_dict( unflatten(tuplize_dict(parse_params(request.params)))) data_dict['type'] = group_type or 'group' context['message'] = data_dict.get('log_message', '') data_dict['users'] = [{'name': c.user, 'capacity': 'admin'}] # Set approval status to pending data_dict['approval_status'] = 'pending' group = self._action('group_create')(context, data_dict) send_new_organization_email_to_admin() # Redirect to the appropriate _read route for the type of group h.redirect_to(group['type'] + '_read', id=group['name']) except (NotFound, NotAuthorized) as e: abort(404, _('Group not found')) except DataError: abort(400, _(u'Integrity Error')) except ValidationError as e: errors = e.error_dict error_summary = e.error_summary return self.new(data_dict, errors, error_summary)
def _save_new(self, context): try: data_dict = logic.clean_dict(dict_fns.unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) data_dict['group'] = data_dict['organization'] # TODO: Do we need info message at the UI level when e-mail could # not be sent? member = toolkit.get_action( 'member_request_create')(context, data_dict) helpers.redirect_to('organizations_index', id="newrequest", membership_id=member['id']) except dict_fns.DataError: abort(400, _(u'Integrity Error')) except logic.NotFound: abort(404, _('Item not found')) except logic.NotAuthorized: abort(405, self.not_auth_message) except logic.ValidationError, e: errors = e.error_dict error_summary = e.error_summary return self.new(errors, error_summary)
def _send_request(self, resource_id, context=None): try: data_dict = logic.clean_dict( unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) except logic.NotAuthorized: toolkit.abort(401, _('Not authorized to see this page')) try: data_dict['pkg_dict'] = toolkit.get_action('package_show')( context, { 'id': data_dict.get('package_name') }) except toolkit.ObjectNotFound: toolkit.abort(404, _('Package not found')) except: toolkit.abort(404, _('Exception retrieving package')) # Validation errors = {} error_summary = {} if data_dict.get('message', '') == '': errors['message'] = [u'Missing Value'] error_summary['message'] = u'Missing Value' if len(errors) > 0: return self.restricted_request_access_form( package_id=data_dict.get('package-name'), resource_id=data_dict.get('resource'), errors=errors, error_summary=error_summary, data=data_dict) error_summary = self._send_request_mail(data_dict, resource_id) return render('restricted/restricted_request_access_result.html', extra_vars={ 'data': data_dict, 'error_summary': error_summary, 'pkg_dict': data_dict.get('pkg_dict') })
def new(self, data=None, errors=None, error_summary=None): """ This overrides the PackageController method to redirect to the show dataset view without having to go to the add data view. The difference is the inclusion of what the dataset type is. If the save param finish is included or any exceptions happen it will either abort or call the super new method. """ log.info( 'ckanext-bcgov.controllers.package:EDCPackageController.new overriding ckan\'s method' ) save_action = toolkit.request.params.get('save') data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params(toolkit.request.POST, ignore_keys=CACHE_PARAMETERS)))) log.debug('EDCPackageController data from toolkit.request.POST %s' % data_dict) is_an_update = data_dict.get('pkg_name', False) if data and 'type' in data and data['type']: package_type = data['type'] else: package_type = self._guess_package_type(True) if save_action == 'finish' and not is_an_update and package_type == 'Geographic': return self._new_dataset_only(package_type, data_dict, errors, error_summary) elif save_action == 'add_data' and not is_an_update and package_type == 'Geographic': return self._new_dataset_only(package_type, data_dict, errors, error_summary, 'resources') else: return super(EDCPackageController, self).new(data, errors, error_summary)
def post(self, dataset_id): if not hasattr(toolkit.c, 'user') or not toolkit.c.user: return toolkit.abort(401, 'Unauthorized') context = {u'model': model, u'user': toolkit.c.user} try: form_dict = logic.clean_dict( dictization_functions.unflatten( logic.tuplize_dict(logic.parse_params( toolkit.request.form)))) user = toolkit.get_action('user_show')(context, { 'id': form_dict['username'] }) data_dict = { 'id': dataset_id, 'user_id': user['id'], 'capacity': form_dict['capacity'] } toolkit.get_action('dataset_collaborator_create')(context, data_dict) except dictization_functions.DataError: return toolkit.abort(400, _(u'Integrity Error')) except toolkit.NotAuthorized: message = u'Unauthorized to edit collaborators {0}'.format( dataset_id) return toolkit.abort(403, toolkit._(message)) except toolkit.ObjectNotFound: return toolkit.abort(404, toolkit._(u'Resource not found')) except toolkit.ValidationError as e: toolkit.h.flash_error(e.error_summary) else: toolkit.h.flash_success(toolkit._('User added to collaborators')) return toolkit.redirect_to(u'collaborators.read', dataset_id=dataset_id)
def publish_ogc(self): """ Publishes the resource content into Geoserver. Shape file and csv files are handled differently. """ context = { 'model': model, 'session': model.Session, 'user': c.user or c.author } data = clean_dict(unflatten(tuplize_dict(parse_params( request.params)))) res = Resource().get(data['id']) uri = Resource().get(data['id']).extras['content_model_version'] url = res.url if url[len(url) - 3:len(url)] == 'zip': action.shapefile_expose_as_layer(context, data) if url[len(url) - 3:len(url)] == 'csv': action.datastore_spatialize(context, data) return {'success': True, 'url': url}
def publish_ren(self): context = {'model': model, 'user': c.user} if request.method == 'POST': data_dict = clean_dict( unflatten(tuplize_dict(parse_params(request.POST)))) print data_dict try: c.pkg_dict = get_action('package_show')( context, { 'id': data_dict['dataset_id'] }) c.pkg = context['package'] get_action('comment_publish')(context, data_dict) extra_vars = {'pkg_name': c.pkg.name} except ValidationError, ve: log.debug(ve) except Exception, e: log.debug(e) abort(403)
def _save_new(self, context, group_type=None): """ Replacing GroupController._save_new because the redirect_to call is not wrapped. """ try: data_dict = clean_dict( dict_fns.unflatten( tuplize_dict(parse_params(tk.request.params)))) data_dict['type'] = 'metadata_collection' data_dict['infrastructures'] = self._parse_infrastructure_ids( data_dict.get('infrastructure_ids')) context['message'] = data_dict.get('log_message', '') data_dict['users'] = [{'name': tk.c.user, 'capacity': 'admin'}] group = tk.get_action('metadata_collection_create')(context, data_dict) tk.h.redirect_to('metadata_collection_read', id=group['name'], organization_id=tk.c.org_dict['name']) except tk.ObjectNotFound: tk.abort(404, tk._('Group not found')) except tk.NotAuthorized, e: tk.abort(403, e.message)
def config(self): items = self._get_config_form_items() data = request.POST if 'save' in data: try: # really? data_dict = logic.clean_dict( dict_fns.unflatten( logic.tuplize_dict( logic.parse_params(request.POST, ignore_keys=CACHE_PARAMETERS)))) del data_dict['save'] data = logic.get_action('config_option_update')({ 'user': c.user }, data_dict) except logic.ValidationError as e: errors = e.error_dict error_summary = e.error_summary vars = { 'data': data, 'errors': errors, 'error_summary': error_summary, 'form_items': items } return base.render('admin/config.html', extra_vars=vars) h.redirect_to(controller='admin', action='config') schema = logic.schema.update_configuration_schema() data = {} for key in schema: data[key] = config.get(key) vars = {'data': data, 'errors': {}, 'form_items': items} return base.render('admin/config.html', extra_vars=vars)
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 _save_edit(self, name_or_id, context): from ckan.lib.search import SearchIndexError log.debug('Package save request name: %s POST: %r', name_or_id, request.POST) try: data_dict = clean_dict( unflatten(tuplize_dict(parse_params(request.POST)))) context['message'] = data_dict.get('log_message', '') if not context['moderated']: context['pending'] = False data_dict['id'] = name_or_id pkg = get_action('package_update')(context, data_dict) if request.params.get('save', '') == 'Approve': get_action('make_latest_pending_package_active')(context, data_dict) c.pkg = context['package'] c.pkg_dict = pkg self._form_save_redirect(pkg['name'], 'edit') except NotAuthorized: abort(401, _('Unauthorized to read package %s') % id) except NotFound, e: abort(404, _('Dataset not found'))
def _save_new(self, context): came_from = request.params.get('came_from') try: data_dict = logic.clean_dict( unflatten( logic.tuplize_dict(logic.parse_params(request.params)))) context['message'] = data_dict.get('log_message', '') recaptcha_response = data_dict['g-recaptcha-response'] remote_ip = request.environ.get('REMOTE_ADDR', 'Unknown IP Address') if (_check_recaptcha(remote_ip, recaptcha_response)): user = get_action('user_create')(context, data_dict) else: error_msg = _(u'Bad Captcha. Please try again.') h.flash_error(error_msg) return self.new(data_dict) except NotAuthorized: abort(403, _('Unauthorized to create user %s') % '') except NotFound, e: abort(404, _('User not found'))
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) for times in range(3): msg = h.get_billing_api("api/RegisterAndSession/register", request_type='post', ckan_user_id=user.get('id'), ckan_user_name=user.get('name'), role=user.get('sysadmin')) decoded = json.loads(msg) if decoded['msg'] == 'error': log.debug('register as %r failed %r times - initial the session failed', user.get('name'), times) elif decoded['msg'] == 'success': break else: log.debug('register as %r failed %r times - api/RegisterAndSession/register return wrong data', user.get('name'), times) except NotAuthorized: abort(403, _('Unauthorized to create user %s') % '') except NotFound, e: abort(404, _('User not found'))