def get_rendered_ownership_form(request): """Returns the rendered ownership form for the item in the current request. If the item is not an instance of Owned, than an empty string is returned. Changing the owner of the item will only be available for users with a administrative role and update permissions on the current item. Changing the group is restricted to the groups the user is member if the user has not an administrative role. """ def _has_administrational_role(modul, user): for action in modul.actions: if action.name == "Update": for role in action.roles: if role.admin and has_role(user, role.name): return True return False item = get_item_from_request(request) form = get_ownership_form(request) modul = get_item_modul(request, item) usergroup_modul = get_item_modul(request, Usergroup) _groups = [unicode(g.name) for g in request.user.groups] _admin = (_has_administrational_role(modul, request.user) or has_role(request.user, "admin") or _has_administrational_role(usergroup_modul, request.user)) values = {"_admin": _admin, "_groups": _groups} if isinstance(item, Owned): return form.render(values=values) else: return ""
def create(self, user, values): """Will create a new instance of clazz. The instance is it is not saved persistent at this moment. The method will also take care of setting the correct ownership. :user: User instance will own the new created item :values: Dictionary with values for the new item :returns: Instance of clazz """ if not isinstance(values, dict): raise ValueError("Values must be a dictionary") item = self._clazz() # Try to set the ownership of the entry if the item provides the # fields. if (hasattr(item, 'uid') and user is not None): item.uid = user.id if (hasattr(item, 'gid')): modul = get_item_modul(None, item) if modul.default_gid: item.gid = modul.default_gid elif (user is not None and user.default_gid): item.gid = user.default_gid if values: if hasattr(self, "_use_strict"): item.set_values(values, use_strict=self._use_strict) else: item.set_values(values) return item
def has_permission(permission, context, request): """Wrapper for pyramid's buitin has_permission function. This wrapper sets dynamically the __acl__ attribute of the given context and then . check if the user has the given permission in the current context using pyramid's has_permission function. Context can be: * Instance of BaseItem * Subclass of BaseItem * Ressource, built from a RessourceFactory If context is an instance or subclass of BaseItem the wrapper will dynamically set the __acl__ attribute. This attribute is used by the pyramid's has_permission function the check the permission. If the context is a resource the function does nothing as the resource already has the __acl__ attribute set. If the user has the permission the it returns True, else False (Actually it returns a boolean like object, see pyramids has_permission doc for more details.) :permission: String. Name of the permission. E.g list, create, read :context: Either Resource, Instance of BaseItem or Subclass of BaseItem :request: current request :returns: True or False (Boolean like object) """ if isinstance(context, BaseItem) or hasattr(context, "_modul_id"): modul = get_item_modul(request, context) context.__acl__ = context._get_permissions(modul, context, request) # Call of has_permission will trigger 4 additional SQL-Queries. The # query will only be trigger once per request. return has_permission_(permission, context, request)
def get_blobform_config(request, item, formname): """Helper function used in the create_ method to setup the create forms for blogform items. To create a new blogform item the creation is done in three steps: 1. Stage 1: The user selects a form from a list 2. Stage 2: The create dialog is rendered with the selected form 3. Stage 3: The item is validated and saved. :request: current request :item: item to build the form :formname: name of the form in the formconfig :returns: formconfig, item used to build a form. """ # First check if the fid parameter is provided fid = request.params.get('fid') or item.fid blobform = request.params.get('blobforms') if fid: log.debug("Stage 3: User has submitted data to create a new item") setattr(item, 'fid', fid) formfactory = BlobformForm.get_item_factory() formconfig = Config(parse(formfactory.load(fid).definition)) return item, formconfig.get_form(formname) elif blobform: log.debug("Stage 2: User has selected a blobform %s " % blobform) setattr(item, 'fid', blobform) formfactory = BlobformForm.get_item_factory() formconfig = Config(parse(formfactory.load(blobform).definition)) return item, formconfig.get_form(formname) else: log.debug("Stage 1: User is selecting a blobform") modul = get_item_modul(request, item) formconfig = get_form_config(modul, "blobform") return modul, formconfig
def render(self): modul = get_item_modul(self._request, self._item) template_modul = get_item_modul(self._request, Printtemplate) values = {} values['request'] = self._request values['body'] = self._render_body() values['modul'] = modul.get_label(plural=True) values['header'] = template_modul.get_label(plural=True) values['action'] = self._action.capitalize() values['ok_text'] = template_modul.get_label(plural=False) values['ok_url'] = self._request.current_route_path() values['_'] = self._request.translate values['cancel_url'] = self._request.ringo.history.last( ) or self._request.url.replace("print", "read") values['eval_url'] = self.form._eval_url values['h'] = ringo.lib.helpers return literal(self.template.render(**values))
def _handle_delete_request(request, items, callback): clazz = request.context.__model__ _ = request.translate if request.method == 'POST' and is_confirmed(request): item_label = get_item_modul(request, clazz).get_label(plural=True) item_label_log = get_item_modul(request, clazz).get_label() mapping = {'item_type': item_label, 'num': len(items)} for item in items: if callback: item = callback(request, item) request.db.delete(item) # Invalidate cache invalidate_cache() try: request.db.flush() except (sa.exc.CircularDependencyError, sa.exc.IntegrityError) as e: mapping["error"] = e.message.decode("utf-8") title = _("Can not delete ${item_type} items.", mapping=mapping) body = _("There has been an integrity error which prevents " "the request to be fulfilled. There are still " "depended items on the item to be deleted. Please " "remove all depended relations to this item before " "deleting it and try again. Hint: ${error}", mapping=mapping) request.db.rollback() renderer = InfoDialogRenderer(request, title, body) rvalue = {} ok_url = request.session['history'].pop(2) rvalue['dialog'] = renderer.render(ok_url) return rvalue msg = _('Deleted ${num} ${item_type} successfully.', mapping=mapping) log_msg = u'User {user.login} deleted {item_label} {item.id}' \ .format(item_label=item_label, item=item, user=request.user) log.info(log_msg) request.session.flash(msg, 'success') # Handle redirect after success. return _handle_redirect(request) else: renderer = ConfirmDialogRenderer(request, clazz, 'delete') rvalue = {} rvalue['dialog'] = renderer.render(items) rvalue['clazz'] = clazz rvalue['item'] = items return rvalue
def _load_user(userid, request): try: modul = get_item_modul(request, User) UserClazz = dynamic_import(modul.clazzpath) factory = UserClazz.get_item_factory() return factory.load(userid) except NoResultFound: return None
def __init__(self, request, item=None): # Reset ACL self.__acl__ = [] self.item = item item_id = request.matchdict.get('id') if item_id and not self.item: self.item = self._load_item(item_id, request) if not self.__modul__: self.__modul__ = get_item_modul(request, self.__model__) self.__acl__ = self._get_item_permissions(request)
def render(self, items): values = {} values['request'] = self._request values['items'] = items values['body'] = self._render_body() values['modul'] = get_item_modul(self._request, self._item).get_label(plural=True) values['action'] = self._action.capitalize() values['ok_url'] = self._request.current_route_path() values['_'] = self._request.translate values['cancel_url'] = self._request.referrer values['evalurl'] = self._request.application_url+get_eval_url() return literal(self.template.render(**values))
def _render_body(self): out = [] # Collect all available evaluations and provide the evaluations # for this modul to the form while rendering. evaluations = [] #converter = get_converter() modul = get_item_modul(self._request, self._item) for evaluation in modul.evaluations: evaluations.append((evaluation, evaluation.id)) values = {"evaluations": evaluations} values["_converter"] = False # converter.is_available() out.append(self.form.render(buttons=False, values=values)) return "".join(out)
def render(self, items): _ = self._request.translate values = {} values['request'] = self._request values['items'] = items values['body'] = self._render_body() values['modul'] = get_item_modul(self._request, self._item).get_label(plural=True) values['action'] = _(self._action.capitalize()) values['ok_url'] = self._request.current_route_path() values['_'] = self._request.translate values['cancel_url'] = self._request.referrer values['eval_url'] = self._request.application_url+get_eval_url() return literal(self.template.render(**values))
def _handle_delete_request(request, items, callback): clazz = request.context.__model__ _ = request.translate if request.method == 'POST' and request.ringo.params.confirmed: item_label = get_item_modul(request, clazz).get_label(plural=True) mapping = {'item_type': item_label, 'num': len(items)} for item in items: handle_callback(request, callback, item=item, mode="pre,default") request.db.delete(item) handle_callback(request, callback, item=item, mode="post") # Invalidate cache invalidate_cache() try: request.db.flush() except (sa.exc.CircularDependencyError, sa.exc.IntegrityError) as e: mapping["error"] = e.message.decode("utf-8") title = _("Can not delete ${item_type} items.", mapping=mapping) body = _( "There has been an integrity error which prevents " "the request to be fulfilled. There are still " "depended items on the item to be deleted. Please " "remove all depended relations to this item before " "deleting it and try again. Hint: ${error}", mapping=mapping) request.db.rollback() renderer = InfoDialogRenderer(request, title, body) rvalue = {} ok_url = request.ringo.history.pop(2) rvalue['dialog'] = renderer.render(ok_url) return rvalue msg = _('Deleted ${num} ${item_type} successfully.', mapping=mapping) log_msg = u'User {user.login} deleted {item_label} {item.id}' \ .format(item_label=item_label, item=item, user=request.user) log.info(log_msg) request.session.flash(msg, 'success') # Handle redirect after success. return _handle_redirect(request) else: renderer = ConfirmDialogRenderer(request, clazz, 'delete') rvalue = {} rvalue['dialog'] = renderer.render(items) rvalue['clazz'] = clazz rvalue['item'] = items return rvalue
def has_admin_role(action_name, clazz, request): """Return True if the current user has admin role for the given action_name on the given clazz. Having a admin role means that the check for the ownership in context of the permissions checks can be omitted. :action_name: Name of the action :clazz: clazz :request: current request and user :returns: True or False """ modul = get_item_modul(request, clazz) for action in modul.actions: if action.name.lower() == action_name: for role in action.roles: if role.admin and has_role(request.user, role.name): return True return False
def restore(request): clazz = request.context.__model__ _ = request.translate handle_params(request) handle_history(request) item = get_item_from_request(request) item_label = get_item_modul(request, clazz).get_label(plural=True) mapping = {'item_type': item_label, 'item': item} item.trash_state_id = 1 route_name = get_action_routename(item, 'update') url = request.route_path(route_name, id=item.id) msg = _('Restored ${item} from trash successfully.', mapping=mapping) log_msg = u'User {user.login} restored {item_label} {item.id}'.format( item_label=item_label, item=item, user=request.user) log.info(log_msg) request.session.flash(msg, 'success') transaction.commit() return HTTPFound(location=url)
def load_modul(item): """Will load the related modul for the given item. First we try to get the bound session from the object and reuse this session to load the modul item. If the item has no bound session then call the get_item_modul method with no request. :item: item :returns: modul instance """ from ringo.model.modul import ModulItem session = Session.object_session(item) mid = item.__class__._modul_id # Loading the modul is expensive! So try to cache it. if not CACHE_MODULES.get(mid): if session: modul = session.query(ModulItem).filter_by(id=mid).one() else: modul = get_item_modul(None, item) CACHE_MODULES.set(modul.id, modul) return CACHE_MODULES.get(mid)
def load_modul(item): """Will load the related modul for the given item. First we try to get the bound session from the object and reuse this session to load the modul item. If the item has no bound session then call the get_item_modul method with no request. :item: item :returns: modul instance """ from ringo.model.modul import ModulItem session = Session.object_session(item) mid = item.__class__._modul_id # Loading the modul is expensive! So try to cache it. if not CACHE_MODULES.get(mid): if session: modul = session.query(ModulItem).get(mid) else: modul = get_item_modul(None, item) CACHE_MODULES.set(modul.id, modul) return CACHE_MODULES.get(mid)
def _render_body(self, items): out = [] _ = self._request.translate item_label = escape(get_item_modul(self._request, self._item).get_label()) mapping = {'action': escape(_(self._action.capitalize()).lower()), 'item': item_label, 'Action': escape(_(self._action.capitalize()))} out.append(_("Do you really want to ${action}" " the following ${item} items?", mapping=mapping)) out.append(HTML.tag("br", _closed=False)) out.append(HTML.tag("ol", _closed=False)) for item in items: out.append(HTML.tag("li", _closed=False)) out.append(escape(unicode(item))) out.append(HTML.tag("/li", _closed=False)) out.append(HTML.tag("/ol", _closed=False)) out.append(_('Please press "${Action}" to ${action} the item.' ' Press "Cancel" to cancel the action.', mapping=mapping)) return literal("").join(out)