当前位置: 首页>>代码示例>>Python>>正文


Python SecurityManagement.newSecurityManager方法代码示例

本文整理汇总了Python中AccessControl.SecurityManagement.newSecurityManager方法的典型用法代码示例。如果您正苦于以下问题:Python SecurityManagement.newSecurityManager方法的具体用法?Python SecurityManagement.newSecurityManager怎么用?Python SecurityManagement.newSecurityManager使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在AccessControl.SecurityManagement的用法示例。


在下文中一共展示了SecurityManagement.newSecurityManager方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: createObjectAsPortalOwner

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [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
开发者ID:collective,项目名称:collective.contemplate,代码行数:27,代码来源:login.py

示例2: login_as_portal_owner

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [as 别名]
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
开发者ID:milieuinfo,项目名称:minaraad,代码行数:9,代码来源:base.py

示例3: __call__

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [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')
开发者ID:redomino,项目名称:redomino.revision,代码行数:58,代码来源:revision_actions.py

示例4: setUp

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [as 别名]
    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
开发者ID:4teamwork,项目名称:ftw.bridge.client,代码行数:13,代码来源:test_favorite.py

示例5: reorderFolderContents

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [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)
开发者ID:austgl,项目名称:everydo-project,代码行数:55,代码来源:utils.py

示例6: create_folder

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [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
开发者ID:collective,项目名称:collective.contentrules.yearmonth,代码行数:16,代码来源:target_folder.py

示例7: notifyAboutReview

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [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)
开发者ID:austgl,项目名称:everydo-project,代码行数:52,代码来源:files.py

示例8: setContentCategory

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [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())
开发者ID:austgl,项目名称:everydo-project,代码行数:18,代码来源:adapters.py

示例9: kss_obj_delete

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [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()
开发者ID:austgl,项目名称:everydo-project,代码行数:47,代码来源:kssview.py

示例10: authenticateCredentials

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [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
开发者ID:collective,项目名称:Products.remember,代码行数:21,代码来源:member.py

示例11: __call__

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [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
开发者ID:a25kk,项目名称:stv2,代码行数:44,代码来源:browser.py

示例12: deleteTeam

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [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()
开发者ID:austgl,项目名称:everydo-project,代码行数:43,代码来源:kssview.py

示例13: _auth_with_ticket

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [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)
开发者ID:yangh,项目名称:collective.quickupload,代码行数:25,代码来源:quick_upload.py

示例14: handle_delete

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [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)
开发者ID:socialplanning,项目名称:opencore,代码行数:38,代码来源:account.py

示例15: len

# 需要导入模块: from AccessControl import SecurityManagement [as 别名]
# 或者: from AccessControl.SecurityManagement import newSecurityManager [as 别名]
import transaction
from AccessControl import SecurityManagement

SecurityManagement.newSecurityManager(
    None, app.acl_users.getUser('admin'))

for path, obj in app.ZopeFind(app, search_sub=True,
                              obj_expr="id=='broken'"):
    try:
        split_path = path.rsplit('/', 1)
        if len(split_path) == 2:
            container_path, broken_id = split_path
            container = app.unrestrictedTraverse(container_path)
        else:
            container = app
            broken_id, = split_path
        if broken_id in container.objectIds():
            if container.manage_delObjects is not None:
                container.manage_delObjects([broken_id])
    except:
        import pdb, sys; pdb.post_mortem(sys.exc_info()[2])
        raise
                
transaction.commit()
开发者ID:pchanxxx,项目名称:msc-buidout,代码行数:26,代码来源:broken_delete.py


注:本文中的AccessControl.SecurityManagement.newSecurityManager方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。