本文整理汇总了Python中AccessControl.SecurityManagement类的典型用法代码示例。如果您正苦于以下问题:Python SecurityManagement类的具体用法?Python SecurityManagement怎么用?Python SecurityManagement使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SecurityManagement类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: createObjectAsPortalOwner
def createObjectAsPortalOwner(container, type_name, id_):
"""Create an object as the portal owner"""
info = interfaces.ITemplateTypeInfo(
container.portal_types.getTypeInfo(type_name), None)
if info is None:
return
template = info.getTemplate(container)
if template is None:
return
source = Acquisition.aq_parent(Acquisition.aq_inner(template))
sm = SecurityManagement.getSecurityManager()
SecurityManagement.newSecurityManager(
None,
container.portal_url.getPortalObject().getOwner())
result, = container.manage_pasteObjects(
source.manage_copyObjects([template.getId()]))
container.manage_renameObject(result['new_id'], id_)
SecurityManagement.setSecurityManager(sm)
added = container[id_]
owner.changeOwnershipOf(added)
event.notify(interfaces.TemplateCopiedEvent(added, template))
return added
示例2: login_as_portal_owner
def login_as_portal_owner(app):
uf = app.acl_users
owner = uf.getUserById(ptc.portal_owner)
if not hasattr(owner, 'aq_base'):
owner = owner.__of__(uf)
SecurityManagement.newSecurityManager(None, owner)
return owner
示例3: flash_upload_file
def flash_upload_file(self) :
context = aq_inner(self.context)
request = self.request
self._auth_with_ticket()
file_name = request.form.get("Filename", "")
file_data = request.form.get("Filedata", None)
content_type = mimetypes.guess_type(file_name)[0]
portal_type = request.form.get('typeupload', '')
title = request.form.get("title", None)
description = request.form.get("description", None)
if not portal_type :
ctr = getToolByName(context, 'content_type_registry')
portal_type = ctr.findTypeName(file_name.lower(), content_type, '') or 'File'
if file_data:
factory = IQuickUploadFileFactory(context)
logger.debug("Uploading file with flash: filename=%s, title=%s, "
"description=%s, content_type=%s, portal_type=%s" % (
file_name, title, description, content_type, portal_type)
)
try :
f = factory(file_name, title, description, content_type, file_data, portal_type)
except :
# XXX todo : improve errors handlers for flashupload
raise
if f['success'] is not None :
o = f['success']
logger.info("file url: %s" % o.absolute_url())
SecurityManagement.setSecurityManager(self.old_sm)
return o.absolute_url()
示例4: tearDown
def tearDown(self):
IStatusMessage(self.request).show()
if 'HTTP_REFERER' in self.request.environ:
del self.request.environ['HTTP_REFERER']
SecurityManagement.noSecurityManager()
if 'location' in self.request.response.headers:
del self.request.response.headers['location']
示例5: __call__
def __call__(self):
""" Create a new revision folder based on an existing item """
context_id = self.context.getId()
parent = getMultiAdapter((self.context, self.request), name=u'plone_context_state').parent()
try:
uniqueid = parent.generateUniqueId('Folder')
uniqueid = parent.invokeFactory('Folder', uniqueid)
folderish_obj = getattr(parent, uniqueid)
folderish_obj.setTitle(self.context.Title())
alsoProvides(folderish_obj, IRevision)
revision_info = IRevisionInfo(folderish_obj)
next_code = revision_info.next_code()
transaction.savepoint(optimistic=True)
_move(parent, self.context, folderish_obj, context_id, next_code)
revisionfile = getattr(folderish_obj, next_code)
alsoProvides(revisionfile, IRevisionFile)
_move(parent, folderish_obj, parent, uniqueid, context_id)
newcontext = getattr(parent, context_id)
ppw = getToolByName(newcontext, 'portal_placeful_workflow', None)
if ppw:
portal_type = self.context.portal_type
priority_utility = queryUtility(IRevisionWorkflowUtility, name=portal_type)
priority_utility = not priority_utility and queryUtility(IRevisionWorkflowUtility)
policy_id = priority_utility and priority_utility.policy_id()
if policy_id and ppw.isValidPolicyName(policy_id):
old_sm = SecurityManagement.getSecurityManager()
try:
SecurityManagement.newSecurityManager(None, SpecialUsers.system)
newcontext.manage_addProduct['CMFPlacefulWorkflow'].manage_addWorkflowPolicyConfig()
config = ppw.getWorkflowPolicyConfig(newcontext)
config.setPolicyIn(policy=policy_id)
config.setPolicyBelow(policy=policy_id, update_security=True)
finally:
SecurityManagement.setSecurityManager(old_sm)
newcontext.reindexObject()
newcontext.reindexObjectSecurity()
except ConflictError:
raise
except Exception:
view_url = getMultiAdapter((self.context, self.request), name=u'plone_context_state').view_url()
self.request.response.redirect(view_url)
IStatusMessage(self.request).addStatusMessage(_(u'enabled_revision_error', default=u'Error'), type='error')
else:
view_url = getMultiAdapter((folderish_obj, self.request), name=u'plone_context_state').view_url()
self.request.response.redirect(view_url)
IStatusMessage(self.request).addStatusMessage(_(u'enabled_revision_ok', default=u'Revision created correctly'), type='info')
示例6: setUp
def setUp(self):
RequestAwareTestCase.setUp(self)
user = SimpleUser('john.doe', 'pw', [], [])
SecurityManagement.newSecurityManager(object(), user)
self.portal = self.layer['portal']
self.request = self.layer['request']
self.page = self.portal.get('feed-folder').get('page')
self.referer_url = 'http://nohost/plone/feed-folder/page'
self.request.environ['HTTP_REFERER'] = self.referer_url
示例7: reorderFolderContents
def reorderFolderContents(folder, encodedlist, reverse=False):
# id[]=313128&id[]=800959&id[]=304611&id[]=947600&id[]=588736&id[]=274764
folder = folder.aq_inner
encodedlist = encodedlist.strip()
if not encodedlist:
return
ids = [id.split('=')[1] for id in encodedlist.split('&')]
if reverse:
ids.reverse()
ctool = getToolByName(folder, 'portal_catalog')
existing_ids = folder.objectIds()
moved_ids = [id for id in ids if id not in existing_ids]
# print moved_ids, ids, existing_ids
if moved_ids:
parent_path = '/'.join(folder.aq_inner.aq_parent.getPhysicalPath())
brains = ctool(path=parent_path,
portal_type='TodoItem',
getId=moved_ids)
for b in brains:
o = b.getObject()
cutted = o.aq_parent.manage_cutObjects([o.getId()])
# 解决粘贴的时候权限的问题
originalSecurityManager = SecurityManagement.getSecurityManager()
username = originalSecurityManager.getUser().getUserName()
deliverUser = User.SimpleUser(username,'', ['Manager', 'Owner'], '')
acl_users = folder.acl_users.aq_inner
deliverUser = deliverUser.__of__(acl_users)
SecurityManagement.newSecurityManager(None, deliverUser)
folder.manage_pasteObjects(cutted)
SecurityManagement.setSecurityManager(originalSecurityManager)
_dict = {}
unchanged = []
for obj in folder._objects:
if obj['id'] not in ids:
unchanged.append(obj)
else:
_dict[obj['id']] = obj
# 注意,可能传过来了不存在的id, 在对象被删除后会发生!
ordered = [_dict[id] for id in ids if id in _dict]
ordered.extend(unchanged)
folder._objects = tuple(ordered)
# 更新索引
for id in _dict:
obj = getattr(folder, id)
ctool.reindexObject(obj, idxs=['getObjPositionInParent'], update_metadata=1)
示例8: create_folder
def create_folder(self, context, id, title=''):
old_sm = SecurityManagement.getSecurityManager()
SecurityManagement.newSecurityManager(None, SpecialUsers.system)
try:
folder = api.content.create(type=self.action.folderish_type,
id=id,
title=title,
container=context)
for transition in self.action.transitions:
api.content.transition(obj=folder,
transition=transition)
finally:
SecurityManagement.setSecurityManager(old_sm)
return folder
示例9: notifyAboutReview
def notifyAboutReview(ob, event):
# 仅当文件或者图片(File/Image)的时候,才发送
if ob.getPortalTypeName() not in ['File', 'Image']:
return
# 仅当处于提交、审核通过、拒绝的时候才通知
mtool = getToolByName(ob, 'portal_membership')
userid = mtool.getAuthenticatedMember().getId()
operation = ''
if event.action.endswith('submit'):
operation = 'submit'
elif event.action.endswith('publish'):
operation = 'publish'
elif event.action.endswith('reject'):
operation = 'reject'
# 工作流就是这样定义的, 下面逻辑没错!
elif event.action.endswith('retract') and ob.Creator() != userid:
operation = 'reject'
else:
return
# 必须在项目中
if hasattr(ob, 'getProject'):
project = ob.getProject().aq_inner
acl_users = getToolByName(project, 'acl_users')
oe = IOrganizedEmployess(project.teams)
all_members = oe.get_all_people()
members = []
if operation == 'submit':
# 只有Administrator或者Reviewer才能收到邮件
# userids = ob.users_with_local_role('Administrator') + ob.users_with_local_role('Reviewer')
originalSecurityManager = SecurityManagement.getSecurityManager()
for member in all_members:
user = acl_users.getUserById(member.getId())
if user is not None:
# 模拟那个用户来登录
SecurityManagement.newSecurityManager(None, user)
if mtool.checkPermission('Review portal content', ob):
members.append(member)
SecurityManagement.setSecurityManager(originalSecurityManager)
else:
member = mtool.getMemberById(ob.Creator())
if member:
members.append(member)
sendNotification(ob, members, operation)
示例10: setContentCategory
def setContentCategory(self, obj, new_cat_id):
cutted = obj.aq_inner.aq_parent.manage_cutObjects(obj.getId())
new_cat = getattr(self.context, new_cat_id).aq_inner
# 解决权限的问题
originalSecurityManager = SecurityManagement.getSecurityManager()
username = originalSecurityManager.getUser().getUserName()
deliverUser = User.SimpleUser(username,'', ['Manager', 'Owner'], '')
acl_users = obj.acl_users.aq_inner
deliverUser = deliverUser.__of__(acl_users)
SecurityManagement.newSecurityManager(None, deliverUser)
new_cat.manage_pasteObjects(cutted)
SecurityManagement.setSecurityManager(originalSecurityManager)
return getattr(new_cat, obj.getId())
示例11: kss_obj_delete
def kss_obj_delete(self, selector='.kssDeletionRegion'):
obj = self.context.aq_inner
if obj.getPortalTypeName() == 'Discussion Item':
parent = obj.inReplyTo()
if parent is not None:
portal_discussion = getUtility(IDiscussionTool)
talkback = portal_discussion.getDiscussionFor(parent)
else:
talkback = obj.aq_parent
# remove the discussion item
talkback.deleteReply( str(obj.getId()) )
else:
# 被锁定时先解锁
if HAS_LOCKING:
lockable = ILockable(obj)
if lockable.locked():
lockable.unlock()
parent = obj.aq_parent
# archetypes的manage_delObjects会检查每个item的删除权限
originalSecurityManager = SecurityManagement.getSecurityManager()
SecurityManagement.newSecurityManager(None, User.SimpleUser('admin','',('Manager',), ''))
parent.manage_delObjects(str(obj.getId()))
SecurityManagement.setSecurityManager(originalSecurityManager)
if selector.startswith('redirect2'):
# 跳转到某个地址
# 需要定义 # class="kssattr-delSelector-redirect2http://test.everydo.com"
redirect2url = selector[len('redirect2'):]
self.getCommandSet('zopen').redirect(url=redirect2url)
else:
core = self.getCommandSet('core')
effects = self.getCommandSet('effects')
selector = core.getParentNodeSelector(selector)
# effects.effect(selector, 'fade')
core.deleteNode(selector)
self.getCommandSet('plone').issuePortalMessage(
translate(_(u'Deleted.'), default="Deleted.", context=self.request),
translate(_(u'Info'), default="Info", context=self.request))
return self.render()
示例12: guarded_getattr
def guarded_getattr(inst, name, default=_marker):
"""Retrieves an attribute, checking security in the process.
Raises Unauthorized if the attribute is found but the user is
not allowed to access the attribute.
"""
if name[:1] == '_':
raise Unauthorized, name
# Try to get the attribute normally so that unusual
# exceptions are caught early.
try:
v = getattr(inst, name)
except AttributeError:
if default is not _marker:
return default
raise
try:
container = v.im_self
except AttributeError:
container = aq_parent(aq_inner(v)) or inst
assertion = Containers(type(container))
if isinstance(assertion, dict):
# We got a table that lets us reason about individual
# attrs
assertion = assertion.get(name)
if assertion:
# There's an entry, but it may be a function.
if callable(assertion):
return assertion(inst, name)
# Nope, it's boolean
return v
raise Unauthorized, name
if assertion:
if callable(assertion):
factory = assertion(name, v)
if callable(factory):
return factory(inst, name)
assert factory == 1
else:
assert assertion == 1
return v
# See if we can get the value doing a filtered acquire.
# aq_acquire will either return the same value as held by
# v or it will return an Unauthorized raised by validate.
validate = SecurityManagement.getSecurityManager().validate
aq_acquire(inst, name, aq_validate, validate)
return v
示例13: test_add_portlet_fails_with_anonymous
def test_add_portlet_fails_with_anonymous(self):
portal = self.layer['portal']
request = self.layer['request']
request.environ['HTTP_X_BRIDGE_ORIGIN'] = 'client-one'
request.form['path'] = '@@watcher-feed?uid=567891234'
sm = SecurityManagement.getSecurityManager()
SecurityManagement.noSecurityManager()
try:
view = queryMultiAdapter((portal, request),
name='add-watcher-portlet')
with self.assertRaises(Exception) as cm:
view()
self.assertEqual(str(cm.exception), 'Could not find userid.')
finally:
SecurityManagement.setSecurityManager(sm)
示例14: __call__
def __call__(self):
ticket = self.request.form.get('ticket',None)
if ticket is None:
# we cannot set post headers in flash, so get the
# querystring manually
qs = self.request.get('QUERY_STRING','ticket=')
ticket = qs.split('=')[-1] or None
logger.debug('Ticket being used is "%s"' % str(ticket))
if ticket is None:
raise Unauthorized('No ticket specified')
context = utils.non_view_context(self.context)
url = absoluteURL(context, self.request)
username = ticketmod.ticketOwner(url, ticket)
if username is None:
logger.warn('Ticket "%s" was invalidated, cannot be used '
'any more.' % str(ticket))
raise Unauthorized('Ticket is not valid')
old_sm = SecurityManagement.getSecurityManager()
user = utils.find_user(context, username)
SecurityManagement.newSecurityManager(self.request, user)
logger.debug('Switched to user "%s"' % username)
ticketmod.invalidateTicket(url,ticket)
if self.request.form.get('Filedata', None) is None:
# flash sends a emtpy form in a pre request in flash version 8.0
return ""
fileUpload = self.request.form['Filedata']
fileName = self.request.form['Filename']
contentType = self.request.form.get('Content-Type',None)
factory = IFileFactory(self.context)
f = factory(fileName, contentType, fileUpload)
event.notify(FlashUploadedEvent(f))
result = "filename=%s" %f.getId()
SecurityManagement.setSecurityManager(old_sm)
return result
示例15: edit_collection
def edit_collection(self):
provider = self.collection()
smanager = SecurityManagement.getSecurityManager()
allowed = smanager.checkPermission(ChangeTopics, provider)
if allowed:
provider = self.collection()
if provider is not None:
if ICollection.providedBy(provider):
return provider.absolute_url() + '/edit'
return provider.absolute_url() + '/criterion_edit_form'
return None