def getRoles(self, principal_id): """Returns the roles for the given principal in context""" request = getRequest() response = request.RESPONSE token = request.get('token', None) if not token: token = request.cookies.get('token', None) tr_annotate = ITokenRolesAnnotate(self.context, None) safeWrite(tr_annotate) if tr_annotate and token in tr_annotate.token_dict: expire_date = tr_annotate.token_dict[token].get('token_end') roles_to_assign = tr_annotate.token_dict[token].get( 'token_roles', ('Reader', )) if expire_date.replace(tzinfo=None) > datetime.now(): if token not in request.cookies: physical_path = self.context.getPhysicalPath() # Is there a better method for calculate the url_path? url_path = '/' + '/'.join( request.physicalPathToVirtualPath(physical_path)) response.setCookie( name='token', value=token, expires=DateTime(expire_date).toZone('GMT').rfc822(), path=url_path) return roles_to_assign return ()
def __call__(self, action, comment, actor, time): context = self.context workflow_tool = getToolByName(context, 'portal_workflow') workflows = workflow_tool.getWorkflowsFor(context) if not workflows: return workflow_id = workflows[0].id review_state = workflow_tool.getInfoFor(context, 'review_state', None) history_entry = { 'action': action, 'review_state': review_state, 'comments': comment, 'actor': actor, 'time': time, } # If we have plone.protect > 3.0, mark the journal write as safe if 'safeWrite' in dir(utils): utils.safeWrite(context) utils.safeWrite(review_state) workflow_tool.setStatusOf(workflow_id, context, history_entry)
def getRoles(self, principal_id): """Returns the roles for the given principal in context""" request = getRequest() response = request.RESPONSE token = request.get('token', None) if not token: token = request.cookies.get('token', None) tr_annotate = ITokenRolesAnnotate(self.context, None) safeWrite(tr_annotate) if tr_annotate and token in tr_annotate.token_dict: expire_date = tr_annotate.token_dict[token].get('token_end') roles_to_assign = tr_annotate.token_dict[token].get('token_roles', ('Reader', )) if expire_date.replace(tzinfo=None) > datetime.now(): if token not in request.cookies: physical_path = self.context.getPhysicalPath() # Is there a better method for calculate the url_path? url_path = '/' + '/'.join(request.physicalPathToVirtualPath(physical_path)) response.setCookie(name='token', value=token, expires=DateTime(expire_date).toZone('GMT').rfc822(), path=url_path) return roles_to_assign return ()
def updateGroups(self): # XXX this is a hack around the current implementation. it might # be better to keep the data in the groups and do the mass # manipulation here and just here only. See the method # associated with the update button in the mixin class above. wh = zope.component.getAdapter(self.context, IExposureWizard) safeWrite(wh, self.request) # XXX skip the first one, base on assumption that the view is # going to be first. for g in self.groups[1:]: if g.deleted: # Have to manipulate the current structure. del wh.structure[g.pos] continue if g.new_filename is None: continue # so we have a new file name, the entry will be replaced. wh.structure[g.pos] = (g.new_filename, g.structure) # trigger the update (ping it). _changeWizard(self.context)
def _update_recent_contacts(self): ''' Update, if needed, the list of the last twenty profiles that we have visited ''' my_profile = pi_api.userprofile.get_current() contact = self.context.username if not my_profile or my_profile.username == contact: return recent_contacts = copy(my_profile.recent_contacts or []) # If the contact is already the first on the list, we have nothing todo try: if recent_contacts.index(contact) == 0: return except ValueError: pass # Otherwise we want it to be the first on the list try: recent_contacts.remove(contact) except ValueError: pass recent_contacts.insert(0, contact) # We limit ourselves recent_contacts = recent_contacts[:20] # Do not touch the DB if nothing has changed if my_profile.recent_contacts == recent_contacts: return safeWrite(my_profile, self.request) my_profile.recent_contacts = recent_contacts
def csrf_safe(f, self, *args, **kw): """mark objects managed by `self._p_jar` (newly) modified by *f* as CSRF safe.""" registered = getattr(getattr(self, "_p_jar", None), "_registered_objects", [] ) nr = len(registered) try: return f(self, *args, **kw) finally: for i in range(nr, len(registered)): # newly registered safeWrite(registered[i])
def safe_write(request): """Disable CSRF protection of plone.protect for a block of code. Inside the context manager objects can be written to without any restriction. The context manager collects all touched objects and marks them as safe write.""" objects_before = set(_registered_objects(request)) yield objects_after = set(_registered_objects(request)) for obj in objects_after - objects_before: safeWrite(obj, request)
def __call__(self, action, comment, actor, time): context = self.context annotations = IAnnotations(context) journal_annotations = annotations.get(JOURNAL_ENTRIES_ANNOTATIONS_KEY, None) if not journal_annotations: annotations[JOURNAL_ENTRIES_ANNOTATIONS_KEY] = PersistentList() journal_annotations = annotations.get(JOURNAL_ENTRIES_ANNOTATIONS_KEY) history_entry = PersistentDict({"action": action, "comments": comment, "actor": actor, "time": time}) # If we have plone.protect > 3.0, mark the journal write as safe if "safeWrite" in dir(utils): utils.safeWrite(context) utils.safeWrite(journal_annotations) journal_annotations.append(history_entry)
def create_conversation(self, new_userid): if not pi_api.userprofile.get(new_userid): raise ValueError("Invalid userid: %s", new_userid) # maybe this user does not even have an inbox yet try: inbox = pi_api.messaging.get_inbox() except KeyError: inbox = pi_api.messaging.create_inbox() safeWrite(inbox, self.request) safeWrite(inbox.__parent__, self.request) # don't error out when selecting an existing conversation if new_userid not in inbox.keys(): conversation = pi_api.messaging.create_conversation(new_userid) safeWrite(conversation, self.request) safeWrite(inbox, self.request) safeWrite(inbox.data, self.request) logger.info("%s started new conversation with %s", api.user.get_current().id, new_userid)
def update(self): self.error = None self.mail_not_sent = None # only calculate taxes if some items in cart are taxable taxable_subtotal = sum( item.subtotal for item in self.cart.items if item.taxable) if taxable_subtotal != 0: try: self.cart.calculate_taxes() except TaxRateException as e: # The sales tax could not be calculated as some of the # required information was missing. (can be triggered by anon # users, hitting the checkout url directly) self.error = ('There was an problem calculating ' 'the tax: ') + e.args[0] if self.error: return # Make sure writing tax to cart doesn't trigger CSRF warning safeWrite(self.cart.data) self.prepopulate_billing_info()
def flush_queue(self): # update marker - block autoflush self._update_mtime() with LOCK: try: # cancel scheduled flush if self.MAX_QUEUE_AGE > 0 and self._v_timer is not None: # logger.info("Cancelling timer") self._v_timer.cancel() self._v_timer = None except AttributeError: self._v_timer = None if STATUSQUEUE.empty(): return 0 # no write while True: try: (id, status) = STATUSQUEUE.get(block=False) safeWrite(status) self._store(status) except Queue.Empty: break return 1 # confirmed write
def mark_read(self, userid): conversation = pi_api.messaging.get_conversation(userid) if conversation.new_messages_count > 0: conversation.mark_read() # this is a valid write-on-read safeWrite(conversation, self.request) # the write propagates to all children messages for message in conversation.get_messages(): safeWrite(message, self.request) # the write also propagates to parent inbox safeWrite(conversation.__parent__, self.request)
def __init__(self, context): self.annotations = IAnnotations(context).setdefault( ANNOTATIONS_KEY, PersistentDict()) safeWrite(context)
def __init__(self, context): self.annotations = IAnnotations(context).setdefault(ANNOTATIONS_KEY, PersistentDict()) safeWrite(context)