本文整理汇总了Python中AccessControl.SecurityManagement.getSecurityManager方法的典型用法代码示例。如果您正苦于以下问题:Python SecurityManagement.getSecurityManager方法的具体用法?Python SecurityManagement.getSecurityManager怎么用?Python SecurityManagement.getSecurityManager使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类AccessControl.SecurityManagement
的用法示例。
在下文中一共展示了SecurityManagement.getSecurityManager方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: createObjectAsPortalOwner
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [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: __call__
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [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')
示例3: guarded_getattr
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [as 别名]
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
示例4: authenticateCredentials
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [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
示例5: edit_collection
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [as 别名]
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
示例6: reorderFolderContents
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [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)
示例7: create_folder
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [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
示例8: notifyAboutReview
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [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)
示例9: setContentCategory
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [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())
示例10: kss_obj_delete
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [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()
示例11: test_add_portlet_fails_with_anonymous
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [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)
示例12: __call__
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [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
示例13: deleteTeam
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [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()
示例14: _auth_with_ticket
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [as 别名]
def _auth_with_ticket(self):
"""
with flashupload authentication is done using a ticket
"""
context = aq_inner(self.context)
request = self.request
url = context.absolute_url()
ticket = getDataFromAllRequests(request, "ticket")
if ticket is None:
raise Unauthorized("No ticket specified")
logger.info('Authenticate using ticket, the ticket is "%s"' % str(ticket))
username = ticketmod.ticketOwner(url, ticket)
if username is None:
logger.info('Ticket "%s" was invalidated, cannot be used ' "any more." % str(ticket))
raise Unauthorized("Ticket is not valid")
self.old_sm = SecurityManagement.getSecurityManager()
user = find_user(context, username)
SecurityManagement.newSecurityManager(self.request, user)
logger.info('Switched to user "%s"' % username)
示例15: handle_delete
# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import getSecurityManager [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)