示例#1
0
    def setUp(self):
        super(TestAuthentication, self).setUp()

        with self._context("database"):
            # Create few users and groups
            gh = GroupHolder()
            ah = AvatarHolder()
            self._authMgr = AuthenticatorMgr()

            for i in xrange(1, 3):
                group = Group()
                group.setName("fake-group-%d" % i)
                group.setDescription("fake")
                group.setEmail("*****@*****.**" % i)
                group.setId("fake-group-%d" % i)
                avatar = Avatar()
                avatar.setName("fake-%d" % i)
                avatar.setSurName("fake")
                avatar.setOrganisation("fake")
                avatar.setLang("en_GB")
                avatar.setEmail("*****@*****.**" % i)
                avatar.setId("fake-%d" % i)
                avatar.activateAccount()
                group.addMember(avatar)
                ah.add(avatar)
                gh.add(group)
                identity = self._authMgr.createIdentity(LoginInfo("fake-%d" % i, "fake-%d" % i), avatar, "Local")
                self._authMgr.add(identity)
    def setUp(self):
        super(TestAuthentication, self).setUp()

        with self._context("database"):
            # Create few users and groups
            gh = GroupHolder()
            ah = AvatarHolder()
            self._authMgr = AuthenticatorMgr()

            for i in xrange(1, 3):
                group = Group()
                group.setName("fake-group-%d" % i)
                group.setDescription("fake")
                group.setEmail("*****@*****.**" % i)
                group.setId("fake-group-%d" % i)
                avatar = Avatar()
                avatar.setName("fake-%d" % i)
                avatar.setSurName("fake")
                avatar.setOrganisation("fake")
                avatar.setLang("en_GB")
                avatar.setEmail("*****@*****.**" % i)
                avatar.setId("fake-%d" % i)
                avatar.activateAccount()
                group.addMember(avatar)
                ah.add(avatar)
                gh.add(group)
                identity = self._authMgr.createIdentity(
                    LoginInfo("fake-%d" % i, "fake-%d" % i), avatar, "Local")
                self._authMgr.add(identity)
示例#3
0
 def testGroupHolder(self):
     gh = GroupHolder()
     ah = AvatarHolder()
     self.assert_(gh.getById("fake-group-1").containsUser(ah.getById("fake-1")))
     self.assertEqual(gh.match({"groupname": "fake-group-1"}, searchInAuthenticators=False)[0].getEmail(),
                      "*****@*****.**")
     self.assertEqual(len(gh.matchFirstLetter("f", searchInAuthenticators=False)), 2)
示例#4
0
def create_dummy_group():
    """
    Creates a dummy group for testing purposes.
    """
    gh = GroupHolder()
    dummy_group = create_group("fake_group", "fake", "*****@*****.**")
    gh.add(dummy_group)
    return dummy_group
示例#5
0
 def _checkParams(self):
     AdminService._checkParams(self)
     self._pm = ParameterManager(self._params)
     gh = GroupHolder()
     groupId = self._pm.extract("groupId", pType=str, allowEmpty=False)
     self._group = gh.getById(groupId)
     if self._group == None:
         raise ServiceError("ER-G0", _("Cannot find group with id %s") % groupId)
示例#6
0
def create_dummy_group():
    """
    Creates a dummy group for testing purposes.
    """
    gh = GroupHolder()
    dummy_group = create_group("fake_group", "fake", "*****@*****.**")
    gh.add(dummy_group)
    return dummy_group
示例#7
0
def migrateGroups(catalog):
    print "Migrating groups...",
    gh=GroupHolder()
    count=0
    for g in catalog.dump():
        gh._getIdx()[g.getId()]=g
        count+=1
    print "[Done:%s]"%count
示例#8
0
def migrateGroups(catalog):
    print "Migrating groups...",
    gh = GroupHolder()
    count = 0
    for g in catalog.dump():
        gh._getIdx()[g.getId()] = g
        count += 1
    print "[Done:%s]" % count
示例#9
0
 def getAllManagers(self):
     managers = set([self.getResponsible()])
     if self.customAtts.get('Simba List'):
         groups = GroupHolder().match({'name': self.customAtts['Simba List']},
                                      exact=True, forceWithoutExtAuth=True)
         if not groups:
             groups = GroupHolder().match({'name': self.customAtts['Simba List']}, exact=True)
         if groups and len(groups) == 1:
             managers |= set(groups[0].getMemberList())
     return list(managers)
 def testGroupHolder(self):
     gh = GroupHolder()
     ah = AvatarHolder()
     self.assert_(
         gh.getById("fake-group-1").containsUser(ah.getById("fake-1")))
     self.assertEqual(
         gh.match({"groupname": "fake-group-1"},
                  searchInAuthenticators=False)[0].getEmail(),
         "*****@*****.**")
     self.assertEqual(
         len(gh.matchFirstLetter("f", searchInAuthenticators=False)), 2)
示例#11
0
 def update( self ):
     """ Documentation in base class. """
     RoomBase.update( self )
     
     # Check Simba mailing list
     listName = self.customAtts.get( 'Simba List' )
     if listName:
         from MaKaC.user import GroupHolder
         groups = GroupHolder().match( { 'name': listName }, forceWithoutExtAuth = True )
         if not groups:
             groups = GroupHolder().match( { 'name': listName } )
         if not groups:
             self.customAtts['Simba List'] = 'Error: unknown mailing list'
     
     self._p_changed = True
示例#12
0
文件: user.py 项目: NIIF/indico
def retrieve_principal(principal):
    """
    Retrieves principal object from a `(type, id)` tuple.

    Valid principal types are 'Avatar' and 'Group'
    """
    from MaKaC.user import AvatarHolder, GroupHolder

    ah = AvatarHolder()
    gh = GroupHolder()

    type_, id_ = principal
    try:
        return ah.getById(id_) if type_ == 'Avatar' else gh.getById(id_)
    except KeyError:
        return None
示例#13
0
 def getByTypeId(cls, type, id):
     if type == 'Avatar':
         return cls(AvatarHolder().getById(id))
     elif type.endswith('Group'):
         return cls(GroupHolder().getById(id))
     else:
         return None
示例#14
0
    def testACL(self):
        block = self._createTestBlocking()
        grp = Group()
        grp.setName('Test')
        GroupHolder().add(grp)

        self.assertFalse(block.canOverride(self._avatar1))
        self.assertTrue(block.canOverride(self._avatar2))
        self.assertFalse(block.canOverride(self._avatar3))
        self.assertTrue(block.canOverride(self._avatar4))
        # Add user to acl
        block.addAllowed(self._avatar1)
        self.assertTrue(block.canOverride(self._avatar1))
        # Add empty group to acl
        block.addAllowed(grp)
        self.assertTrue(block.canOverride(self._avatar1))
        self.assertTrue(block.canOverride(self._avatar2))
        self.assertFalse(block.canOverride(self._avatar3))
        self.assertTrue(block.canOverride(self._avatar4))
        # Add user to group
        grp.addMember(self._avatar3)
        self.assertTrue(block.canOverride(self._avatar3))
        # Remove user from acl
        block.delAllowed(self._avatar1)
        self.assertFalse(block.canOverride(self._avatar1))
        # But add him to a permitted group!
        grp.addMember(self._avatar1)
        self.assertTrue(block.canOverride(self._avatar1))
        # Remove users from group
        for m in list(grp.getMemberList()):
            grp.removeMember(m)
        self.assertFalse(block.canOverride(self._avatar1))
        self.assertTrue(block.canOverride(self._avatar2))
        self.assertFalse(block.canOverride(self._avatar3))
        self.assertTrue(block.canOverride(self._avatar4))
示例#15
0
def create_group(monkeypatch_methods):
    """Returns a callable which lets you create dummy groups"""
    monkeypatch_methods('MaKaC.user.GroupHolder', MockGroupHolder)

    _groups = []
    gh = GroupHolder()

    def _create_group(id_):
        group = MockGroup()
        group.id = id_
        gh.add(group)
        _groups.append(group)
        return group

    yield _create_group

    for group in _groups:
        gh.remove(group)
示例#16
0
def retrieve_principals(iterable):
    """Retrieves principal objects from `(type, id)` tuples.

    Valid principal types are 'Avatar' and 'Group'
    """
    from MaKaC.user import AvatarHolder, GroupHolder

    ah = AvatarHolder()
    gh = GroupHolder()
    principals = []
    for type_, id_ in iterable:
        if type_ == 'Avatar':
            principal = ah.getById(id_)
        else:
            principal = gh.getById(id_)
        if principal:
            principals.append(principal)
    return principals
示例#17
0
文件: user.py 项目: NIIF/indico
def create_group(monkeypatch_methods):
    """Returns a callable which lets you create dummy groups"""
    monkeypatch_methods('MaKaC.user.GroupHolder', MockGroupHolder)

    _groups = []
    gh = GroupHolder()

    def _create_group(id_):
        group = MockGroup()
        group.id = id_
        gh.add(group)
        _groups.append(group)
        return group

    yield _create_group

    for group in _groups:
        gh.remove(group)
示例#18
0
    def update( self ):
        """ Documentation in base class. """
        RoomBase.update( self )

        # Check Simba mailing list
        listName = self.customAtts.get( 'Simba List' )
        if listName:
            from MaKaC.user import GroupHolder
            groups = GroupHolder().match( { 'name': listName }, forceWithoutExtAuth = True )
            if not groups:
                groups = GroupHolder().match( { 'name': listName } )
            if not groups:
                self.customAtts['Simba List'] = 'Error: unknown mailing list'

        # reindex - needed due to possible manager changes
        # super slow, though...
        Catalog.getIdx('user_room').unindex_obj(self.guid)
        Catalog.getIdx('user_room').index_obj(self.guid)

        self._p_changed = True
示例#19
0
def searchGroups(group="", searchExt=False):
    if group != "":
        # build criteria
        criteria = {"name": group}
        # search not obsolete groups
        groups = [
            group for group in GroupHolder().match(
                criteria, forceWithoutExtAuth=(not searchExt))
            if not group.isObsolete()
        ]
        return groups
    else:
        return []
示例#20
0
 def validate_principals(self, field):
     for item in field.data:
         try:
             type_ = item['_type']
             id_ = item['id']
         except Exception as e:
             raise ValidationError('Invalid principal data: {}'.format(e))
         if type_ not in ('Avatar', 'Group', 'LDAPGroup'):
             raise ValidationError(
                 'Invalid principal data: type={}'.format(type_))
         holder = AvatarHolder() if type_ == 'Avatar' else GroupHolder()
         if not holder.getById(id_):
             raise ValidationError('Invalid principal: {}:{}'.format(
                 type_, id_))
示例#21
0
def searchGroups(group="", searchExt=False):
    if group != "":
        # build criteria
        criteria = {"name": group}
        # search not obsolete groups
        groups = [
            group
            for group in GroupHolder().match(criteria,
                                             searchInAuthenticators=searchExt)
            if not group.isObsolete()
        ]
        return groups
    else:
        return []
示例#22
0
    def changeUserList(self, object, newList):
        # clone the list, to avoid problems
        allowedUsers = object.getAllowedToAccessList()[:]

        # user can be a user or group
        for user in allowedUsers:
            if not user.getId() in newList:
                object.revokeAccess(user)
            else:
                del newList[user.getId()]

        for elem in newList:
            if 'isGroup' in elem and elem['isGroup']:
                avatar = GroupHolder().getById(elem['id'])
            else:
                avatar = AvatarHolder().getById(elem['id'])
            object.grantAccess(avatar)
示例#23
0
    def changeUserList(self, object, newList):
        # clone the list, to avoid problems
        allowedUsers = object.getAllowedToAccessList()[:]

        # user can be a user or group
        for user in allowedUsers:
            if not user.getId() in newList:
                object.revokeAccess(user)
            else:
                del newList[user.getId()]

        for elem in newList:
            # TODO: Change this, when DictPickler goes away
            if ('isGroup' in elem and elem['isGroup']) or \
                   ('_fossil' in elem and elem['_fossil'] == 'group'):
                avatar = GroupHolder().getById(elem['id'])
            else:
                avatar = AvatarHolder().getById(elem['id'])
            object.grantAccess(avatar)
示例#24
0
def searchPeople(surName="", name="", organisation="", email="", group="", conferenceId=None, exactMatch=True, searchExt=False):
    results = {}
    if surName != "" or name != "" or organisation != "" or email != "":
        # build criteria
        criteria = {
            "surName": surName,
            "name": name,
            "organisation": organisation,
            "email": email
        }
        # search users
        people = AvatarHolder().match(criteria, exact=exactMatch, forceWithoutExtAuth=(not searchExt))
        # search authors
        if conferenceId != None:
            try:
                conference = ConferenceHolder().getById(conferenceId)
                authorIndex = conference.getAuthorIndex()
                authors = authorIndex.match(criteria, exact=exactMatch)
                # merge with users
                users = people
                people = []
                emails = []
                for user in users:
                    people.append(user)
                    emails.extend(user.getEmails())
                for author in authors:
                    if author.getEmail() not in emails:
                        people.append(author)
            except:
                pass
        results["people"] = people
    if group != "":
        # build criteria
        criteria = {
            "name": group
        }
        # search groups
        groups = GroupHolder().match(criteria, forceWithoutExtAuth=(not searchExt))
        results["groups"] = groups
    return results
示例#25
0
 def getPrincipal(self):
     if self._type == 'Avatar':
         return AvatarHolder().getById(self._id)
     else:
         return GroupHolder().getById(self._id)
示例#26
0
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Indico;if not, see <http://www.gnu.org/licenses/>.

from MaKaC.common import DBMgr
from MaKaC.user import GroupHolder
"""
Set as obsolete the groups listed in a file
"""

fileGroups = 'GroupsDeletedInAD.txt'

DBMgr.getInstance().startRequest()
error = False
gh = GroupHolder()
groupIdx = gh._getIdx()

groupsObsoletes = open(fileGroups, 'r')
for group in groupsObsoletes.readlines():
    gr = groupIdx.get(group.rstrip())
    if gr != None:
        gr.setObsolete(True)

if not error:
    DBMgr.getInstance().endRequest()
    print "Groups set as obsoleted."
    print "No error. The change are saved"
else:
    print "There were errors. The changes was not saved"
示例#27
0
## You should have received a copy of the GNU General Public License
## along with Indico;if not, see <http://www.gnu.org/licenses/>.


from indico.core.db import DBMgr
from MaKaC.user import GroupHolder

"""
Set as obsolete the groups listed in a file
"""

fileGroups='GroupsDeletedInAD.txt'

DBMgr.getInstance().startRequest()
error = False
gh = GroupHolder()
groupIdx=gh._getIdx()

groupsObsoletes = open(fileGroups,'r')
for group in groupsObsoletes.readlines():
    gr=groupIdx.get(group.rstrip())
    if gr != None:
        gr.setObsolete(True)

if not error:
    DBMgr.getInstance().endRequest()
    print "Groups set as obsoleted."
    print "No error. The change are saved"
else:
    print "There were errors. The changes was not saved"
示例#28
0
## CDS Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDS Indico; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

from MaKaC.common import DBMgr
from MaKaC.user import AvatarHolder, Avatar, GroupHolder
from MaKaC.conference import CategoryManager, ConferenceHolder

ch = ConferenceHolder()
ah = AvatarHolder()
gh = GroupHolder()

print "Cleaning index..."
userIds = []

DBMgr.getInstance().startRequest()

for av in ah.getList():
    userIds.append(av.getId())

DBMgr.getInstance().endRequest()

i = 0
total = len(userIds)
for id in userIds:
    print "processed %d users on %d"%(i, total)
示例#29
0
from MaKaC.conference import CategoryManager
from MaKaC.webinterface.urlHandlers import UHCategoryDisplay, UHConferenceDisplay


def checkGroup (obj, group):
    ac = obj.getAccessController()
    if group in ac.allowed:
        return True
    return False

def showSubCategory(cat, group):
    if checkGroup(cat, group):
        print "%s - %s"%(cat.getName(), UHCategoryDisplay.getURL(cat))
    if cat.hasSubcategories():
        for subcat in cat.getSubCategoryList():
            showSubCategory(subcat,group)
    else:
        for conference in  cat.getConferenceList():
           if checkGroup(conference, group):
               print "%s - %s"%(conference.getName(), UHConferenceDisplay.getURL(conference))

DBMgr.getInstance().startRequest()
cm=CategoryManager()
cat=cm.getById("XXXX")
group = GroupHolder().getById("YYYYY")
showSubCategory(cat, group)


DBMgr.getInstance().endRequest()

 def entity(self):
     if self.entity_type == 'Avatar':
         return AvatarHolder().getById(self.entity_id)
     else:  # Group, LDAPGroup
         return GroupHolder().getById(self.entity_id)
示例#31
0
    def _addMaterialType(self, text, user):

        from MaKaC.common.fossilize import fossilize
        from MaKaC.fossils.conference import ILocalFileExtendedFossil, ILinkFossil

        Logger.get('requestHandler').debug('Adding %s - request %s' %
                                           (self._uploadType, request))

        mat, newlyCreated = self._getMaterial()

        # if the material still doesn't exist, create it
        if newlyCreated:
            protectedAtResourceLevel = False
        else:
            protectedAtResourceLevel = True

        resources = []
        if self._uploadType in ['file', 'link']:
            if self._uploadType == "file":
                for fileEntry in self._files:
                    resource = LocalFile()
                    resource.setFileName(fileEntry["fileName"])
                    resource.setFilePath(fileEntry["filePath"])
                    resource.setDescription(self._description)
                    if self._displayName == "":
                        resource.setName(resource.getFileName())
                    else:
                        resource.setName(self._displayName)

                    if not type(self._target) is Category:
                        log_info = {
                            "subject":
                            "Added file %s%s" % (fileEntry["fileName"], text)
                        }
                        self._target.getConference().getLogHandler().logAction(
                            log_info, log.ModuleNames.MATERIAL)
                    resources.append(resource)
                    # in case of db conflict we do not want to send the file to conversion again, nor re-store the file

            elif self._uploadType == "link":

                for link in self._links:
                    resource = Link()
                    resource.setURL(link["url"])
                    resource.setDescription(self._description)
                    if self._displayName == "":
                        resource.setName(resource.getURL())
                    else:
                        resource.setName(self._displayName)

                    if not type(self._target) is Category:
                        log_info = {
                            "subject":
                            "Added link %s%s" % (resource.getURL(), text)
                        }
                        self._target.getConference().getLogHandler().logAction(
                            log_info, log.ModuleNames.MATERIAL)
                    resources.append(resource)

            status = "OK"
            info = resources
        else:
            status = "ERROR"
            info = "Unknown upload type"
            return mat, status, info

        # forcedFileId - in case there is a conflict, use the file that is
        # already stored
        repoIDs = []
        for i, resource in enumerate(resources):
            if self._repositoryIds:
                mat.addResource(resource, forcedFileId=self._repositoryIds[i])
            else:
                mat.addResource(resource, forcedFileId=None)

            #apply conversion
            if self._topdf and not isinstance(resource, Link):
                file_ext = os.path.splitext(
                    resource.getFileName())[1].strip().lower()
                if fileConverter.CDSConvFileConverter.hasAvailableConversionsFor(
                        file_ext):
                    # Logger.get('conv').debug('Queueing %s for conversion' % resource.getFilePath())
                    fileConverter.CDSConvFileConverter.convert(
                        resource.getFilePath(), 'pdf', mat)
                    resource.setPDFConversionRequestDate(nowutc())

            # store the repo id, for files
            if isinstance(resource, LocalFile) and self._repositoryIds is None:
                repoIDs.append(resource.getRepositoryId())

            if protectedAtResourceLevel:
                protectedObject = resource
            else:
                protectedObject = mat
                mat.setHidden(self._visibility)
                mat.setAccessKey(self._password)

                protectedObject.setProtection(self._statusSelection)

            for userElement in self._userList:
                if 'isGroup' in userElement and userElement['isGroup']:
                    avatar = GroupHolder().getById(userElement['id'])
                else:
                    avatar = AvatarHolder().getById(userElement['id'])
                protectedObject.grantAccess(avatar)

        self._topdf = False
        if self._repositoryIds is None:
            self._repositoryIds = repoIDs

        return mat, status, fossilize(
            info, {
                "MaKaC.conference.Link": ILinkFossil,
                "MaKaC.conference.LocalFile": ILocalFileExtendedFossil
            })
示例#32
0
##
## Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Indico;if not, see <http://www.gnu.org/licenses/>.

from MaKaC.common import DBMgr
from MaKaC.user import AvatarHolder, Avatar, GroupHolder
from MaKaC.conference import CategoryManager, ConferenceHolder

ch = ConferenceHolder()
ah = AvatarHolder()
gh = GroupHolder()

print "Cleaning index..."
userIds = []

DBMgr.getInstance().startRequest()

for av in ah.getList():
    userIds.append(av.getId())

DBMgr.getInstance().endRequest()

i = 0
total = len(userIds)
for id in userIds:
    print "processed %d users on %d"%(i, total)