def authz(self, id): pkg = model.Package.get(id) if pkg is None: abort(404, gettext('Dataset not found')) # needed to add in the tab bar to the top of the auth page c.pkg = pkg c.pkgname = pkg.name c.pkgtitle = pkg.title try: context = { 'model': model, 'user': c.user or c.author, 'package': pkg } check_access('package_edit_permissions', context) c.authz_editable = True c.pkg_dict = get_action('package_show')(context, {'id': id}) except NotAuthorized: c.authz_editable = False if not c.authz_editable: abort( 401, gettext('User %r not authorized to edit %s ' 'authorizations') % (c.user, id)) roles = self._handle_update_of_authz(pkg) self._prepare_authz_info_for_render(roles) # c.related_count = len(pkg.related) return render('package/authz.html')
def authz(self, id): pkg = model.Package.get(id) if pkg is None: abort(404, gettext('Package not found')) c.pkg = pkg # needed to add in the tab bar to the top of the auth page c.pkgname = pkg.name c.pkgtitle = pkg.title try: context = { 'model': model, 'user': c.user or c.author, 'package': pkg } check_access('package_edit_permissions', context) c.authz_editable = True c.pkg_dict = get_action('package_show')(context, {'id': id}) except NotAuthorized: c.authz_editable = False if not c.authz_editable: abort( 401, gettext('User %r not authorized to edit %s authorizations') % (c.user, id)) current_uors = self._get_userobjectroles(id) self._handle_update_of_authz(current_uors, pkg) # get the roles again as may have changed user_object_roles = self._get_userobjectroles(id) self._prepare_authz_info_for_render(user_object_roles) return render('package/authz.html')
def search(self, ver=None, register=None): log.debug('search %s params: %r' % (register, request.params)) ver = ver or '1' # i.e. default to v1 if register == 'revision': since_time = None if request.params.has_key('since_id'): id = request.params['since_id'] if not id: return self._finish_bad_request( gettext(u'No revision specified')) rev = model.Session.query(model.Revision).get(id) if rev is None: return self._finish_not_found( gettext(u'There is no revision with id: %s') % id) since_time = rev.timestamp elif request.params.has_key('since_time'): since_time_str = request.params['since_time'] try: since_time = date_str_to_datetime(since_time_str) except ValueError, inst: return self._finish_bad_request('ValueError: %s' % inst) else: return self._finish_bad_request( gettext( "Missing search term ('since_id=UUID' or 'since_time=TIMESTAMP')" )) revs = model.Session.query( model.Revision).filter(model.Revision.timestamp > since_time) return self._finish_ok([rev.id for rev in revs])
def search(self, ver=None, register=None): log.debug('search %s params: %r' % (register, request.params)) ver = ver or '1' # i.e. default to v1 if register == 'revision': since_time = None if request.params.has_key('since_id'): id = request.params['since_id'] if not id: return self._finish_bad_request( gettext(u'No revision specified')) rev = model.Session.query(model.Revision).get(id) if rev is None: return self._finish_not_found( gettext(u'There is no revision with id: %s') % id) since_time = rev.timestamp elif request.params.has_key('since_time'): since_time_str = request.params['since_time'] try: since_time = date_str_to_datetime(since_time_str) except ValueError, inst: return self._finish_bad_request('ValueError: %s' % inst) else: return self._finish_bad_request( gettext("Missing search term ('since_id=UUID' or 'since_time=TIMESTAMP')")) revs = model.Session.query(model.Revision).filter(model.Revision.timestamp>since_time) return self._finish_ok([rev.id for rev in revs])
def authz(self, id): pkg = model.Package.get(id) if pkg is None: abort(404, gettext('Dataset not found')) c.pkg = pkg # needed to add in the tab bar to the top of the auth page c.pkgname = pkg.name c.pkgtitle = pkg.title try: context = {'model':model,'user':c.user or c.author, 'package':pkg} check_access('package_edit_permissions',context) c.authz_editable = True c.pkg_dict = get_action('package_show')(context, {'id': id}) except NotAuthorized: c.authz_editable = False if not c.authz_editable: abort(401, gettext('User %r not authorized to edit %s authorizations') % (c.user, id)) roles = self._handle_update_of_authz(pkg) self._prepare_authz_info_for_render(roles) c.num_followers = get_action('dataset_follower_count')(context, {'id':c.pkg.id}) self._setup_follow_button(context) # c.related_count = len(pkg.related) return render('package/authz.html')
def rate(self, id): package_name = id package = model.Package.get(package_name) if package is None: abort(404, gettext('Package Not Found')) self._clear_pkg_cache(package) rating = request.params.get('rating', '') if rating: try: ckan.rating.set_my_rating(c, package, rating) except ckan.rating.RatingValueException, e: abort(400, gettext('Rating value invalid'))
def list(self, ver=None, register=None, subregister=None, id=None): context = { 'model': model, 'session': model.Session, 'user': c.user, 'api_version': ver } log.debug('listing: %s' % context) action_map = { 'revision': 'revision_list', 'group': 'group_list', 'dataset': 'package_list', 'tag': 'tag_list', 'licenses': 'licence_list', ('dataset', 'relationships'): 'package_relationships_list', ('dataset', 'revisions'): 'package_revision_list', ('dataset', 'activity'): 'package_activity_list', ('group', 'activity'): 'group_activity_list', ('user', 'activity'): 'user_activity_list', ('activity', 'details'): 'activity_detail_list', } action = self._get_action_from_map(action_map, register, subregister) if not action: return self._finish_bad_request( gettext('Cannot list entity of this type: %s') % register) try: return self._finish_ok(action(context, {'id': id})) except NotFound, e: extra_msg = e.extra_msg return self._finish_not_found(extra_msg)
def create(self, ver=None, register=None, subregister=None, id=None, id2=None): action_map = { ('dataset', 'relationships'): get_action('package_relationship_create'), ('package', 'relationships'): get_action('package_relationship_create'), 'group': get_action('group_create_rest'), 'dataset': get_action('package_create_rest'), 'package': get_action('package_create_rest'), 'rating': get_action('rating_create'), } for type in model.PackageRelationship.get_all_types(): action_map[('dataset', type)] = get_action('package_relationship_create') action_map[('package', type)] = get_action('package_relationship_create') context = {'model': model, 'session': model.Session, 'user': c.user, 'api_version': ver} log.debug('create: %s' % (context)) try: request_data = self._get_request_data() data_dict = {'id': id, 'id2': id2, 'rel': subregister} data_dict.update(request_data) except ValueError, inst: return self._finish_bad_request( gettext('JSON Error: %s') % str(inst))
def action(self, logic_function): function = get_action(logic_function) if not function: log.error('Can\'t find logic function: %s' % logic_function) return self._finish_bad_request( gettext('Action name not known: %s') % str(logic_function)) context = {'model': model, 'session': model.Session, 'user': c.user} model.Session()._context = context return_dict = {'help': function.__doc__} try: request_data = self._get_request_data() except ValueError, inst: log.error('Bad request data: %s' % str(inst)) return self._finish_bad_request( gettext('JSON Error: %s') % str(inst))
def update(self, ver=None, register=None, subregister=None, id=None, id2=None): action_map = { 'dataset': 'package_update_rest', 'group': 'group_update_rest', ('dataset', 'relationships'): 'package_relationship_update_rest', } for type in model.PackageRelationship.get_all_types(): action_map[('dataset', type)] = 'package_relationship_update_rest' context = { 'model': model, 'session': model.Session, 'user': c.user, 'api_version': ver, 'id': id } log.debug('update: %s' % (context)) try: request_data = self._get_request_data() data_dict = {'id': id, 'id2': id2, 'rel': subregister} data_dict.update(request_data) except ValueError, inst: return self._finish_bad_request( gettext('JSON Error: %s') % str(inst))
def delete(self, ver=None, register=None, subregister=None, id=None, id2=None): action_map = { "group": "group_delete", "dataset": "package_delete", ("dataset", "relationships"): "package_relationship_delete_rest", } for type in model.PackageRelationship.get_all_types(): action_map[("dataset", type)] = "package_relationship_delete_rest" context = {"model": model, "session": model.Session, "user": c.user, "api_version": ver} data_dict = {"id": id, "id2": id2, "rel": subregister} log.debug("delete %s/%s/%s/%s" % (register, id, subregister, id2)) action = self._get_action_from_map(action_map, register, subregister) if not action: return self._finish_bad_request( gettext("Cannot delete entity of this type: %s %s") % (register, subregister or "") ) try: response_data = action(context, data_dict) return self._finish_ok(response_data) except NotAuthorized: return self._finish_not_authz() except NotFound, e: extra_msg = e.extra_msg return self._finish_not_found(extra_msg)
def authz(self, id): group = model.Group.get(id) if group is None: abort(404, _('Group not found')) c.groupname = group.name c.grouptitle = group.display_name try: context = { 'model': model, 'user': c.user or c.author, 'group': group } check_access('group_edit_permissions', context) c.authz_editable = True c.group = context['group'] except NotAuthorized: c.authz_editable = False if not c.authz_editable: abort( 401, gettext('User %r not authorized to edit %s authorizations') % (c.user, id)) current_uors = self._get_userobjectroles(id) self._handle_update_of_authz(current_uors, group) # get the roles again as may have changed user_object_roles = self._get_userobjectroles(id) self._prepare_authz_info_for_render(user_object_roles) return render('group/authz.html')
def list(self, ver=None, register=None, subregister=None, id=None): context = {"model": model, "session": model.Session, "user": c.user, "api_version": ver} log.debug("listing: %s" % context) action_map = { "revision": "revision_list", "group": "group_list", "dataset": "package_list", "tag": "tag_list", "licenses": "licence_list", ("dataset", "relationships"): "package_relationships_list", ("dataset", "revisions"): "package_revision_list", ("dataset", "activity"): "package_activity_list", ("group", "activity"): "group_activity_list", ("user", "activity"): "user_activity_list", ("activity", "details"): "activity_detail_list", } action = self._get_action_from_map(action_map, register, subregister) if not action: return self._finish_bad_request(gettext("Cannot list entity of this type: %s") % register) try: return self._finish_ok(action(context, {"id": id})) except NotFound, e: extra_msg = e.extra_msg return self._finish_not_found(extra_msg)
def action(self, logic_function): # FIXME this is a hack till ver gets passed api_version = 3 function = get_action(logic_function) if not function: log.error("Can't find logic function: %s" % logic_function) return self._finish_bad_request(gettext("Action name not known: %s") % str(logic_function)) context = {"model": model, "session": model.Session, "user": c.user, "api_version": api_version} model.Session()._context = context return_dict = {"help": function.__doc__} try: request_data = self._get_request_data() except ValueError, inst: log.error("Bad request data: %s" % str(inst)) return self._finish_bad_request(gettext("JSON Error: %s") % str(inst))
def list(self, ver=None, register=None, subregister=None, id=None): context = { 'model': model, 'session': model.Session, 'user': c.user, 'api_version': ver } log.debug('listing: %s' % context) action_map = { 'revision': get.revision_list, 'group': get.group_list, 'package': get.package_list, 'tag': get.tag_list, 'licenses': get.licence_list, ('package', 'relationships'): get.package_relationships_list, ('package', 'revisions'): get.package_revision_list, } action = action_map.get((register, subregister)) if not action: action = action_map.get(register) if not action: return self._finish_bad_request( gettext('Cannot list entity of this type: %s') % register) try: return self._finish_ok(action(context, {'id': id})) except NotFound, e: extra_msg = e.extra_msg return self._finish_not_found(extra_msg)
def show(self, ver=None, register=None, subregister=None, id=None, id2=None): action_map = { 'revision': get_action('revision_show'), 'group': get_action('group_show_rest'), 'tag': get_action('tag_show_rest'), 'dataset': get_action('package_show_rest'), 'package': get_action('package_show_rest'), ('dataset', 'relationships'): get_action('package_relationships_list'), ('package', 'relationships'): get_action('package_relationships_list'), } context = {'model': model, 'session': model.Session, 'user': c.user, 'api_version': ver} data_dict = {'id': id, 'id2': id2, 'rel': subregister} for type in model.PackageRelationship.get_all_types(): action_map[('dataset', type)] = get_action('package_relationships_list') action_map[('package', type)] = get_action('package_relationships_list') log.debug('show: %s' % context) action = action_map.get((register, subregister)) if not action: action = action_map.get(register) if not action: return self._finish_bad_request( gettext('Cannot read entity of this type: %s') % register) try: return self._finish_ok(action(context, data_dict)) except NotFound, e: extra_msg = e.extra_msg return self._finish_not_found(extra_msg)
def show(self, ver=None, register=None, subregister=None, id=None, id2=None): action_map = { 'revision': 'revision_show', 'group': 'group_show_rest', 'tag': 'tag_show_rest', 'dataset': 'package_show_rest', ('dataset', 'relationships'): 'package_relationships_list', } for type in model.PackageRelationship.get_all_types(): action_map[('dataset', type)] = 'package_relationships_list' context = { 'model': model, 'session': model.Session, 'user': c.user, 'api_version': ver } data_dict = {'id': id, 'id2': id2, 'rel': subregister} log.debug('show: %s' % context) action = self._get_action_from_map(action_map, register, subregister) if not action: return self._finish_bad_request( gettext('Cannot read entity of this type: %s') % register) try: return self._finish_ok(action(context, data_dict)) except NotFound, e: extra_msg = e.extra_msg return self._finish_not_found(extra_msg)
def list(self, ver=None, register=None, subregister=None, id=None): context = {'model': model, 'session': model.Session, 'user': c.user, 'api_version': ver} log.debug('listing: %s' % context) action_map = { 'revision': get_action('revision_list'), 'group': get_action('group_list'), 'dataset': get_action('package_list'), 'package': get_action('package_list'), 'tag': get_action('tag_list'), 'licenses': get_action('licence_list'), ('dataset', 'relationships'): get_action('package_relationships_list'), ('package', 'relationships'): get_action('package_relationships_list'), ('dataset', 'revisions'): get_action('package_revision_list'), ('package', 'revisions'): get_action('package_revision_list'), } action = action_map.get((register, subregister)) if not action: action = action_map.get(register) if not action: return self._finish_bad_request( gettext('Cannot list entity of this type: %s') % register) try: return self._finish_ok(action(context, {'id': id})) except NotFound, e: extra_msg = e.extra_msg return self._finish_not_found(extra_msg)
def delete(self, ver=None, register=None, subregister=None, id=None, id2=None): action_map = { ('dataset', 'relationships'): get_action('package_relationship_delete'), ('package', 'relationships'): get_action('package_relationship_delete'), 'group': get_action('group_delete'), 'dataset': get_action('package_delete'), 'package': get_action('package_delete'), } for type in model.PackageRelationship.get_all_types(): action_map[('dataset', type)] = get_action('package_relationship_delete') action_map[('package', type)] = get_action('package_relationship_delete') context = {'model': model, 'session': model.Session, 'user': c.user, 'api_version': ver} data_dict = {'id': id, 'id2': id2, 'rel': subregister} log.debug('delete %s/%s/%s/%s' % (register, id, subregister, id2)) action = action_map.get((register, subregister)) if not action: action = action_map.get(register) if not action: return self._finish_bad_request( gettext('Cannot delete entity of this type: %s %s') %\ (register, subregister or '')) try: response_data = action(context, data_dict) return self._finish_ok(response_data) except NotAuthorized: return self._finish_not_authz() except NotFound, e: extra_msg = e.extra_msg return self._finish_not_found(extra_msg)
def is_slug_valid(self): slug = request.params.get('slug') or '' slugtype = request.params.get('type') or '' if slugtype==u'package': response_data = dict(valid=not bool(package_exists(slug))) return self._finish_ok(response_data) if slugtype==u'group': response_data = dict(valid=not bool(group_exists(slug))) return self._finish_ok(response_data) return self._finish_bad_request(gettext('Bad slug type: %s') % slugtype)
def is_slug_valid(self): slug = request.params.get('slug') or '' slugtype = request.params.get('type') or '' if slugtype == u'package': response_data = dict(valid=not bool(package_exists(slug))) return self._finish_ok(response_data) if slugtype == u'group': response_data = dict(valid=not bool(group_exists(slug))) return self._finish_ok(response_data) return self._finish_bad_request( gettext('Bad slug type: %s') % slugtype)
def authz(self, id): pkg = model.Package.get(id) if pkg is None: abort(404, gettext("Dataset not found")) c.pkg = pkg # needed to add in the tab bar to the top of the auth page c.pkgname = pkg.name c.pkgtitle = pkg.title try: context = {"model": model, "user": c.user or c.author, "package": pkg} check_access("package_edit_permissions", context) c.authz_editable = True c.pkg_dict = get_action("package_show")(context, {"id": id}) except NotAuthorized: c.authz_editable = False if not c.authz_editable: abort(401, gettext("User %r not authorized to edit %s authorizations") % (c.user, id)) roles = self._handle_update_of_authz(pkg) self._prepare_authz_info_for_render(roles) return render("package/authz.html")
def action(self, logic_function): function = get_action(logic_function) context = {'model': model, 'session': model.Session, 'user': c.user} model.Session()._context = context return_dict = {'help': function.__doc__} try: request_data = self._get_request_data() except ValueError, inst: return self._finish_bad_request( gettext('JSON Error: %s') % str(inst))
def authz(self, id): pkg = model.Package.get(id) if pkg is None: abort(404, gettext('Package not found')) c.pkg = pkg # needed to add in the tab bar to the top of the auth page c.pkgname = pkg.name c.pkgtitle = pkg.title try: context = {'model':model,'user':c.user or c.author, 'package':pkg} check_access('package_edit_permissions',context) c.authz_editable = True except NotAuthorized: c.authz_editable = False if not c.authz_editable: abort(401, gettext('User %r not authorized to edit %s authorizations') % (c.user, id)) current_uors = self._get_userobjectroles(id) self._handle_update_of_authz(current_uors, pkg) # get the roles again as may have changed user_object_roles = self._get_userobjectroles(id) self._prepare_authz_info_for_render(user_object_roles) return render('package/authz.html')
def delete(self, ver=None, register=None, subregister=None, id=None, id2=None): action_map = { ('dataset', 'relationships'): get_action('package_relationship_delete'), ('package', 'relationships'): get_action('package_relationship_delete'), 'group': get_action('group_delete'), 'dataset': get_action('package_delete'), 'package': get_action('package_delete'), } for type in model.PackageRelationship.get_all_types(): action_map[('dataset', type)] = get_action('package_relationship_delete') action_map[('package', type)] = get_action('package_relationship_delete') context = { 'model': model, 'session': model.Session, 'user': c.user, 'api_version': ver } data_dict = {'id': id, 'id2': id2, 'rel': subregister} log.debug('delete %s/%s/%s/%s' % (register, id, subregister, id2)) action = action_map.get((register, subregister)) if not action: action = action_map.get(register) if not action: return self._finish_bad_request( gettext('Cannot delete entity of this type: %s %s') %\ (register, subregister or '')) try: response_data = action(context, data_dict) return self._finish_ok(response_data) except NotAuthorized: return self._finish_not_authz() except NotFound, e: extra_msg = e.extra_msg return self._finish_not_found(extra_msg)
def update(self, ver=None, register=None, subregister=None, id=None, id2=None): action_map = { "dataset": "package_update_rest", "group": "group_update_rest", ("dataset", "relationships"): "package_relationship_update_rest", } for type in model.PackageRelationship.get_all_types(): action_map[("dataset", type)] = "package_relationship_update_rest" context = {"model": model, "session": model.Session, "user": c.user, "api_version": ver, "id": id} log.debug("update: %s" % (context)) try: request_data = self._get_request_data() data_dict = {"id": id, "id2": id2, "rel": subregister} data_dict.update(request_data) except ValueError, inst: return self._finish_bad_request(gettext("JSON Error: %s") % str(inst))
def authz(self, id): group = model.Group.get(id) if group is None: abort(404, _('Group not found')) c.groupname = group.name c.grouptitle = group.display_name try: context = {'model':model,'user':c.user or c.author, 'group':group} check_access('group_edit_permissions',context) c.authz_editable = True c.group = context['group'] except NotAuthorized: c.authz_editable = False if not c.authz_editable: abort(401, gettext('User %r not authorized to edit %s authorizations') % (c.user, id)) roles = self._handle_update_of_authz(group) self._prepare_authz_info_for_render(roles) return render('group/authz.html')
def authz(self, id): group = model.Group.get(id) if group is None: abort(404, _("Group not found")) c.groupname = group.name c.grouptitle = group.display_name try: context = {"model": model, "user": c.user or c.author, "group": group} check_access("group_edit_permissions", context) c.authz_editable = True c.group = context["group"] except NotAuthorized: c.authz_editable = False if not c.authz_editable: abort(401, gettext("User %r not authorized to edit %s authorizations") % (c.user, id)) roles = self._handle_update_of_authz(group) self._prepare_authz_info_for_render(roles) return render("group/authz.html")
def show(self, ver=None, register=None, subregister=None, id=None, id2=None): action_map = { "revision": "revision_show", "group": "group_show_rest", "tag": "tag_show_rest", "dataset": "package_show_rest", ("dataset", "relationships"): "package_relationships_list", } for type in model.PackageRelationship.get_all_types(): action_map[("dataset", type)] = "package_relationships_list" context = {"model": model, "session": model.Session, "user": c.user, "api_version": ver} data_dict = {"id": id, "id2": id2, "rel": subregister} log.debug("show: %s" % context) action = self._get_action_from_map(action_map, register, subregister) if not action: return self._finish_bad_request(gettext("Cannot read entity of this type: %s") % register) try: return self._finish_ok(action(context, data_dict)) except NotFound, e: extra_msg = e.extra_msg return self._finish_not_found(extra_msg)
log.error("Can't find logic function: %s" % logic_function) return self._finish_bad_request(gettext("Action name not known: %s") % str(logic_function)) context = {"model": model, "session": model.Session, "user": c.user, "api_version": api_version} model.Session()._context = context return_dict = {"help": function.__doc__} try: request_data = self._get_request_data() except ValueError, inst: log.error("Bad request data: %s" % str(inst)) return self._finish_bad_request(gettext("JSON Error: %s") % str(inst)) if not isinstance(request_data, dict): # this occurs if request_data is blank log.error("Bad request data - not dict: %r" % request_data) return self._finish_bad_request( gettext("Bad request data: %s") % "Request data JSON decoded to %r but " "it needs to be a dictionary." % request_data ) try: result = function(context, request_data) return_dict["success"] = True return_dict["result"] = result except DataError, e: log.error("Format incorrect: %s - %s" % (e.error, request_data)) # TODO make better error message return self._finish(400, _(u"Integrity Error") + ": %s - %s" % (e.error, request_data)) except NotAuthorized: return_dict["error"] = {"__type": "Authorization Error", "message": _("Access denied")} return_dict["success"] = False return self._finish(403, return_dict, content_type="json") except NotFound, e:
def _get_search_params(cls, request_params): if request_params.has_key('qjson'): try: params = json.loads(request_params['qjson'], encoding='utf8') except ValueError, e: raise ValueError, gettext('Malformed qjson value') + ': %r' % e
def _get_search_params(cls, request_params): if request_params.has_key("qjson"): try: params = json.loads(request_params["qjson"], encoding="utf8") except ValueError, e: raise ValueError, gettext("Malformed qjson value") + ": %r" % e
def authz(self, id): pkg = model.Package.get(id) if pkg is None: abort(404, gettext('Package not found')) c.pkgname = pkg.name c.pkgtitle = pkg.title c.authz_editable = self.authorizer.am_authorized(c, model.Action.EDIT_PERMISSIONS, pkg) if not c.authz_editable: abort(401, gettext('User %r not authorized to edit %s authorizations') % (c.user, id)) # Three different ways of getting the list of userobjectroles for this package. # They all take a frighteningly long time to retrieve # the data, but I can't tell how they'll scale. On a large dataset it might # be worth working out which is quickest, so I've made a function for # ease of changing the query. def get_userobjectroles(): # we already have a pkg variable in scope, but I found while testing # that it occasionally mysteriously loses its value! Redefine it # here. pkg = model.Package.get(id) # dread's suggestion for 'get all userobjectroles for this package': uors = model.Session.query(model.PackageRole).join('package').filter_by(name=pkg.name).all() # rgrp's version: # uors = model.Session.query(model.PackageRole).filter_by(package=pkg) # get them all and filter in python: # uors = [uor for uor in model.Session.query(model.PackageRole).all() if uor.package==pkg] return uors def action_save_form(users_or_authz_groups): # The permissions grid has been saved # which is a grid of checkboxes named user$role rpi = request.params.items() # The grid passes us a list of the users/roles that were displayed submitted = [ a for (a,b) in rpi if (b == u'submitted')] # and also those which were checked checked = [ a for (a,b) in rpi if (b == u'on')] # from which we can deduce true/false for each user/role combination # that was displayed in the form table_dict={} for a in submitted: table_dict[a]=False for a in checked: table_dict[a]=True # now we'll split up the user$role strings to make a dictionary from # (user,role) to True/False, which tells us what we need to do. new_user_role_dict={} for (ur,val) in table_dict.items(): u,r = ur.split('$') new_user_role_dict[(u,r)] = val # we get the current user/role assignments # and make a dictionary of them current_uors = get_userobjectroles() if users_or_authz_groups=='users': current_users_roles = [( uor.user.name, uor.role) for uor in current_uors if uor.user] elif users_or_authz_groups=='authz_groups': current_users_roles = [( uor.authorized_group.name, uor.role) for uor in current_uors if uor.authorized_group] else: assert False, "shouldn't be here" current_user_role_dict={} for (u,r) in current_users_roles: current_user_role_dict[(u,r)]=True # and now we can loop through our dictionary of desired states # checking whether a change needs to be made, and if so making it # Here we check whether someone is already assigned a role, in order # to avoid assigning it twice, or attempting to delete it when it # doesn't exist. Otherwise problems can occur. if users_or_authz_groups=='users': for ((u,r), val) in new_user_role_dict.items(): if val: if not ((u,r) in current_user_role_dict): model.add_user_to_role(model.User.by_name(u),r,pkg) else: if ((u,r) in current_user_role_dict): model.remove_user_from_role(model.User.by_name(u),r,pkg) elif users_or_authz_groups=='authz_groups': for ((u,r), val) in new_user_role_dict.items(): if val: if not ((u,r) in current_user_role_dict): model.add_authorization_group_to_role(model.AuthorizationGroup.by_name(u),r,pkg) else: if ((u,r) in current_user_role_dict): model.remove_authorization_group_from_role(model.AuthorizationGroup.by_name(u),r,pkg) else: assert False, "shouldn't be here" # finally commit the change to the database model.repo.commit_and_remove() h.flash_success("Changes Saved") def action_add_form(users_or_authz_groups): # The user is attempting to set new roles for a named user new_user = request.params.get('new_user_name') # this is the list of roles whose boxes were ticked checked_roles = [ a for (a,b) in request.params.items() if (b == u'on')] # this is the list of all the roles that were in the submitted form submitted_roles = [ a for (a,b) in request.params.items() if (b == u'submitted')] # from this we can make a dictionary of the desired states # i.e. true for the ticked boxes, false for the unticked desired_roles = {} for r in submitted_roles: desired_roles[r]=False for r in checked_roles: desired_roles[r]=True # again, in order to avoid either creating a role twice or deleting one which is # non-existent, we need to get the users' current roles (if any) current_uors = get_userobjectroles() if users_or_authz_groups=='users': current_roles = [uor.role for uor in current_uors if ( uor.user and uor.user.name == new_user )] user_object = model.User.by_name(new_user) if user_object==None: # The submitted user does not exist. Bail with flash message h.flash_error('unknown user:'******'authz_groups': current_roles = [uor.role for uor in current_uors if ( uor.authorized_group and uor.authorized_group.name == new_user )] user_object = model.AuthorizationGroup.by_name(new_user) if user_object==None: # The submitted user does not exist. Bail with flash message h.flash_error('unknown authorization group:' + str (new_user)) else: # Whenever our desired state is different from our current state, change it. for (r,val) in desired_roles.items(): if val: if (r not in current_roles): model.add_authorization_group_to_role(user_object, r, pkg) else: if (r in current_roles): model.remove_authorization_group_from_role(user_object, r, pkg) h.flash_success("Authorization Group Added") else: assert False, "shouldn't be here" # and finally commit all these changes to the database model.repo.commit_and_remove() # In the event of a post request, work out which of the four possible actions # is to be done, and do it before displaying the page if 'add' in request.POST: action_add_form('users') if 'authz_add' in request.POST: action_add_form('authz_groups') if 'save' in request.POST: action_save_form('users') if 'authz_save' in request.POST: action_save_form('authz_groups') # ================= # Display the page # Find out all the possible roles. At the moment, any role can be # associated with any object, so that's easy: possible_roles = model.Role.get_all() # get the list of users who have roles on this object, with their roles uors = get_userobjectroles() # uniquify and sort users = sorted(list(set([uor.user.name for uor in uors if uor.user]))) authz_groups = sorted(list(set([uor.authorized_group.name for uor in uors if uor.authorized_group]))) # make a dictionary from (user, role) to True, False users_roles = [( uor.user.name, uor.role) for uor in uors if uor.user] user_role_dict={} for u in users: for r in possible_roles: if (u,r) in users_roles: user_role_dict[(u,r)]=True else: user_role_dict[(u,r)]=False # and similarly make a dictionary from (authz_group, role) to True, False authz_groups_roles = [( uor.authorized_group.name, uor.role) for uor in uors if uor.authorized_group] authz_groups_role_dict={} for u in authz_groups: for r in possible_roles: if (u,r) in authz_groups_roles: authz_groups_role_dict[(u,r)]=True else: authz_groups_role_dict[(u,r)]=False # pass these variables to the template for rendering c.roles = possible_roles c.users = users c.user_role_dict = user_role_dict c.authz_groups = authz_groups c.authz_groups_role_dict = authz_groups_role_dict return render('package/authz.html')
'user': c.user, 'api_version': api_version } model.Session()._context = context return_dict = {'help': function.__doc__} try: request_data = self._get_request_data() except ValueError, inst: log.error('Bad request data: %s' % str(inst)) return self._finish_bad_request( gettext('JSON Error: %s') % str(inst)) if not isinstance(request_data, dict): # this occurs if request_data is blank log.error('Bad request data - not dict: %r' % request_data) return self._finish_bad_request( gettext('Bad request data: %s') % \ 'Request data JSON decoded to %r but ' \ 'it needs to be a dictionary.' % request_data) try: result = function(context, request_data) return_dict['success'] = True return_dict['result'] = result except DataError, e: log.error('Format incorrect: %s - %s' % (e.error, request_data)) #TODO make better error message return self._finish(400, _(u'Integrity Error') + \ ': %s - %s' % (e.error, request_data)) except NotAuthorized: return_dict['error'] = { '__type': 'Authorization Error', 'message': _('Access denied')
def authz(self, id): group = model.Group.get(id) if group is None: abort(404, _('Group not found')) c.groupname = group.name c.grouptitle = group.display_name c.authz_editable = self.authorizer.am_authorized(c, model.Action.EDIT_PERMISSIONS, group) if not c.authz_editable: abort(401, gettext('User %r not authorized to edit %s authorizations') % (c.user, id)) #see package.py for comments def get_userobjectroles(): group = model.Group.get(id) uors = model.Session.query(model.GroupRole).join('group').filter_by(name=group.name).all() return uors def action_save_form(users_or_authz_groups): # The permissions grid has been saved # which is a grid of checkboxes named user$role rpi = request.params.items() # The grid passes us a list of the users/roles that were displayed submitted = [ a for (a,b) in rpi if (b == u'submitted')] # and also those which were checked checked = [ a for (a,b) in rpi if (b == u'on')] # from which we can deduce true/false for each user/role combination # that was displayed in the form table_dict={} for a in submitted: table_dict[a]=False for a in checked: table_dict[a]=True # now we'll split up the user$role strings to make a dictionary from # (user,role) to True/False, which tells us what we need to do. new_user_role_dict={} for (ur,val) in table_dict.items(): u,r = ur.split('$') new_user_role_dict[(u,r)] = val # we get the current user/role assignments # and make a dictionary of them current_uors = get_userobjectroles() if users_or_authz_groups=='users': current_users_roles = [( uor.user.name, uor.role) for uor in current_uors if uor.user] elif users_or_authz_groups=='authz_groups': current_users_roles = [( uor.authorized_group.name, uor.role) for uor in current_uors if uor.authorized_group] else: assert False, "shouldn't be here" current_user_role_dict={} for (u,r) in current_users_roles: current_user_role_dict[(u,r)]=True # and now we can loop through our dictionary of desired states # checking whether a change needs to be made, and if so making it # Here we check whether someone is already assigned a role, in order # to avoid assigning it twice, or attempting to delete it when it # doesn't exist. Otherwise problems can occur. if users_or_authz_groups=='users': for ((u,r), val) in new_user_role_dict.items(): if val: if not ((u,r) in current_user_role_dict): model.add_user_to_role(model.User.by_name(u),r,group) else: if ((u,r) in current_user_role_dict): model.remove_user_from_role(model.User.by_name(u),r,group) elif users_or_authz_groups=='authz_groups': for ((u,r), val) in new_user_role_dict.items(): if val: if not ((u,r) in current_user_role_dict): model.add_authorization_group_to_role(model.AuthorizationGroup.by_name(u),r,group) else: if ((u,r) in current_user_role_dict): model.remove_authorization_group_from_role(model.AuthorizationGroup.by_name(u),r,group) else: assert False, "shouldn't be here" # finally commit the change to the database model.repo.commit_and_remove() h.flash_success("Changes Saved") def action_add_form(users_or_authz_groups): # The user is attempting to set new roles for a named user new_user = request.params.get('new_user_name') # this is the list of roles whose boxes were ticked checked_roles = [ a for (a,b) in request.params.items() if (b == u'on')] # this is the list of all the roles that were in the submitted form submitted_roles = [ a for (a,b) in request.params.items() if (b == u'submitted')] # from this we can make a dictionary of the desired states # i.e. true for the ticked boxes, false for the unticked desired_roles = {} for r in submitted_roles: desired_roles[r]=False for r in checked_roles: desired_roles[r]=True # again, in order to avoid either creating a role twice or deleting one which is # non-existent, we need to get the users' current roles (if any) current_uors = get_userobjectroles() if users_or_authz_groups=='users': current_roles = [uor.role for uor in current_uors if ( uor.user and uor.user.name == new_user )] user_object = model.User.by_name(new_user) if user_object==None: # The submitted user does not exist. Bail with flash message h.flash_error('unknown user:'******'authz_groups': current_roles = [uor.role for uor in current_uors if ( uor.authorized_group and uor.authorized_group.name == new_user )] user_object = model.AuthorizationGroup.by_name(new_user) if user_object==None: # The submitted user does not exist. Bail with flash message h.flash_error('unknown authorization group:' + str (new_user)) else: # Whenever our desired state is different from our current state, change it. for (r,val) in desired_roles.items(): if val: if (r not in current_roles): model.add_authorization_group_to_role(user_object, r, group) else: if (r in current_roles): model.remove_authorization_group_from_role(user_object, r, group) h.flash_success("Authorization Group Added") else: assert False, "shouldn't be here" # and finally commit all these changes to the database model.repo.commit_and_remove() # In the event of a post request, work out which of the four possible actions # is to be done, and do it before displaying the page if 'add' in request.POST: action_add_form('users') if 'authz_add' in request.POST: action_add_form('authz_groups') if 'save' in request.POST: action_save_form('users') if 'authz_save' in request.POST: action_save_form('authz_groups') # ================= # Display the page # Find out all the possible roles. At the moment, any role can be # associated with any object, so that's easy: possible_roles = model.Role.get_all() # get the list of users who have roles on this object, with their roles uors = get_userobjectroles() # uniquify and sort users = sorted(list(set([uor.user.name for uor in uors if uor.user]))) authz_groups = sorted(list(set([uor.authorized_group.name for uor in uors if uor.authorized_group]))) # make a dictionary from (user, role) to True, False users_roles = [( uor.user.name, uor.role) for uor in uors if uor.user] user_role_dict={} for u in users: for r in possible_roles: if (u,r) in users_roles: user_role_dict[(u,r)]=True else: user_role_dict[(u,r)]=False # and similarly make a dictionary from (authz_group, role) to True, False authz_groups_roles = [( uor.authorized_group.name, uor.role) for uor in uors if uor.authorized_group] authz_groups_role_dict={} for u in authz_groups: for r in possible_roles: if (u,r) in authz_groups_roles: authz_groups_role_dict[(u,r)]=True else: authz_groups_role_dict[(u,r)]=False # pass these variables to the template for rendering c.roles = possible_roles c.users = users c.user_role_dict = user_role_dict c.authz_groups = authz_groups c.authz_groups_role_dict = authz_groups_role_dict return render('group/authz.html')
gettext('Action name not known: %s') % str(logic_function)) context = {'model': model, 'session': model.Session, 'user': c.user} model.Session()._context = context return_dict = {'help': function.__doc__} try: request_data = self._get_request_data() except ValueError, inst: log.error('Bad request data: %s' % str(inst)) return self._finish_bad_request( gettext('JSON Error: %s') % str(inst)) if not isinstance(request_data, dict): # this occurs if request_data is blank log.error('Bad request data - not dict: %r' % request_data) return self._finish_bad_request( gettext('Bad request data: %s') % \ 'Request data JSON decoded to %r but ' \ 'it needs to be a dictionary.' % request_data) try: result = function(context, request_data) return_dict['success'] = True return_dict['result'] = result except DataError, e: log.error('Format incorrect: %s - %s' % (e.error, request_data)) #TODO make better error message return self._finish(400, _(u'Integrity Error') + \ ': %s - %s' % (e.error, request_data)) except NotAuthorized: return_dict['error'] = {'__type': 'Authorization Error', 'message': _('Access denied')} return_dict['success'] = False