Ejemplo n.º 1
0
    def _removeProxy(self, command, proxyType):
        record = yield recordForPrincipalID(self.dir, command['Principal'])
        if record is None:
            self.respondWithError("Principal not found: %s" % (command['Principal'],))
            returnValue(None)

        proxyRecord = yield recordForPrincipalID(self.dir, command['Proxy'])
        if proxyRecord is None:
            self.respondWithError("Proxy not found: %s" % (command['Proxy'],))
            returnValue(None)

        txn = self.store.newTransaction()
        yield Delegates.removeDelegate(txn, record, proxyRecord, (proxyType == "write"))
        yield txn.commit()
        yield self.respondWithProxies(command, record, proxyType)
Ejemplo n.º 2
0
    def _removeProxy(self, command, proxyType):
        record = yield recordForPrincipalID(self.dir, command['Principal'])
        if record is None:
            self.respondWithError("Principal not found: %s" % (command['Principal'],))
            returnValue(None)

        proxyRecord = yield recordForPrincipalID(self.dir, command['Proxy'])
        if proxyRecord is None:
            self.respondWithError("Proxy not found: %s" % (command['Proxy'],))
            returnValue(None)

        txn = self.store.newTransaction()
        yield removeDelegate(txn, record, proxyRecord, (proxyType == "write"))
        yield txn.commit()
        yield self.respondWithProxies(command, record, proxyType)
Ejemplo n.º 3
0
 def _listProxies(self, command, proxyType):
     record = yield recordForPrincipalID(self.dir, command['Principal'])
     if record is None:
         self.respondWithError("Principal not found: %s" %
                               (command['Principal'], ))
         returnValue(None)
     yield self.respondWithProxies(command, record, proxyType)
Ejemplo n.º 4
0
def action_setAutoAcceptGroup(store, record, autoAcceptGroup):
    if record.recordType == RecordType.group:
        print("Setting auto-accept-group for {record} is not allowed.".format(
            record=prettyRecord(record)))

    elif (record.recordType == RecordType.user
          and not config.Scheduling.Options.AutoSchedule.AllowUsers):
        print("Setting auto-accept-group for {record} is not allowed.".format(
            record=prettyRecord(record)))

    else:
        groupRecord = yield recordForPrincipalID(record.service,
                                                 autoAcceptGroup)
        if groupRecord is None or groupRecord.recordType != RecordType.group:
            print("Invalid principal ID: {id}".format(id=autoAcceptGroup))
        else:
            print("Setting auto-accept-group to {group} for {record}".format(
                group=prettyRecord(groupRecord),
                record=prettyRecord(record),
            ))

            # Get original fields
            newFields = record.fields.copy()

            # Set new values
            newFields[
                record.service.fieldName.autoAcceptGroup] = groupRecord.uid

            updatedRecord = DirectoryRecord(record.service, newFields)
            yield record.service.updateRecords([updatedRecord], create=False)
Ejemplo n.º 5
0
    def action_addgroupmembers(self, j):
        try:
            grpID = j["group"]
        except KeyError:
            self._error("error", "No 'group' member in root JSON object.")
        try:
            memberIDs = j["members"]
        except KeyError:
            self._error("error", "No 'members' member in root JSON object.")

        try:
            record = yield recordForPrincipalID(self._directory, grpID)
        except ValueError:
            record = None
        if record is None:
            self._error(
                "error",
                "No group with id '{}' in the directory.".format(grpID))

        existingMembers = yield record.members()
        existingMemberUIDs = set([member.uid for member in existingMembers])
        add = set()
        invalid = set()
        exists = set()
        for memberID in memberIDs:
            memberRecord = yield recordForPrincipalID(self._directory,
                                                      memberID)
            if memberRecord is None:
                invalid.add(memberID)
            elif memberRecord.uid in existingMemberUIDs:
                exists.add(memberRecord)
            else:
                add.add(memberRecord)

        if add:
            yield record.addMembers(add)
            yield record.service.updateRecords([record], create=False)

        returnValue(
            self._ok(
                "ok", "Added group members", {
                    "group": grpID,
                    "added": self._recordsToJSON(add),
                    "exists": self._recordsToJSON(exists),
                    "invalid": sorted(invalid),
                }))
Ejemplo n.º 6
0
    def action_removegroupmembers(self, j):
        try:
            grpID = j["group"]
        except KeyError:
            self._error("error", "No 'group' member in root JSON object.")
        try:
            memberIDs = j["members"]
        except KeyError:
            self._error("error", "No 'members' member in root JSON object.")

        try:
            record = yield recordForPrincipalID(self._directory, grpID)
        except ValueError:
            record = None
        if record is None:
            self._error(
                "error",
                "No group with id '{}' in the directory.".format(grpID))

        existingMembers = yield record.members()
        existingMemberUIDs = set([member.uid for member in existingMembers])
        remove = set()
        invalid = set()
        missing = set()
        for memberID in memberIDs:
            memberRecord = yield recordForPrincipalID(self._directory,
                                                      memberID)
            if memberRecord is None:
                invalid.add(memberID)
            elif memberRecord.uid not in existingMemberUIDs:
                missing.add(memberRecord)
            else:
                remove.add(memberRecord)

        if remove:
            record.removeMembers(remove)
            yield record.service.updateRecords([record], create=False)

        returnValue(
            self._ok(
                "ok", "Removed group members", {
                    "group": grpID,
                    "removed": self._recordsToJSON(remove),
                    "missing": self._recordsToJSON(missing),
                    "invalid": sorted(invalid),
                }))
Ejemplo n.º 7
0
    def action_addgroupmembers(self, j):
        try:
            grpID = j["group"]
        except KeyError:
            self._error("error", "No 'group' member in root JSON object.")
        try:
            memberIDs = j["members"]
        except KeyError:
            self._error("error", "No 'members' member in root JSON object.")

        try:
            record = yield recordForPrincipalID(self._directory, grpID)
        except ValueError:
            record = None
        if record is None:
            self._error("error", "No group with id '{}' in the directory.".format(grpID))

        existingMembers = yield record.members()
        existingMemberUIDs = set([member.uid for member in existingMembers])
        add = set()
        invalid = set()
        exists = set()
        for memberID in memberIDs:
            memberRecord = yield recordForPrincipalID(self._directory, memberID)
            if memberRecord is None:
                invalid.add(memberID)
            elif memberRecord.uid in existingMemberUIDs:
                exists.add(memberRecord)
            else:
                add.add(memberRecord)

        if add:
            yield record.addMembers(add)
            yield record.service.updateRecords([record], create=False)

        returnValue(self._ok("ok", "Added group members", {
            "group": grpID,
            "added": self._recordsToJSON(add),
            "exists": self._recordsToJSON(exists),
            "invalid": sorted(invalid),
        }))
Ejemplo n.º 8
0
    def action_removegroupmembers(self, j):
        try:
            grpID = j["group"]
        except KeyError:
            self._error("error", "No 'group' member in root JSON object.")
        try:
            memberIDs = j["members"]
        except KeyError:
            self._error("error", "No 'members' member in root JSON object.")

        try:
            record = yield recordForPrincipalID(self._directory, grpID)
        except ValueError:
            record = None
        if record is None:
            self._error("error", "No group with id '{}' in the directory.".format(grpID))

        existingMembers = yield record.members()
        existingMemberUIDs = set([member.uid for member in existingMembers])
        remove = set()
        invalid = set()
        missing = set()
        for memberID in memberIDs:
            memberRecord = yield recordForPrincipalID(self._directory, memberID)
            if memberRecord is None:
                invalid.add(memberID)
            elif memberRecord.uid not in existingMemberUIDs:
                missing.add(memberRecord)
            else:
                remove.add(memberRecord)

        if remove:
            record.removeMembers(remove)
            yield record.service.updateRecords([record], create=False)

        returnValue(self._ok("ok", "Removed group members", {
            "group": grpID,
            "removed": self._recordsToJSON(remove),
            "missing": self._recordsToJSON(missing),
            "invalid": sorted(invalid),
        }))
Ejemplo n.º 9
0
def migrateWiki(store, principalID):
    """
    Iterate calendar homes looking for wiki principals; create resources
    for each.
    """

    directory = store.directoryService()
    recordType = CalRecordType.resource
    prefix = WikiDirectoryService.uidPrefix
    ch = schema.CALENDAR_HOME

    if principalID is not None:
        delegateRecord = yield recordForPrincipalID(directory, principalID)
    else:
        delegateRecord = None

    # Look up in the DB all the uids starting with the wiki prefix
    txn = store.newTransaction()
    rows = (yield Select(
        [
            ch.OWNER_UID,
        ],
        From=ch,
        Where=(ch.OWNER_UID.StartsWith(prefix)),
    ).on(txn))
    yield txn.commit()

    # For each wiki uid, if the resource record does not already exist,
    # create a record
    for uid in [row[0] for row in rows]:
        uid = uid.decode("utf-8")
        record = yield directory.recordWithUID(uid)
        if record is None:
            name = uid[len(prefix):]
            fields = {
                directory.fieldName.recordType: recordType,
                directory.fieldName.uid: uid,
                directory.fieldName.shortNames: [name],
                directory.fieldName.fullNames: [name],
                directory.fieldName.hasCalendars: True,
                directory.fieldName.hasContacts: False,
            }
            record = DirectoryRecord(directory, fields)
            yield record.service.updateRecords([record], create=True)
            print("Added '{}'".format(name))

            # Refetch the record
            yield directory.flush()
            record = yield directory.recordWithUID(uid)
            if delegateRecord is not None:
                txn = store.newTransaction()
                yield Delegates.addDelegate(txn, record, delegateRecord, True)
                yield txn.commit()
Ejemplo n.º 10
0
def _addRemoveProxy(msg, fn, store, record, proxyType, *proxyIDs):
    directory = store.directoryService()
    readWrite = (proxyType == "write")
    for proxyID in proxyIDs:
        proxyRecord = yield recordForPrincipalID(directory, proxyID)
        if proxyRecord is None:
            print("Invalid principal ID: %s" % (proxyID, ))
        else:
            txn = store.newTransaction()
            yield fn(txn, record, proxyRecord, readWrite)
            yield txn.commit()
            print("{msg} {proxy} as a {proxyType} proxy for {record}".format(
                msg=msg,
                proxy=prettyRecord(proxyRecord),
                proxyType=proxyType,
                record=prettyRecord(record)))
Ejemplo n.º 11
0
def runPrincipalActions(service, store, principalIDs, actions):
    directory = store.directoryService()
    for principalID in principalIDs:
        # Resolve the given principal IDs to records
        try:
            record = yield recordForPrincipalID(directory, principalID)
        except ValueError:
            record = None

        if record is None:
            sys.stderr.write("Invalid principal ID: %s\n" % (principalID,))
            continue

        # Performs requested actions
        for action in actions:
            (yield action[0](store, record, *action[1:]))
            print("")
Ejemplo n.º 12
0
def runPrincipalActions(service, store, principalIDs, actions):
    directory = store.directoryService()
    for principalID in principalIDs:
        # Resolve the given principal IDs to records
        try:
            record = yield recordForPrincipalID(directory, principalID)
        except ValueError:
            record = None

        if record is None:
            sys.stderr.write("Invalid principal ID: %s\n" % (principalID, ))
            continue

        # Performs requested actions
        for action in actions:
            (yield action[0](store, record, *action[1:]))
            print("")
Ejemplo n.º 13
0
def _addRemoveProxy(msg, fn, store, record, proxyType, *proxyIDs):
    directory = store.directoryService()
    readWrite = (proxyType == "write")
    for proxyID in proxyIDs:
        proxyRecord = yield recordForPrincipalID(directory, proxyID)
        if proxyRecord is None:
            print("Invalid principal ID: %s" % (proxyID,))
        else:
            txn = store.newTransaction()
            yield fn(txn, record, proxyRecord, readWrite)
            yield txn.commit()
            print(
                "{msg} {proxy} as a {proxyType} proxy for {record}".format(
                    msg=msg, proxy=prettyRecord(proxyRecord),
                    proxyType=proxyType, record=prettyRecord(record)
                )
            )
Ejemplo n.º 14
0
def printGroupCacherInfo(service, store, principalIDs):
    """
    Print all groups that have been delegated to, their cached members, and
    who delegated to those groups.
    """
    directory = store.directoryService()
    txn = store.newTransaction()
    if not principalIDs:
        groupUIDs = yield txn.allGroupDelegates()
    else:
        groupUIDs = []
        for principalID in principalIDs:
            record = yield recordForPrincipalID(directory, principalID)
            if record:
                groupUIDs.append(record.uid)

    for groupUID in groupUIDs:
        (
            groupID, name, _ignore_membershipHash, modified, _ignore_extant
        ) = yield txn.groupByUID(
            groupUID
        )
        print("Group: \"{name}\" ({uid})".format(name=name, uid=groupUID))

        for txt, readWrite in (("read-only", False), ("read-write", True)):
            delegatorUIDs = yield txn.delegatorsToGroup(groupID, readWrite)
            for delegatorUID in delegatorUIDs:
                delegator = yield directory.recordWithUID(delegatorUID)
                print(
                    "...has {rw} access to {rec}".format(
                        rw=txt, rec=prettyRecord(delegator)
                    )
                )

        print("Group members:")
        memberUIDs = yield txn.groupMemberUIDs(groupID)
        for memberUID in memberUIDs:
            record = yield directory.recordWithUID(memberUID)
            print(prettyRecord(record))

        print("Last cached: {} GMT".format(modified))
        print()

    yield txn.commit()
Ejemplo n.º 15
0
 def render(self, request):
     """
     Create a L{WebAdminPage} to render HTML content for this request, and
     return a response.
     """
     resourceId = request.args.get('resourceId', [''])[0]
     if resourceId:
         record = yield recordForPrincipalID(self.directory, resourceId)
         yield self.resourceActions(request, record)
     htmlContent = yield flattenString(request, WebAdminPage(self))
     response = Response()
     response.stream = MemoryStream(htmlContent)
     for (header, value) in (
         ("content-type", self.contentType()),
         ("content-encoding", self.contentEncoding()),
     ):
         if value is not None:
             response.headers.setHeader(header, value)
     returnValue(response)
Ejemplo n.º 16
0
    def action_listgroupmembers(self, j):
        try:
            grpID = j["group"]
        except KeyError:
            self._error("error", "No 'group' member in root JSON object.")

        try:
            record = yield recordForPrincipalID(self._directory, grpID)
        except ValueError:
            record = None
        if record is None:
            self._error("error", "No group with id '{}' in the directory.".format(grpID))

        members = yield record.members()

        returnValue(self._ok("ok", "Group membership", {
            "group": grpID,
            "members": self._recordsToJSON(members),
        }))
Ejemplo n.º 17
0
    def action_listgroupmembers(self, j):
        try:
            grpID = j["group"]
        except KeyError:
            self._error("error", "No 'group' member in root JSON object.")

        try:
            record = yield recordForPrincipalID(self._directory, grpID)
        except ValueError:
            record = None
        if record is None:
            self._error("error", "No group with id '{}' in the directory.".format(grpID))

        members = yield record.members()

        returnValue(self._ok("ok", "Group membership", {
            "group": grpID,
            "members": self._recordsToJSON(members),
        }))
Ejemplo n.º 18
0
def action_removeGroupMember(store, record, *memberIDs):
    directory = store.directoryService()
    existingMembers = yield record.members()
    existingMemberUIDs = set([member.uid for member in existingMembers])
    remove = set()
    for memberID in memberIDs:
        memberRecord = yield recordForPrincipalID(directory, memberID)
        if memberRecord is None:
            print("Invalid member ID: %s" % (memberID, ))
        elif memberRecord.uid not in existingMemberUIDs:
            print("Missing member ID: %s" % (memberID, ))
        else:
            remove.add(memberRecord)

    if remove:
        yield record.removeMembers(remove)
        for memberRecord in remove:
            print("Removed {member} for {record}".format(
                member=prettyRecord(memberRecord),
                record=prettyRecord(record)))
        yield record.service.updateRecords([record], create=False)
Ejemplo n.º 19
0
def action_addGroupMember(store, record, *memberIDs):
    directory = store.directoryService()
    existingMembers = yield record.members()
    existingMemberUIDs = set([member.uid for member in existingMembers])
    add = set()
    for memberID in memberIDs:
        memberRecord = yield recordForPrincipalID(directory, memberID)
        if memberRecord is None:
            print("Invalid member ID: %s" % (memberID, ))
        elif memberRecord.uid in existingMemberUIDs:
            print("Existing member ID: %s" % (memberID, ))
        else:
            add.add(memberRecord)

    if add:
        yield record.addMembers(add)
        for memberRecord in add:
            print("Added {member} for {record}".format(
                member=prettyRecord(memberRecord),
                record=prettyRecord(record)))
        yield record.service.updateRecords([record], create=False)
Ejemplo n.º 20
0
def printGroupCacherInfo(service, store, principalIDs):
    """
    Print all groups that have been delegated to, their cached members, and
    who delegated to those groups.
    """
    directory = store.directoryService()
    txn = store.newTransaction()
    if not principalIDs:
        groupUIDs = yield txn.allGroupDelegates()
    else:
        groupUIDs = []
        for principalID in principalIDs:
            record = yield recordForPrincipalID(directory, principalID)
            if record:
                groupUIDs.append(record.uid)

    for groupUID in groupUIDs:
        group = yield txn.groupByUID(groupUID)
        print("Group: \"{name}\" ({uid})".format(name=group.name, uid=group.groupUID))

        for txt, readWrite in (("read-only", False), ("read-write", True)):
            delegatorUIDs = yield txn.delegatorsToGroup(group.groupID, readWrite)
            for delegatorUID in delegatorUIDs:
                delegator = yield directory.recordWithUID(delegatorUID)
                print(
                    "...has {rw} access to {rec}".format(
                        rw=txt, rec=prettyRecord(delegator)
                    )
                )

        print("Group members:")
        memberUIDs = yield txn.groupMemberUIDs(group.groupID)
        for memberUID in memberUIDs:
            record = yield directory.recordWithUID(memberUID)
            print(prettyRecord(record))

        print("Last cached: {} GMT".format(group.modified))
        print()

    yield txn.commit()
Ejemplo n.º 21
0
def action_addGroupMember(store, record, *memberIDs):
    directory = store.directoryService()
    existingMembers = yield record.members()
    existingMemberUIDs = set([member.uid for member in existingMembers])
    add = set()
    for memberID in memberIDs:
        memberRecord = yield recordForPrincipalID(directory, memberID)
        if memberRecord is None:
            print("Invalid member ID: %s" % (memberID,))
        elif memberRecord.uid in existingMemberUIDs:
            print("Existing member ID: %s" % (memberID,))
        else:
            add.add(memberRecord)

    if add:
        yield record.addMembers(add)
        for memberRecord in add:
            print(
                "Added {member} for {record}".format(
                    member=prettyRecord(memberRecord),
                    record=prettyRecord(record)
                )
            )
        yield record.service.updateRecords([record], create=False)
Ejemplo n.º 22
0
def action_setAutoAcceptGroup(store, record, autoAcceptGroup):
    if record.recordType == RecordType.group:
        print(
            "Setting auto-accept-group for {record} is not allowed.".format(
                record=prettyRecord(record)
            )
        )

    elif (
        record.recordType == RecordType.user and
        not config.Scheduling.Options.AutoSchedule.AllowUsers
    ):
        print(
            "Setting auto-accept-group for {record} is not allowed.".format(
                record=prettyRecord(record)
            )
        )

    else:
        groupRecord = yield recordForPrincipalID(record.service, autoAcceptGroup)
        if groupRecord is None or groupRecord.recordType != RecordType.group:
            print("Invalid principal ID: {id}".format(id=autoAcceptGroup))
        else:
            print("Setting auto-accept-group to {group} for {record}".format(
                group=prettyRecord(groupRecord),
                record=prettyRecord(record),
            ))

            # Get original fields
            newFields = record.fields.copy()

            # Set new values
            newFields[record.service.fieldName.autoAcceptGroup] = groupRecord.uid

            updatedRecord = DirectoryRecord(record.service, newFields)
            yield record.service.updateRecords([updatedRecord], create=False)
Ejemplo n.º 23
0
def action_removeGroupMember(store, record, *memberIDs):
    directory = store.directoryService()
    existingMembers = yield record.members()
    existingMemberUIDs = set([member.uid for member in existingMembers])
    remove = set()
    for memberID in memberIDs:
        memberRecord = yield recordForPrincipalID(directory, memberID)
        if memberRecord is None:
            print("Invalid member ID: %s" % (memberID,))
        elif memberRecord.uid not in existingMemberUIDs:
            print("Missing member ID: %s" % (memberID,))
        else:
            remove.add(memberRecord)

    if remove:
        yield record.removeMembers(remove)
        for memberRecord in remove:
            print(
                "Removed {member} for {record}".format(
                    member=prettyRecord(memberRecord),
                    record=prettyRecord(record)
                )
            )
        yield record.service.updateRecords([record], create=False)
Ejemplo n.º 24
0
 def _listProxies(self, command, proxyType):
     record = yield recordForPrincipalID(self.dir, command['Principal'])
     if record is None:
         self.respondWithError("Principal not found: %s" % (command['Principal'],))
         returnValue(None)
     yield self.respondWithProxies(command, record, proxyType)