本文整理汇总了Python中AccessControl.SecurityManagement.setSecurityManager方法的典型用法代码示例。如果您正苦于以下问题:Python SecurityManagement.setSecurityManager方法的具体用法?Python SecurityManagement.setSecurityManager怎么用?Python SecurityManagement.setSecurityManager使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类AccessControl.SecurityManagement
的用法示例。
在下文中一共展示了SecurityManagement.setSecurityManager方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: createObjectAsPortalOwner
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
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: flash_upload_file
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
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()
示例3: __call__
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
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')
示例4: reorderFolderContents
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
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)
示例5: create_folder
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
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
示例6: notifyAboutReview
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
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)
示例7: setContentCategory
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
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())
示例8: kss_obj_delete
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
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()
示例9: authenticateCredentials
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
def authenticateCredentials(self, credentials):
""" See IAuthenticationPlugin.
"""
# Fail if authentication is not permitted for this member. Otherwise,
# return the result of verifying the credentials.
orig_sm = SecurityManagement.getSecurityManager()
try:
SecurityManagement.newSecurityManager(None, self.getUser())
if not SecurityManagement.getSecurityManager(
).checkPermission(CAN_AUTHENTICATE_PERMISSION, self):
return None
finally:
SecurityManagement.setSecurityManager(orig_sm)
if self.verifyCredentials(credentials):
login = credentials.get('login')
userid = self.getUserId()
return userid, login
示例10: test_add_portlet_fails_with_anonymous
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
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)
示例11: __call__
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
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
示例12: deleteTeam
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
def deleteTeam(self, selector):
obj = self.context.aq_inner
parent = obj.aq_parent
team_id = obj.getId()
originalSecurityManager = SecurityManagement.getSecurityManager()
SecurityManagement.newSecurityManager(None, User.SimpleUser('admin','',('Manager',), ''))
parent.manage_delObjects(str(team_id))
SecurityManagement.setSecurityManager(originalSecurityManager)
core = self.getCommandSet('core')
selector = core.getParentNodeSelector(selector)
core.deleteNode(selector)
containner = parent.aq_parent
teamidstr = ".teamitemroot-" + team_id + "-" + \
containner.getId()
teamselector = core.getSelector("css", teamidstr)
core.deleteNode(teamselector)
containner.manage_delLocalRoles([team_id + '-' + \
containner.getId()])
containner.reindexObjectSecurity()
for item in ['messages', 'files', 'todos', 'milestones',\
'writeboards', 'chatroom', 'time']:
obj = containner.unrestrictedTraverse(item)
obj.manage_delLocalRoles([team_id + '-' + \
containner.getId()])
obj.reindexObjectSecurity()
if item in ['messages', 'files']:
for i in obj.contentValues():
i.manage_delLocalRoles([team_id + '-' + \
containner.getId()])
i.reindexObjectSecurity()
self.getCommandSet('plone').issuePortalMessage(
translate(_(u'Deleted.'), default="Deleted.", context=self.request),
translate(_(u'Info'), default="Info", context=self.request))
return self.render()
示例13: handle_delete
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import setSecurityManager [as 别名]
def handle_delete(self):
mship = getToolByName(self.context, 'portal_membership')
user_to_delete = self.viewed_member_info['id']
old_manager = SecurityManagement.getSecurityManager()
current_user = old_manager.getUser().getId()
from opencore.interfaces.event import MemberDeletedEvent
notify(MemberDeletedEvent(
self.context.portal_memberdata[user_to_delete]))
# To avoid blocking while we traverse the entire contents of the site,
# we quickly delete the member and their own content...
if current_user == user_to_delete:
# Normally, users don't have permission to delete users.
# Make an exception for deleting yourself.
superuser = UnrestrictedUser('superuser', '', [], [])
SecurityManagement.newSecurityManager(self.request, superuser)
mship.deleteMembers([user_to_delete], delete_memberareas=True,
delete_localroles=False)
SecurityManagement.setSecurityManager(old_manager)
self.context.acl_users.logout(self.request)
else:
# Otherwise, rely on normal access controls. This will
# allow site admins (and only site admins) to delete
# anybody.
mship.deleteMembers([user_to_delete], delete_memberareas=True,
delete_localroles=False)
portal_url = getToolByName(self.context, 'portal_url')()
self.addPortalStatusMessage(
_(u'psm_account_deleted',
u"Account '${deleted_user_id}' has been permanently deleted.",
mapping={u'deleted_user_id': user_to_delete}
)
)
return self.redirect(portal_url)