示例#1
0
    def setupSecurityOptions(self):
        import AccessControl

        AccessControl.setImplementation(self.cfg.security_policy_implementation)
        AccessControl.setDefaultBehaviors(
            not self.cfg.skip_ownership_checking, not self.cfg.skip_authentication_checking, self.cfg.verbose_security
        )
示例#2
0
def import_file(filename, plominodb):
    filepath = join(DIRPATH, filename)
    plominodb.importDesignFromXML(open(filepath).read())
    # If the import file has a pd b, allow it
    import AccessControl
    # obfuscate pd b module to fly under git pre-commit hook's radar
    AccessControl.ModuleSecurityInfo('pd' 'b').declarePublic('set_trace')
    AccessControl.ModuleSecurityInfo('ipd' 'b').declarePublic('set_trace')
示例#3
0
 def setupSecurityOptions(self):
     import AccessControl
     AccessControl.setImplementation(
         self.cfg.security_policy_implementation)
     AccessControl.setDefaultBehaviors(
         not self.cfg.skip_ownership_checking,
         not self.cfg.skip_authentication_checking,
         self.cfg.verbose_security)
示例#4
0
def Get_Projects_List(url, values, log):
    """Get the list of projects from Klocwork server address defined in ServerData["url"]"""

    vals = copy(values)
    vals["action"] = "Projects"
    log.write("Getting projects list, query:\n %s\n" % vals)
    Response = AccessControl.RequestAPI(url, vals)
    Result = AccessControl.ParseAPI(ClassesAPI.ProjectList, Response)
    return Result
示例#5
0
def attachable_documents_vocabulary(context):
    terms = []

    user = AccessControl.getSecurityManager().getUser()
    if user == AccessControl.SpecialUsers.nobody:
        return SimpleVocabulary(terms)

    intids = getUtility(IIntIds)

    ids = []

    for doc in context.getFolderContents(
            full_objects=True,
            contentFilter={
                'portal_type':
                ['opengever.document.document', 'ftw.mail.mail']
            }):

        key = str(intids.getId(doc))
        label = doc.Title()
        terms.append(SimpleVocabulary.createTerm(key, key, label))
        ids.append(key)

    for relation in getattr(context, 'relatedItems', []):
        key = str(relation.to_id)
        # check if the task doesn't contain the related document allready
        if key in ids:
            continue
        label = relation.to_object.Title()
        terms.append(SimpleVocabulary.createTerm(key, key, label))

    return SimpleVocabulary(terms)
示例#6
0
    def _exec(self, bound_names, args, kw):
        """Call a Page Template"""
        self._cook_check()
        if not kw.has_key('args'):
            kw['args'] = args
        bound_names['options'] = kw

        try:
            response = self.REQUEST.RESPONSE
            if not response.headers.has_key('content-type'):
                response.setHeader('content-type', self.content_type)
        except AttributeError:
            pass

        # Execute the template in a new security context.
        security = AccessControl.getSecurityManager()
        bound_names['user'] = security.getUser()
        security.addContext(self)

        try:
            context = self.pt_getContext()
            context.update(bound_names)
            return self.pt_render(extra_context=bound_names)
        finally:
            security.removeContext(self)
示例#7
0
    def key_value_provider(self):
        request = getRequest()

        # if we are not logged in we are in the traversal and should not
        # do anything...
        user = AccessControl.getSecurityManager().getUser()
        if user == AccessControl.SpecialUsers.nobody:
            return

        info = getUtility(IContactInformation)
        comm = getUtility(IClientCommunicator)

        # get client
        client_id = request.get('client', request.get('form.widgets.client'))
        if type(client_id) in (list, tuple, set):
            client_id = client_id[0]

        if not info.is_client_assigned(client_id=client_id):
            raise ValueError(
                'Expected %s to be a assigned client of the current user.' %
                client_id)

        # get dossier path
        dossier_path = request.get('dossier_path',
                                   request.get('form.widgets.source_dossier'))
        if type(dossier_path) in (list, tuple, set):
            dossier_path = dossier_path[0]

        if dossier_path:
            cid = client_id
            if cid:
                for doc in comm.get_documents_of_dossier(cid, dossier_path):
                    key = doc.get('path')
                    value = doc.get('title')
                    yield (key, value)
示例#8
0
class HasProtectedMethods(SimpleItem):

    security = AccessControl.ClassSecurityInfo()

    def __init__(self, id):
        self.id = id

    @security.public
    def public_method(self):
        pass

    @security.protected('ppp')
    def pp_method(self):
        pass

    @security.protected('qqq')
    def qq_method(self):
        pass

    @security.protected('rrr')
    def rr_method(self):
        pass

    @security.private
    def private_method(self):
        pass
示例#9
0
def attachable_documents_vocabulary(context):
    terms = []

    user = AccessControl.getSecurityManager().getUser()
    if user == AccessControl.SpecialUsers.nobody:
        return SimpleVocabulary(terms)

    intids = getUtility(IIntIds)

    ids = []

    for doc in context.getFolderContents(
        full_objects=True,
        contentFilter={'portal_type': ['opengever.document.document',
                                       'ftw.mail.mail']}):

        key = str(intids.getId(doc))
        label = doc.Title()
        terms.append(SimpleVocabulary.createTerm(key, key, label))
        ids.append(key)

    for relation in getattr(context, 'relatedItems', []):
        key = str(relation.to_id)
        # check if the task doesn't contain the related document allready
        if key in ids:
            continue
        label = relation.to_object.Title()
        terms.append(SimpleVocabulary.createTerm(key, key, label))

    return SimpleVocabulary(terms)
示例#10
0
    def update_cache(self, xslt_obj, source, result, anonymous_only=1):
        """ Update the page cache, based on several conditions.
        
        """
        import time, md5, AccessControl
        
        sm = AccessControl.getSecurityManager()
        user_id = sm.getUser().getId()
        if anonymous_only and user_id != None:
            return 0
        
        checksum = md5.new(source).hexdigest()
        
        page_cache = getattr(self, '_page_cache', OOBTree())
        
        # create the cache file name -- include the user_id, primarily for
        # debugging
        xid = xslt_obj.getId()
        cache_fname = '%s_%s_%s' % (xid, user_id, checksum)
        cachekey = '%s%s' % (xid, checksum)
        if user_id == None:
            page_cache[cachekey] = (cache_fname, time.time(), 0)
        else:
            page_cache[cachekey] = (cache_fname, time.time(), 1)

        cache_file = file('%s/%s' % (self.cache_dir, cache_fname), 'w+')
        cache_file.write(result)
        cache_file.close()
        
        self._page_cache = page_cache
        
        return 1
示例#11
0
class CatalogTool(base.CatalogTool):

    security = AccessControl.ClassSecurityInfo()
    
    def reindexComments(self):
        pass
    
    def clearFindAndRebuild(self):
        """Empties catalog, then finds all contentish objects (i.e. objects
           with an indexObject method), and reindexes them.
           This may take a long time.
        """
        
        def indexObject(obj, path):	    
            if (base_hasattr(obj, 'indexObject') and
                safe_callable(obj.indexObject)):
                try:
                    obj.indexObject()
                    pdtool = obj.portal_discussion
                    if pdtool.isDiscussionAllowedFor(obj):                        
                        tb = pdtool.getDiscussionFor(obj)
                        for ob in tb.getReplies():
                                ob.indexObject()
                except TypeError:
                    # Catalogs have 'indexObject' as well, but they
                    # take different args, and will fail
                    pass
        self.manage_catalogClear()
        
        portal = aq_parent(aq_inner(self))
        portal.ZopeFindAndApply(portal, search_sub=True, apply_func=indexObject)
    def publishObject(self, object, message):
        """
        Publish an object for the first time in the repository

        Creates a new folder to hold the version history of this
        object and create the first version of the object, returning
        the new unique ID for this object
        """
        storage = self.getStorageForType(object.portal_type)
        objectId = storage.applyVersionControl(object)
        storage.createVersionFolder(object)
        user = AccessControl.getSecurityManager().getUser().getUserName()
        storage.checkinResource(object, message, user)

        self.cache.clearSearchCache()

        #FIXME: these things shouldn't be done here, but with some sort of event system
        # hitcount update
        hitcount = getToolByName(self, 'portal_hitcount', None)
        if hitcount:
            hitcount.registerObject(objectId, DateTime())

        # storage events (mostly collection printing, at the moment)
        pubobj = storage.getObject(objectId, 'latest')
        storage.notifyObjectRevised(pubobj, None)

        # Removing this 'event' until Lens V2
        #if object.getParent():
        ### FIXME: We really want the Zope3 event system for this.
        ### Once we get that, we'll want to use something to the effect of:
        ### zope.event.notify(ObjectRevisionPublished)
        #self.lens_tool.notifyLensDerivedObject(object)
        ### End Event System Hack

        return objectId
示例#13
0
def run():
  try:
    credentials = AccessControl.getCredentials("simple.py")
    connection = cx_Oracle.connect(credentials.user, credentials.password, credentials.connstr)
      
    cursor = connection.cursor()
    cursor.execute("""
      CREATE TABLE employees(first_name VARCHAR2(20), last_name VARCHAR2(20))""")
    print("Table has been created")
    values = [["ROBERT", "ROBERTSON"], ["ANDY", "ANDREWS"], ["MICHAEL", "MICHAELSON"]]
    cursor.executemany("INSERT INTO employees VALUES (:1, :2)", values)
    print("Inserted ", len(values), "employees into the table")
    cursor.execute("""
      SELECT first_name, last_name FROM employees""")
    for fname, lname in cursor:
      print("Selected employee:", fname, lname)
    cursor.execute("DROP TABLE employees")
    print("Table has been dropped")
    cursor.close()
    connection.close()
    print("Connection has been released")

  except Exception as e:
    # Something went wrong
    print("An error ocurred", str(e))
示例#14
0
def getTransitionVocab(context):

    if AccessControl.getSecurityManager().getUser(
    ) == AccessControl.SpecialUsers.nobody:
        return SimpleVocabulary([])

    wftool = getToolByName(context, 'portal_workflow')
    transitions = []
    if opengever.task.task.ITask.providedBy(context) and \
            context.REQUEST.URL.find('++add++opengever.task.task') == -1:
        for tdef in wftool.getTransitionsFor(context):
            transitions.append(
                SimpleVocabulary.createTerm(
                    tdef['id'], tdef['id'],
                    PMF(tdef['id'], default=tdef['title_or_id'])))
        return SimpleVocabulary(transitions)

    else:
        wf = wftool.get(wftool.getChainForPortalType('opengever.task.task')[0])
        state = wf.states.get(wf.initial_state)
        for tid in state.transitions:
            tdef = wf.transitions.get(tid, None)
            transitions.append(
                SimpleVocabulary.createTerm(
                    tdef.id, tdef.id, PMF(tdef.id, default=tdef.title_or_id)))
        return SimpleVocabulary(transitions)
示例#15
0
def _create_yearfolder(inbox, year):
    """creates the yearfolder for the given year"""

    _sm = AccessControl.getSecurityManager()
    AccessControl.SecurityManagement.newSecurityManager(
        inbox.REQUEST,
        AccessControl.SecurityManagement.SpecialUsers.system)
    try:
        # for creating the folder, we need to be a superuser since
        # normal user should not be able to add year folders.
        # --- help i18ndude ---
        msg = _(u'yearfolder_title', default=u'Closed ${year}',
                mapping=dict(year=str(year)))
        # --- / help i18ndude ---
        folder_title = translate(str(msg), msg.domain, msg.mapping,
                                 context=inbox.REQUEST, default=msg.default)
        folder = createContentInContainer(
            inbox, 'opengever.inbox.yearfolder',
            title=folder_title, id=year)
    except:
        AccessControl.SecurityManagement.setSecurityManager(_sm)
        raise
    else:
        AccessControl.SecurityManagement.setSecurityManager(_sm)

    return folder
示例#16
0
    def is_already_done(self, transition, text):
        """This method returns `True` if this exact request was already
        executed.
        This is the case when the sender client has a conflict error when
        committing and the sender-request needs to be re-done. In this case
        this view is called another time but the changes were already made
        and committed - so we need to return "OK" and do nothing.
        """

        response_container = IResponseContainer(self.context)
        if len(response_container) == 0:
            return False

        last_response = response_container[-1]
        current_user = AccessControl.getSecurityManager().getUser()

        if (
            last_response.transition == transition
            and last_response.creator == current_user.getId()
            and last_response.text == text
        ):
            return True

        else:
            return False
示例#17
0
    def publishObject(self, object, message):
        """
        Publish an object for the first time in the repository

        Creates a new folder to hold the version history of this
        object and create the first version of the object, returning
        the new unique ID for this object
        """
        storage = self.getStorageForType(object.portal_type)
        objectId = storage.applyVersionControl(object)
        storage.createVersionFolder(object)
        user = AccessControl.getSecurityManager().getUser().getUserName()
        storage.checkinResource(object, message, user)

        self.cache.clearSearchCache()

        #FIXME: these things shouldn't be done here, but with some sort of event system
        # hitcount update
        hitcount = getToolByName(self, 'portal_hitcount', None)
        if hitcount:
            hitcount.registerObject(objectId, DateTime())

        # storage events (mostly collection printing, at the moment)
        pubobj = storage.getObject(objectId, 'latest')
        storage.notifyObjectRevised(pubobj, None)

        # Removing this 'event' until Lens V2
        #if object.getParent():
            ### FIXME: We really want the Zope3 event system for this.
            ### Once we get that, we'll want to use something to the effect of:
            ### zope.event.notify(ObjectRevisionPublished)
            #self.lens_tool.notifyLensDerivedObject(object)
            ### End Event System Hack

        return objectId
示例#18
0
    def __enter__(self):
        assert self._original_security is None

        self._original_security = AccessControl.getSecurityManager()

        _system_user = AccessControl.SecurityManagement.SpecialUsers.system
        AccessControl.SecurityManagement.newSecurityManager(None, _system_user)
示例#19
0
class Plugin(PAS.plugins.BasePlugin.BasePlugin):
    security = AccessControl.ClassSecurityInfo()
    meta_type = 'LDAPAlchemy Plugin'

    # Tell PAS not to swallow our exceptions, do not use for production
    _dont_swallow_my_exceptions = True

    @security.public
    def authenticateCredentials(self, credentials):
        """see PAS.interfaces.plugins.IAuthenticationPlugin
        """
        login = credentials.get('login')
        pw = credentials.get('password')
        if not (login and pw):
            return None

        # XXX: no real ldapalchemy, yet, but barebone ldapy
        # also for now, we open/close the ldap connection for each call
        ld = ldapy.initialize('ldapi://ldapi')
        login_dn = 'cn=%s,o=o' % login

        try:
            ldapy.simple_bind_s(ld, login_dn, pw)
        except ldapy.InvalidCredentials:
            authinfo = None
        else:
            uid = login
            authinfo = (uid, login)
            ldapy.unbind(ld)

        return authinfo
示例#20
0
 def __visible_groups_for_current_user(self):
     securityManager = AccessControl.getSecurityManager()
     allGroups = self.get_all_groups()
     # Quite a simple process, really: itterate through all the groups,
     #   checking to see if the "messages" instance is visible.
     visibleGroups = []
     for group in allGroups:
         # AM: "Visible groups" should really be: groups which a user
         #   is a member of, public groups, and private groups.
         #   Therefore, we should only be checking the visibility of the
         #   group, not of the messages.
         #
         #   A separate method ("visible messages" or similar) should be
         #   used to determine what messages and files should be included
         #   in search results (and in turn, latest topics and files on a
         #   site homepage) should be shown to users.
         #   **HOWEVER** at this point in time, we do not make a
         #   distinction. Therefore, to preserve security, we define
         #   "visible groups" very restrictively.
         if (hasattr(group, 'messages')
             and securityManager.checkPermission('View', group)
             and securityManager.checkPermission(
                 'View', group.aq_explicit.messages)):
             visibleGroups.append(group)
     assert type(visibleGroups) == list
     return visibleGroups
示例#21
0
    def get_visible_groups(self):
        # get the top level site ID to use with the cache
        site_root = self.context.site_root()
        top_level_site_id = site_root.getId()

        user = AccessControl.getSecurityManager().getUser()
        userId = user.getId()
        groups = '-'.join(user.getGroups())
        key = '-'.join((top_level_site_id, self.siteInfo.id, groups))

        if self.siteUserVisibleGroupsIds.has_key(key):  # lint:ok
            visibleGroupsIds = self.siteUserVisibleGroupsIds.get(key)
            visibleGroups = []
            for groupId in visibleGroupsIds:
                try:
                    visibleGroups.append(getattr(self.groupsObj, groupId))
                except:
                    log.warn("trouble adding '%s' to visible groups" % groupId)
        else:
            top = time.time()
            visibleGroups = self.__visible_groups_for_current_user()
            visibleGroupsIds = [group.getId() for group in visibleGroups]
            self.siteUserVisibleGroupsIds.add(key, visibleGroupsIds)
            bottom = time.time()
            log.debug("Generated visible-groups for (%s) on %s (%s) in "
                      "%.2fms" % (userId, self.siteInfo.name, self.siteInfo.id,
                                  (bottom - top) * 1000.0))

        assert type(visibleGroups) == list, "visibleGroups is not a list"
        return visibleGroups
示例#22
0
    def participate_user(self):
        """Participates `self.user` on `self.context`.
        """
        local_roles = dict(self.context.get_local_roles())
        # get all current local roles of the user on this context
        user_roles = list(local_roles.get(self.member.getId(), []))
        user_roles.extend(self.roles())
        # make the roles unique
        user_roles = dict(zip(user_roles, user_roles)).keys()

        # Set the local roles with the security of the inviter. If
        # he has no longer permissions on this context this will
        # fail.
        _old_security_manager = AccessControl.getSecurityManager()
        _new_user = self.context.acl_users.getUserById(
            self.invitation.inviter)
        AccessControl.SecurityManagement.newSecurityManager(
            self.request, _new_user)
        try:
            self.context.manage_setLocalRoles(self.member.getId(),
                                              user_roles)
            self.context.reindexObjectSecurity()
        except:
            AccessControl.SecurityManagement.setSecurityManager(
                _old_security_manager)
            raise
        else:
            AccessControl.SecurityManagement.setSecurityManager(
                _old_security_manager)
示例#23
0
    def setUp(self):
        """Shared test environment set-up, ran before every test."""
        portal = self.portal = self.layer['portal']
        portal._setObject('hpm', HasProtectedMethods('hpm'))

        sm = AccessControl.getSecurityManager()
        sm._policy._verbose = 1

        for role in ('Member', 'VIP', 'Manager'):
            portal._addRole(role)

        for permission, roles in role_mapping:
            portal.manage_permission(permission, roles, 1)

        api.user.create(
            username='******',
            email='*****@*****.**',
            password='******',
            roles=('Member', 'VIP')
        )

        self._old_sm = AccessControl.SecurityManagement.getSecurityManager()

        AccessControl.SecurityManagement.newSecurityManager(
            self.portal.REQUEST,
            self.portal.acl_users.getUser('boss'),
        )
示例#24
0
    def get_visible_groups(self):
        # get the top level site ID to use with the cache
        site_root = self.context.site_root()
        top_level_site_id = site_root.getId()

        user = AccessControl.getSecurityManager().getUser()
        userId = user.getId()
        groups = '-'.join(user.getGroups())
        key = '-'.join((top_level_site_id, self.siteInfo.id, groups))

        if self.siteUserVisibleGroupsIds.has_key(key):  # lint:ok
            visibleGroupsIds = self.siteUserVisibleGroupsIds.get(key)
            visibleGroups = []
            for groupId in visibleGroupsIds:
                try:
                    visibleGroups.append(getattr(self.groupsObj, groupId))
                except:
                    log.warn("trouble adding '%s' to visible groups" % groupId)
        else:
            top = time.time()
            visibleGroups = self.__visible_groups_for_current_user()
            visibleGroupsIds = [group.getId() for group in visibleGroups]
            self.siteUserVisibleGroupsIds.add(key, visibleGroupsIds)
            bottom = time.time()
            log.debug("Generated visible-groups for (%s) on %s (%s) in "
                        "%.2fms" % (userId, self.siteInfo.name,
                                    self.siteInfo.id, (bottom - top) * 1000.0))

        assert type(visibleGroups) == list, "visibleGroups is not a list"
        return visibleGroups
示例#25
0
def getTransitionVocab(context):

    if AccessControl.getSecurityManager(
        ).getUser() == AccessControl.SpecialUsers.nobody:
        return SimpleVocabulary([])

    wftool = getToolByName(context, 'portal_workflow')
    transitions = []
    if opengever.task.task.ITask.providedBy(context) and \
            context.REQUEST.URL.find('++add++opengever.task.task') == -1:
        for tdef in wftool.getTransitionsFor(context):
            transitions.append(SimpleVocabulary.createTerm(
                    tdef['id'],
                    tdef['id'],
                    PMF(tdef['id'], default=tdef['title_or_id'])))
        return SimpleVocabulary(transitions)

    else:
        wf = wftool.get(wftool.getChainForPortalType('opengever.task.task')[0])
        state = wf.states.get(wf.initial_state)
        for tid in state.transitions:
            tdef = wf.transitions.get(tid, None)
            transitions.append(SimpleVocabulary.createTerm(
                    tdef.id,
                    tdef.id,
                    PMF(tdef.id, default=tdef.title_or_id)))
        return SimpleVocabulary(transitions)
示例#26
0
def _create_yearfolder(inbox, year):
    """creates the yearfolder for the given year"""

    _sm = AccessControl.getSecurityManager()
    AccessControl.SecurityManagement.newSecurityManager(
        inbox.REQUEST, AccessControl.SecurityManagement.SpecialUsers.system)
    try:
        # for creating the folder, we need to be a superuser since
        # normal user should not be able to add year folders.
        # --- help i18ndude ---
        msg = _(u'yearfolder_title',
                default=u'Closed ${year}',
                mapping=dict(year=str(year)))
        # --- / help i18ndude ---
        folder_title = translate(str(msg),
                                 msg.domain,
                                 msg.mapping,
                                 context=inbox.REQUEST,
                                 default=msg.default)
        folder = createContentInContainer(inbox,
                                          'opengever.inbox.yearfolder',
                                          title=folder_title,
                                          id=year)
    except:
        AccessControl.SecurityManagement.setSecurityManager(_sm)
        raise
    else:
        AccessControl.SecurityManagement.setSecurityManager(_sm)

    return folder
示例#27
0
class HasProtectedMethods(SimpleItem):

    security = AccessControl.ClassSecurityInfo()

    security.declarePublic('public_method')
    security.declareProtected('ppp', 'pp_method')
    security.declareProtected('qqq', 'qq_method')
    security.declareProtected('rrr', 'rr_method')
    security.declarePrivate('private_method')

    def __init__(self, id):
        self.id = id

    def public_method(self):
        pass

    def pp_method(self):
        pass

    def qq_method(self):
        pass

    def rr_method(self):
        pass

    def private_method(self):
        pass
 def member_groups(self):
     user = AccessControl.getSecurityManager().getUser()
     memberGroups = self.groupsInfo.get_member_groups_for_user(user, user)
     if self.maxGroupsToDisplay:
         memberGroups = memberGroups[:self.maxGroupsToDisplay]
     groups = map(IGSGroupInfo, memberGroups)
     return groups
class MemberData(BaseMemberData):

    security = AccessControl.ClassSecurityInfo()

    security.declarePrivate('setMemberProperties')

    def setMemberProperties(self, mapping):
        """Overridden to store a copy of certain user data fields in an SQL database"""
        # Only pass relevant fields to the database
        db_args = dict([(f, v) for (f, v) in mapping.items()
                        if f in DB_FIELDS and self.getProperty(f) != v])
        dbtool = getToolByName(self, 'portal_moduledb')
        if dbtool and db_args:
            # We have to pass in aq_parent to be our own parent,
            # otheriwse the ZSQL method will acquire blank arguments
            # from the property sheet
            if not self.member_catalog(getUserName=self.getId()):
                zLOG.LOG(
                    "MemberData", zLOG.INFO,
                    "INSERT memberdata for %s: %s" % (self.getId(), db_args))
                dbtool.sqlInsertMember(aq_parent=self.aq_parent,
                                       id=self.getId(),
                                       **db_args)
            else:
                zLOG.LOG(
                    "MemberData", zLOG.INFO,
                    "UPDATE memberdata for %s: %s" % (self.getId(), db_args))
                dbtool.sqlUpdateMember(aq_parent=self.aq_parent,
                                       id=self.getId(),
                                       **db_args)

        BaseMemberData.setMemberProperties(self, mapping)
示例#30
0
 def __visible_groups_for_current_user(self):
     securityManager = AccessControl.getSecurityManager()
     allGroups = self.get_all_groups()
     # Quite a simple process, really: itterate through all the groups,
     #   checking to see if the "messages" instance is visible.
     visibleGroups = []
     for group in allGroups:
         # AM: "Visible groups" should really be: groups which a user
         #   is a member of, public groups, and private groups.
         #   Therefore, we should only be checking the visibility of the
         #   group, not of the messages.
         #
         #   A separate method ("visible messages" or similar) should be
         #   used to determine what messages and files should be included
         #   in search results (and in turn, latest topics and files on a
         #   site homepage) should be shown to users.
         #   **HOWEVER** at this point in time, we do not make a
         #   distinction. Therefore, to preserve security, we define
         #   "visible groups" very restrictively.
         if (hasattr(group, 'messages')
                 and securityManager.checkPermission('View', group)
                 and securityManager.checkPermission(
                     'View', group.aq_explicit.messages)):
             visibleGroups.append(group)
     assert type(visibleGroups) == list
     return visibleGroups
示例#31
0
def checkPermission(permission, context=None):
    """
    Return true if the current user has the specified permission on the given
    context or the dmd; otherwise, return false.
    """
    manager = AccessControl.getSecurityManager()
    context = context or get_dmd()
    return manager.checkPermission(permission, context)
示例#32
0
def checkPermission(permission, context=None):
    """
    Return true if the current user has the specified permission on the given
    context or the dmd; otherwise, return false.
    """
    manager = AccessControl.getSecurityManager()
    context = context or get_dmd()
    return manager.checkPermission(permission, context)
示例#33
0
def Get_Ignored_Issues(ServerData, values, log):
    """Get summary of all ignored issues where Severity is Critical/Error and Code is NOT ServerData["ComplexityCode"]
    and issue ID of ignored issues without related comment"""

    temp_ignored = {}
    issue_id = []
    vals = copy(values)
    val = copy(values)
    vals['action'] = "search"

    for i in 1, 2:  # find all ignore Critical and Error issues

        vals["query"] = "severity:%d status:ignore -code:%s grouping:%s" % (
            i, ServerData["ComplexityCode"], ServerData["Grouping"])
        log.write("Getting not-ignored issues, query:\n %s" % vals)
        Response = AccessControl.RequestAPI(ServerData["url"], vals)
        Result = AccessControl.ParseAPI(ClassesAPI.IssuesBuild, Response)

        val["action"] = "issue_details"

        for issue in Result:  # Search for ignored issues without comments
            val["id"] = issue.id
            response = AccessControl.RequestAPI(ServerData["url"], val)
            issue_details = AccessControl.ParseAPI(ClassesAPI.IssuesDetail,
                                                   response)

            for index in range(len(issue_details[0].history)):
                if issue_details[0].history[index].status == u'Ignore':
                    if issue_details[0].history[index].comment == u'':
                        if (index - 1) < 0:
                            issue_id.append(issue.id)
                            break
                        elif issue_details[0].history[index -
                                                      1].comment == u'':
                            issue_id.append(issue.id)
                            break

        if i == 1:
            temp_ignored["crit_ignore"] = len(Result)

        elif i == 2:
            temp_ignored["err_ignore"] = len(Result)

    temp_ignored["no_message_ignore_id"] = str(issue_id).strip('[]')
    return temp_ignored
示例#34
0
 def __call__(self, *args, **kwargs):
     """Add the zope user to the security context, as done in
     PageTemplateFile"""
     if not kwargs.has_key('args'):
         kwargs['args'] = args
         bound_names = {'options': kwargs}
         security = AccessControl.getSecurityManager()
         bound_names['user'] = security.getUser()
         return self.pt_render(extra_context=bound_names)
 def __call__(self, *args, **kwargs):
     """Add the zope user to the security context, as done in
     PageTemplateFile"""
     if not kwargs.has_key('args'):
         kwargs['args'] = args
         bound_names = {'options': kwargs}
         security = AccessControl.getSecurityManager()
         bound_names['user'] = security.getUser()
         return self.pt_render(extra_context=bound_names)
示例#36
0
class MemberData(BaseMemberData):

    __implements__ = IMemberData

    security = AccessControl.ClassSecurityInfo()

    def __init__(self, id):
        self.id = id

    def getId(self):
        """Override to return the id we've stored"""
        return self.id

    security.declarePrivate('notifyModified')

    def notifyModified(self):
        # Recatalog this member
        cat = getToolByName(self, MEMBER_CATALOG)
        cat.catalog_object(self)

    security.declarePublic('getUser')

    def getUser(self):
        # First try using the acqusition context
        user = aq_parent(self)
        bcontext = aq_base(user)
        bcontainer = aq_base(aq_parent(aq_inner(self)))
        if bcontext is bcontainer or not hasattr(bcontext, 'getUserName'):
            # OK, the wrapper didn't work so let's try looking up the user by ID
            user_folder = getToolByName(self, 'acl_users')
            user = user_folder.getUser(self.getId())

        if user:
            return user
        else:
            raise 'MemberDataError', "Can't find user data for %s" % self.getId(
            )

    def getTool(self):
        return getToolByName(self, 'portal_memberdata')

    security.declarePublic('getMemberId')

    def getMemberId(self):
        return self.getId()

    ### GRUF interface

    security.declarePublic('getGroups')

    def getGroups(self):
        """Check to see if a user has a given role or roles."""
        try:
            return self.getUser().getGroups()
        except AttributeError:
            # Cope with users from non-GRUF user folders
            return ()
示例#37
0
def configure_zope(config_filename, debug_mode=False):
    """Read zope.conf with zdaemon^Wzcrap.
    """
    from Zope2.Startup import options, handlers
    import AccessControl

    del sys.argv[1:]
    opts = options.ZopeOptions()
    opts.configfile = config_filename
    opts.realize(raise_getopt_errs=0)

    handlers.handleConfig(opts.configroot, opts.confighandlers)
    AccessControl.setImplementation(
        opts.configroot.security_policy_implementation)
    AccessControl.setDefaultBehaviors(
        not opts.configroot.skip_ownership_checking,
        not opts.configroot.skip_authentication_checking,
        opts.configroot.verbose_security)
    App.config.setConfiguration(opts.configroot)
    set_zope_debug_mode(debug_mode)
示例#38
0
def issueTicket(ident):
    """ issues a timelimit ticket
    >>> type(issueTicket(object()))== type('')
    True
    """
    ticket = str(random.random())
    sm = AccessControl.getSecurityManager()
    user = sm.getUser()
    if user is None:
        raise Unauthorized('No currently authenticated user')
    ticketCache.set(user.getId(), ident, key=dict(ticket=ticket))
    return ticket
示例#39
0
    def test_file_download_no_notification_when_system(self):
        _original_security = AccessControl.getSecurityManager()

        _system_user = AccessControl.SecurityManagement.SpecialUsers.system
        AccessControl.SecurityManagement.newSecurityManager(None, _system_user)
        self.index_html()
        events = [e for e in eventtesting.getEvents()
                  if IFileDownloadedEvent.providedBy(e)]
        self.assertEqual(0, len(events))
        AccessControl.SecurityManagement.setSecurityManager(
            _original_security)
        _original_security = None
示例#40
0
def issueTicket(ident):
    """ issues a timelimit ticket
    >>> type(issueTicket(object()))== type('')
    True
    """
    ticket = str(random.random())
    sm = AccessControl.getSecurityManager()
    user = sm.getUser()
    if user is None:
        raise Unauthorized('No currently authenticated user')
    ticketCache.set(user.getId(), ident, key=dict(ticket=ticket))
    return ticket
示例#41
0
def Get_Complexity_Issues(ServerData, values, log):
    """Appends into temp_project data about complexity issues: 1) Sum of "Approved" issues - status: Not a problem
                                                               2) Sum of "Not approved" issues - Status != Not a problem
                                                               3) Issue ID and complexity value of top 10 most complex "Not approved" issues - as a tuple"""

    vals = copy(values)
    vals['action'] = 'search'
    vals['query'] = "code:%s" % ServerData["ComplexityCode"]
    log.write("Getting complexity issues, query:\n %s" % vals)
    complex_approve = 0
    complex_not_approve = 0
    complex_details = []

    temp_complex = {}

    import re
    Response = AccessControl.RequestAPI(ServerData["url"], vals)
    Result = AccessControl.ParseAPI(ClassesAPI.IssuesBuild, Response)

    for issue in Result:
        if issue.status == "Not a Problem":
            complex_approve += 1

        else:
            complex_not_approve += 1

            x = str(issue.message)
            y = re.search("[0-9]+(?=>)", x)
            y = int(y.group())
            complex_details.append((issue.id, y))

    complex_details = sorted(complex_details,
                             key=lambda score: score[1],
                             reverse=True)
    temp_complex["complex_approved"] = complex_approve
    temp_complex["complex_not_approved"] = complex_not_approve
    temp_complex["ComplexityDetails"] = complex_details[:10]

    return temp_complex
    def writeobj(self, obj, arcname=None):
        # Check if this user has access to this object.
        if not AccessControl.getSecurityManager().checkPermission("View", obj):
            raise "Unauthorized", "not authorized to View %s" % (obj.absolute_url())

        if hasattr(obj, "_original"):
            fsname = obj._original._get_fsname(obj._original.filename)
        elif hasattr(obj, "_get_fsname"):
            fsname = obj._get_fsname(obj.filename)
        else:
            raise Exception, "Can not determine filename for object."

        self.write(filename=fsname, arcname=arcname)
示例#43
0
def Get_Builds_List(url, values, log):
    """Returns the first and second latest list of builds for the project in values['project'], and N/A if either one does not exist"""

    vals = copy(values)
    temp_project = {}
    vals["action"] = "builds"
    log.write("Getting builds list, query:\n %s" % vals)
    Response = AccessControl.RequestAPI(url, vals)
    Result = AccessControl.ParseAPI(ClassesAPI.Build, Response)

    if len(Result) > 0:  # Find latest and second latest build dates and names

        temp_project["last_build"] = Result[0].date
        if len(Result) > 1:
            temp_project["prev_build"] = Result[1].date
        else:
            temp_project["prev_build"] = "N/A"

    else:
        temp_project["last_build"] = "N/A"
        temp_project["prev_build"] = "N/A"

    return temp_project
示例#44
0
class EMailAspect(Products.AlphaFlow.aspect.Aspect):

    zope.interface.implements(IEMailAspect)

    security = AccessControl.ClassSecurityInfo()

    aspect_type  = "email"

    security.declarePrivate('__call__')
    def __call__(self):
        """Send email."""
        work_items = [self.getWorkItem()]
        Products.AlphaFlow.activities.notify._send_email(
            self, self.getDefinition(), work_items)
示例#45
0
def get_roles_and_users():
    """Return the roles and users values for the current user,
    which can be used to query against a roles_and_users index.
    """
    user = AccessControl.getSecurityManager().getUser()
    if user == AccessControl.SpecialUsers.nobody:
        return ['Anonymous']

    result = set(['Anonymous'])
    result.update(user.getRoles())
    result.add('user:{}'.format(user.getId()))
    if hasattr(aq_base(user), 'getGroups'):
        result.update(map('user:{}'.format, user.getGroups()))
    return list(result)
示例#46
0
def portal_newsletters():
    """Return mailing-lists created with the newsletter tool."""

    root = component.queryUtility(Products.CMFPlone.interfaces.IPloneSiteRoot)
    if root is None:
        return []
    root = collective.dancing.utils.fix_request(root, 0)
    if 'portal_newsletters' in root.objectIds():
        channels = root['portal_newsletters']['channels'].objectValues()
        security = AccessControl.getSecurityManager()
        return [c for c in channels if
                security.checkPermission('View', c) and
                collective.singing.interfaces.IChannel.providedBy(c)]
    else:
        return []
示例#47
0
def portal_newsletters():
    """Return mailing-lists created with the newsletter tool."""

    root = component.queryUtility(Products.CMFPlone.interfaces.IPloneSiteRoot)
    if root is None:
        return []
    root = collective.dancing.utils.fix_request(root, 0)
    if 'portal_newsletters' in root.objectIds():
        channels = root['portal_newsletters']['channels'].objectValues()
        security = AccessControl.getSecurityManager()
        return [c for c in channels if
                security.checkPermission('View', c) and
                collective.singing.interfaces.IChannel.providedBy(c)]
    else:
        return []
示例#48
0
    def initProcess(self, definition, obj):
        """Create a new process instance for a content object."""
        # We need to handle the security for this methods ourselves. The user
        # has to have INIT_PROCESS on the content object.
        user = AccessControl.getSecurityManager().getUser()
        if not user.has_permission(gocept.alphaflow.config.INIT_PROCESS, obj):
            raise zExceptions.Unauthorized(
                "initProcess", obj, gocept.alphaflow.config.INIT_PROCESS)

        id = gocept.alphaflow.utils.generateUniqueId(definition.getId())
        instance = zope.component.getMultiAdapter(
            (definition, obj, id),
            gocept.alphaflow.interfaces.ILifeCycleObject)
        self.instances._setObject(id, instance)
        return self.instances[id]
示例#49
0
def Get_NotIgnored_Issues(ServerData, values, log):
    """Appends into "temp_project" data on non-ignored issues: 1) Sum of Critical issues
                                                               2) Sum of Error issues
                                                               3) Data of Complexity issues - assuming complexity issues are classified as Critical/Error"""
    temp = {}
    vals = copy(values)
    vals['action'] = "search"

    for i in 1, 2:  # find all non-ignore Critical and Error issues
        vals["query"] = "severity:%d -status:ignore -code:%s grouping:%s" % (
            i, ServerData["ComplexityCode"], ServerData["Grouping"])
        log.write("Getting ignored issues, query:\n %s" % vals)
        Response = AccessControl.RequestAPI(ServerData["url"], vals)
        Result = AccessControl.ParseAPI(ClassesAPI.IssuesBuild, Response)

        if i == 1:

            temp["crit_issues"] = len(Result)

        elif i == 2:

            temp["err_issues"] = len(Result)

    return temp
示例#50
0
    def __call__(self):
        """If user is not allowed to view PersonalOverview, redirect him
        to the repository root, otherwise behave like always.
        """
        user = AccessControl.getSecurityManager().getUser()
        if user == AccessControl.SecurityManagement.SpecialUsers.nobody:
            raise Unauthorized

        if not self.user_is_allowed_to_view():
            catalog = getToolByName(self.context, 'portal_catalog')
            repos = catalog(portal_type='opengever.repository.repositoryroot')
            repo_url = repos[0].getURL()
            return self.request.RESPONSE.redirect(repo_url)

        else:
            return super(PersonalOverview, self).__call__()
示例#51
0
    def __call__(self):
        """If user is not allowed to view PersonalOverview, redirect him
        to the repository root, otherwise behave like always.
        """
        user = AccessControl.getSecurityManager().getUser()
        if user == AccessControl.SecurityManagement.SpecialUsers.nobody:
            raise Unauthorized

        if not self.user_is_allowed_to_view():
            catalog = getToolByName(self.context, 'portal_catalog')
            repos = catalog(portal_type='opengever.repository.repositoryroot')
            repo_url = repos[0].getURL()
            return self.request.RESPONSE.redirect(repo_url)

        else:
            return super(PersonalOverview, self).__call__()
示例#52
0
def protect_edit_form(obj, event):
    """If the object is locked for the current user, let's redirect to
    the view of the object, where the lockinfo viewlet usually is.
    """

    # Since locking does not work for anonymous users, so we disable the
    # redirect for them. This also makes widget traversal work, since the
    # widget traversal is always anonymous.
    nobody = AccessControl.SecurityManagement.SpecialUsers.nobody
    if AccessControl.getSecurityManager().getUser() == nobody:
        return

    info = getMultiAdapter((obj, obj.REQUEST),
                                name="plone_lock_info")

    if info.is_locked_for_current_user():
        raise Redirect(obj.absolute_url())
示例#53
0
    def key_value_provider(self):
        """yield home dossiers
        key: relative path on home client
        value: "%(reference_number): %(title)"
        """

        # if we are not logged in we are in the traversal and should not
        # do anything...
        user = AccessControl.getSecurityManager().getUser()
        if user == AccessControl.SpecialUsers.nobody:
            return

        request = getRequest()

        info = getUtility(IContactInformation)
        comm = getUtility(IClientCommunicator)

        client_id = request.get(
            'client', request.get('form.widgets.client'))
        if type(client_id) in (list, tuple, set):
            client_id = client_id[0]
        client = info.get_client_by_id(client_id)

        if client and not info.is_client_assigned(client_id=client_id):
            raise ValueError(
                'Expected %s to be a assigned client of the current user.' %
                    client_id)

        elif client:
            # kss validation overrides getSite() hook with a bad object
            # but we need getSite to work properly, so we fix it.
            site = getSite()
            if site.__class__.__name__ == 'Z3CFormValidation':
                fixed_site = getToolByName(self.context,
                                           'portal_url').getPortalObject()
                setSite(fixed_site)
                dossiers = comm.get_open_dossiers(client.client_id)
                setSite(site)
            else:
                dossiers = comm.get_open_dossiers(client.client_id)

            for dossier in dossiers:
                yield (dossier['path'],
                       '%s: %s' % (dossier['reference_number'],
                                   dossier['title']))
示例#54
0
    def setUp(self):
        """Shared test environment set-up, ran before every test."""
        portal = self.portal = self.layer['portal']
        portal._setObject('hpm', HasProtectedMethods('hpm'))

        # This isn't necessary to the unit tests, it makes debugging them
        # easier when they go wrong. Like "verbose-security on" in zope.conf
        sm = AccessControl.getSecurityManager()
        sm._policy._verbose = 1

        # Roles need to be created by name before we can assign permissions
        # to them or grant them to users.
        for role in ('Member', 'VIP', 'Manager'):
            portal._addRole(role)

        for permission, roles in role_mapping:
            portal.manage_permission(permission, roles, 1)

        api.user.create(
            username='******',
            email='*****@*****.**',
            password='******',
            roles=('Member',),
        )

        api.user.create(
            username='******',
            email='*****@*****.**',
            password='******',
            roles=('Member', 'VIP'),
        )

        api.user.create(
            username='******',
            email='*****@*****.**',
            password='******',
            roles=('Member', 'Manager'),
        )

        self._old_sm = AccessControl.SecurityManagement.getSecurityManager()

        AccessControl.SecurityManagement.newSecurityManager(
            self.portal.REQUEST,
            self.portal.acl_users.getUser('boss'),
        )
    def __call__(self, context):
        """this utility calls plone.principalsource.Groups utility
        so we can overwrite this one if we want a diffrent source.
        """
        if context is None:
            context = getSite()

        factory = component.getUtility(
            schema.interfaces.IVocabularyFactory,
            name='plone.principalsource.Groups',
            context=context)
        items = factory(context)

        # check permission
        result = []

        gtool = getToolByName(context, 'portal_groups')

        items = []

        # Change SecurityManager - otherwise we dont receive all users form
        # existing_role_settings
        _old_security_manager = AccessControl.getSecurityManager()
        _new_user = AccessControl.SecurityManagement.SpecialUsers.system
        AccessControl.SecurityManagement.newSecurityManager(
            context.REQUEST,
            _new_user)
        try:
            sharing = context.restrictedTraverse('@@sharing')
            items = sharing.existing_role_settings()
        except:
            AccessControl.SecurityManagement.setSecurityManager(
                _old_security_manager)
            raise
        else:
            AccessControl.SecurityManagement.setSecurityManager(
                _old_security_manager)

        for item in items:
            if item['type'] == 'group':
                gid = item['id']
                group = gtool.getGroupById(gid)
                if sum([group.has_role(r) for r in context.validRoles()]):
                    result.append(item)
        return result
示例#56
0
    def extjs_enabled(self, view=None):
        """Returns `True` if extjs is enabled.
        """
        if view is None:
            view = self.request.get("PUBLISHED", None)

        if INoExtJS.providedBy(view):
            return False

        user = AccessControl.getSecurityManager().getUser()
        if user == AccessControl.SpecialUsers.nobody:
            # ExtJS is not supported for anonymous users, since we are not
            # able to store the state. Things such as sorting would not even
            # work in the session.
            return False

        registry = getUtility(IRegistry)
        return registry["ftw.tabbedview.interfaces." "ITabbedView.extjs_enabled"]
示例#57
0
    def set_default_tab(self, tab=None, view=None):
        """Sets the default tab. The id of the tab is passed as
        argument or in the request payload as ``tab``.
        """

        user = AccessControl.getSecurityManager().getUser()
        if user == AccessControl.SpecialUsers.nobody:
            tab = None

        else:
            tab = tab or self.request.get('tab')

        if not tab:
            return json.dumps([
                    'error',
                    translate('Error', 'plone', context=self.request),
                    translate(_(u'error_set_default_tab',
                                u'Could not set default tab.'),
                              context=self.request)])

        tab_title = translate(tab, 'ftw.tabbedview', context=self.request)
        success = [
            'info',
            translate('Information', 'plone', context=self.request),
            translate(_(u'info_set_default_tab',
                        u'The tab ${title} is now your default tab. ' +
                        u'This is a personal setting.',
                        mapping={'title': tab_title}),
                      context=self.request)]

        if not view and self.request.get('viewname', False):
            view = self.context.restrictedTraverse(
                self.request.get('viewname'))
        else:
            view = self

        key_generator = getMultiAdapter((self.context, view, self.request),
                                        IDefaultTabStorageKeyGenerator)
        key = key_generator.get_key()

        storage = IDictStorage(self)
        storage.set(key, tab.lower())

        return json.dumps(success)
示例#58
0
    def publishRevision(self, object, message):
        """
        Publish a revision of an object in the repository

        object: the object to place under version control.  It must
        implement IMetadata and IVersionedObject
        message: a string log message by the user
        baseVersion: the version of the object this is based on

        returns: unique ID string for the new object
        """

        if not self.isUnderVersionControl(object):
            raise CommitError, "Cannot publish revision of object %s not under version control" % object.getId()

        # handle to original object to preserve locked status, if necessary;
        # we could look this up after publication (and would have to with proper events),
        # but that would be version inspection
        origobj = object.getPublishedObject().latest

        storage = self.getStorageForType(object.portal_type)
        user = AccessControl.getSecurityManager().getUser().getUserName()
        storage.checkinResource(object, message, user)
        self.cache.clearSearchCache()

        ### FIXME: We really want the Zope3 event system for these.
        ### Once we get that, we'll want to use something to the effect of:
        ### zope.event.notify(ObjectRevisionPublished)
        try: # Grab the now-published version
            pubobj = object.getPublishedObject().latest
        except AttributeError:
            pass

        # lens events
        self.lens_tool.notifyLensRevisedObject(pubobj)

        # storage events (mostly collection printing, at the moment)
        storage.notifyObjectRevised(pubobj, origobj)

        # notice of change to all containing collections, latest version only
        container_objs = self.catalog(containedModuleIds=pubobj.objectId)
        for col in container_objs:
            colobj = col.getObject()
            colobj.notifyContentsRevised()
    def update(self):
        self.__updated = True
        self.messageQuery = MessageQuery(self.context)
        # Both of the following should be aquired from adapters.
        self.siteInfo = createObject('groupserver.SiteInfo', self.context)
        self.groupsInfo = createObject('groupserver.GroupsInfo', self.context)

        user = AccessControl.getSecurityManager().getUser()

        self.searchTokens = createObject('groupserver.SearchTextTokens', self.s)

        self.groupIds = [gId for gId in self.g if gId]

        memberGroupIds = []
        if self.mg and user.getId():
            memberGroupIds = [g.getId() for g in
                              self.groupsInfo.get_member_groups_for_user(user, user)]

        if self.groupIds:
            if memberGroupIds:
                self.groupIds = [gId for gId in self.groupIds if gId in memberGroupIds]
            else:
                self.groupIds = \
                    self.groupsInfo.filter_visible_group_ids(self.groupIds)
        else:
            if memberGroupIds:
                self.groupIds = memberGroupIds
            else:
                self.groupIds = self.groupsInfo.get_visible_group_ids()

        try:
            posts = self.messageQuery.post_search_keyword(
                self.searchTokens, self.siteInfo.get_id(), self.groupIds,
                self.a, limit=self.l + 1, offset=self.i)
        except SQLAlchemyError:
            log.exception("A problem occurred with a messageQuery:")
            self.__searchFailed = True
            return
        else:
            self.__searchFailed = False

        self.morePosts = (len(posts) == (self.l + 1))
        self.posts = posts[:self.l]