def logRoleGrant(context, receiver, role): # adapted from subscribers.sharing.SharingHandler # this function should be replaced by a factored out variant from patches.py:sharing_handle_form # to have an actual context-diff. from zopyx.plone.persistentlogger.logger import IPersistentLogger logger = IPersistentLogger(context) user = plone.api.user.get_current() username = user.getUserName() info_url = '/@@user-information?userid={}'.format(username) email = user.getProperty('email') fullname = user.getProperty('fullname') if fullname and email: username = '******'.format(username, fullname, email) diff_context = { 'role_changes': { receiver.getId(): { 'fullname': receiver.getProperty('fullname'), 'email': receiver.getProperty('email'), 'added': {role,}, 'removed': set(), } } } logger.log('Sharing updated (via Role Request)', level='info', username=username, info_url=info_url, details=diff_context)
def log_clear(self): """ Clear persistent log """ alsoProvides(self.request, IDisableCSRFProtection) logger = IPersistentLogger(self.context) logger.clear() msg = u'Log entries cleared' logger.log(msg, 'info') self.context.plone_utils.addPortalMessage(msg) return self.request.response.redirect( '{}/persistent-log'.format(self.context.absolute_url()))
def create_accounting_account(obj, event): """ Create an IAccount for a registered resource during object creation """ logger = IPersistentLogger(obj) try: obj.addAccount() logger.log('Account created on accounting server', level='info') except ConflictError: raise except Exception as e: pass
def test_logging(self): c = self.portal logger = IPersistentLogger(c) self.assertEqual(len(logger), 0) logger.log(u'error', 'error') logger.log(u'info', 'info') self.assertEqual(len(logger), 2) logger.clear() self.assertEqual(len(logger), 0) self.assertEqual(logger.get_last_user(), 'test-user')
def demo(self): """ Create demo logger entries """ import time import random alsoProvides(self.request, IDisableCSRFProtection) logger = IPersistentLogger(self.context) for i in range(20): text = u'some text üöä {}'.format(i) level = random.choice(['debug', 'info', 'warn', 'error', 'fatal']) details = dict(a=random.random(), b=random.random(), c=random.random()) logger.log(text, level, details) time.sleep(0.3) self.context.plone_utils.addPortalMessage(u'Demo logger entries created') self.request.response.redirect(self.context.absolute_url() + '/@@persistent-log')
def _render(self): IPersistentLogger(self.context).log('store') if 'zipfile' not in self.request.form: raise ValueError('No parameter "zipfile" found') # cleanup source folder get_handle = self.context.get_handle(create_if_not_existing=True) target_dir = SRC_PREFIX if get_handle.exists(target_dir): get_handle.removedir(target_dir, force=True) get_handle.makedir(target_dir) # Write payload/data to ZIP file zip_out = temp_zip(suffix='.zip') with open(zip_out, 'wb') as fp: fp.write(self.request.form['zipfile'].read()) # and unpack it result = dict(mapping=dict()) with delete_after(zip_out): with fs.zipfs.ZipFS(zip_out, 'r') as zip_handle: for name in zip_handle.walkfiles(): name = name.lstrip('/') dest_name = '{}/{}'.format(target_dir, name) get_handle.ensuredir(dest_name) data = zip_handle.open(name, 'rb').read() with get_handle.open(dest_name, 'wb') as fp: fp.write(data) with get_handle.open(dest_name + '.sha256', 'wb') as fp: fp.write(hashlib.sha256(data).hexdigest()) result['mapping'][name] = dest_name return result
def _render(self): """ Create a new content object in Plone """ payload = decode_json_payload(self.request) id = str(uuid.uuid4()) title = payload.get('title') description = payload.get('description') custom = payload.get('custom') connector = plone.api.content.create( type='xmldirector.plonecore.connector', container=self.context, id=id, title=title, description=description) connector.connector_subpath = 'plone.api-{}/{}'.format( plone.api.portal.get().getId(), id) connector.api_enabled = True connector.get_handle(create_if_not_existing=True) connector.reindexObject() if custom: annotations = IAnnotations(connector) annotations[ANNOTATION_KEY] = custom IPersistentLogger(connector).log('created', details=payload) self.request.response.setStatus(201) return dict( id=id, url=connector.absolute_url(), )
def demo(self): """ Create demo logger entries """ import time import random alsoProvides(self.request, IDisableCSRFProtection) logger = IPersistentLogger(self.context) for i in range(20): text = u'some text üöä {}'.format(i) level = random.choice(['debug', 'info', 'warn', 'error', 'fatal']) details = dict(a=random.random(), b=random.random(), c=random.random()) logger.log(comment=text, level=level, details=details) time.sleep(0.3) self.context.plone_utils.addPortalMessage( u'Demo logger entries created') self.request.response.redirect(self.context.absolute_url() + '/@@persistent-log')
def SharingHandler(event): """ Log/intercept @@sharing changes """ context = event.object logger = IPersistentLogger(context) user = plone.api.user.get_current() username = user.getUserName() info_url = '/@@user-information?userid={}'.format(username) email = user.getProperty('email') fullname = user.getProperty('fullname') if fullname and email: username = '******'.format(username, fullname, email) logger.log('Sharing updated', level='info', username=username, info_url=info_url, details=event.diff_context)
def test_entries(self): c = self.portal logger = IPersistentLogger(c) logger.log(u'error', 'error') logger.log(u'info', 'info') self.assertEqual(len(logger), 2) entries = logger.entries self.assertEqual(len(entries), 2) for entry in entries: self.assertEqual(entry, logger.entry_by_uuid(entry['uuid']))
def log_clear(self): """ Clear persistent log """ alsoProvides(self.request, IDisableCSRFProtection) logger = IPersistentLogger(self.context) logger.clear() msg = u'Log entries cleared' logger.log(msg, 'info') self.context.plone_utils.addPortalMessage(msg) return self.request.response.redirect('{}/persistent-log'.format( self.context.absolute_url()))
def modified(event): """ get new/updated metadata""" obj = event.object if not IDexterityContent.providedBy(obj): return fields = get_all_fields(obj) data = dict() for f in fields: v = getattr(obj, f, None) if callable(v): v = v() if isinstance(v, RichTextValue): v = v.raw data[f] = v IPersistentLogger(obj).log("Metadata changed", details=data)
def _render(self): payload = decode_json_payload(self.request) IPersistentLogger(self.context).log('set_metadata', details=payload) title = payload.get('title', _marker) if title is not _marker: self.context.setTitle(title) description = payload.get('description', _marker) if description is not _marker: self.context.setDescription(description) subject = payload.get('subject', _marker) if subject is not _marker: self.context.setSubject(subject) custom = payload.get('custom', _marker) if custom is not _marker: annotations = IAnnotations(self.context) annotations[ANNOTATION_KEY] = custom return dict()
def entries(self): alsoProvides(self.request, IDisableCSRFProtection) result = list(IPersistentLogger(self.context).entries) result = sorted(result, key=operator.itemgetter('date')) return result
def test_rolerequest(self, send_mail): def assertMailsSent(subject): self.assertEquals(1, send_mail.call_count) self.assertEquals( {'*****@*****.**', '*****@*****.**'}, send_mail.call_args[1]['recipients']) for args in send_mail.call_args_list: self.assertEquals(2, len(args[1]['recipients'])) self.assertIsNone(args[1]['sender']) self.assertEquals(subject, args[1]['subject']) self.assertEquals('role-request.txt', args[1]['template']) send_mail.reset_mock() username_requester = 'mfn-admin-2' username_receiver = 'mfn-admin-1' email_requester = '*****@*****.**' email_receiver = '*****@*****.**' location = self.folder['B2SAFE'] role = 'Enabler' # Create users plone.api.user.create(email_receiver, username_receiver) plone.api.user.create(email_requester, username_requester, roles=('Manager', )) # Use requester to create rolerequest logout() login(self.portal, username_requester) self.portal.invokeFactory('RoleRequest', 'rolerequest') rolerequest = self.portal.rolerequest rolerequest.update(Title='Role Request for Peter Lustig', userid=username_receiver, role=role, context=location, motivation='Motivation') # Switch back to TEST_USER logout() login(self.portal, TEST_USER_NAME) # Take a tour through the transition graph checking mails being sent, permissions set and logged logger = IPersistentLogger(location) self.assertEquals('submitted', plone.api.content.get_state(rolerequest)) self.assertEquals(0, send_mail.call_count) self.assertFalse(role in plone.api.user.get_roles( username=username_receiver, obj=location, inherit=False)) self.assertEquals(0, len(logger.entries)) plone.api.content.transition(obj=rolerequest, transition='reject') self.assertEquals('rejected', plone.api.content.get_state(rolerequest)) assertMailsSent('[DPMT] Role request rejected') self.assertFalse(role in plone.api.user.get_roles( username=username_receiver, obj=location, inherit=False)) self.assertEquals(0, len(logger.entries)) plone.api.content.transition(obj=rolerequest, transition='submit') self.assertEquals('submitted', plone.api.content.get_state(rolerequest)) self.assertEquals(0, send_mail.call_count) self.assertFalse(role in plone.api.user.get_roles( username=username_receiver, obj=location, inherit=False)) self.assertEquals(0, len(logger.entries)) plone.api.content.transition(obj=rolerequest, transition='accept') self.assertEquals('accepted', plone.api.content.get_state(rolerequest)) assertMailsSent('[DPMT] Role request accepted') self.assertTrue(role in plone.api.user.get_roles( username=username_receiver, obj=location, inherit=False)) self.assertEquals(1, len(logger.entries))