Exemple #1
0
def searchPattern(request, pattern):
    if request.is_ajax():
        if pattern == "":
            return HttpResponse("Please enter a query.")

        objectsTemplate = LBEObjectTemplate.objects.all()
        resultObjects = []
        groupsTemplate = LBEGroup.objects.all()
        resultGroups = []

        for ot in objectsTemplate:
            objectHelper = LBEObjectInstanceHelper(ot)
            result = objectHelper.searchPattern(pattern)
            if result:
                resultObjects.append(result)

        for gt in groupsTemplate:
            groupHelper = GroupInstanceHelper(gt)
            result = groupHelper.searchPattern(pattern)
            if result:
                resultGroups.append(result)

        return render_to_response(
            "directory/default/search/result.html",
            {"objects": resultObjects, "groups": resultGroups},
            context_instance=RequestContext(request),
        )
Exemple #2
0
def viewObjectInstance(request, lbeObject_id, objectName=None):
    try:
        objectTemplate = LBEObjectTemplate.objects.get(id=lbeObject_id)
        instanceHelper = LBEObjectInstanceHelper(objectTemplate)
        obj = instanceHelper.getValuesDecompressed(objectName)
        # Replace attributes name by displayName:
        objectInstance = SortedDict()
        attributesInstance = LBEAttributeInstance.objects.filter(lbeObjectTemplate=objectTemplate).order_by("position")
        for attribute in attributesInstance:
            if attribute.reference is not None:
                try:
                    ref = obj[attribute.lbeAttribute.name][0].split("=")[1].split(",")[0]
                    objectInstance[attribute.lbeAttribute.displayName] = [
                        '<a href="/directory/object/view/'
                        + str(attribute.reference.objectTemplate.id)
                        + "/"
                        + ref
                        + '">'
                        + ref
                        + "</a>"
                    ]
                except BaseException:
                    pass
            else:
                objectInstance[attribute.lbeAttribute.displayName] = obj[attribute.lbeAttribute.name]
        objectInstance["name"] = objectName
        objectInstance["displayName"] = obj[objectTemplate.instanceDisplayNameAttribute.name][0]
    except BaseException as e:
        objectInstance = []
    return render_to_response(
        "directory/default/object/view.html",
        {"object": objectInstance, "obj_id": lbeObject_id},
        context_instance=RequestContext(request),
    )
Exemple #3
0
 def start(self):
     print " Upgrade Server..."
     for objectTemplate in LBEObjectTemplate.objects.all():
         print " |-> \033[91m" + objectTemplate.name + '\033[0m:'
         objHelper = LBEObjectInstanceHelper(objectTemplate)
         try:
             scope = objHelper.callScriptClassMethod("search_scope")
         except BaseException:
             scope = 0
         objTarget = self.target.searchObjects(objectTemplate, scope)
         objBackend = self.backend.searchObjects(objectTemplate)
         # Target to Backend:
         for ot in objTarget:
             exist = False
             for ob in objBackend:
                 if ot.name == ob.name:
                     self._upgradeObject(objectTemplate, objHelper, ot, ob)
                     exist = True
                     break
             if not exist:
                 self._deleteORCreate(objectTemplate, ot)
         # Synced object:
         objectTemplate.synced_at = django.utils.timezone.now()
         objectTemplate.save()
     print " End."
Exemple #4
0
 def changeRDN(self, lbeObjectTemplate, lbeObjectInstance, oldRDNAttribute, oldRDNValue):
     objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)
     # Old RDN:
     dn = oldRDNAttribute + '=' + oldRDNValue + ',' + objectHelper.callScriptClassMethod('base_dn')
     # New RDN:
     rdnAttributeName = lbeObjectTemplate.instanceNameAttribute.name
     newDN = rdnAttributeName + '=' + lbeObjectInstance.attributes[rdnAttributeName][0]
     self.handler.changeRDN(dn, newDN.encode("utf-8"))
Exemple #5
0
    def searchNewObjects(self, lbeObjectTemplate, SCOPE, start=0, page=0):
        objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)
        filter = '(&(createTimeStamp>=' + self._ldap_date(lbeObjectTemplate.imported_at) + ')'
        for oc in objectHelper.callScriptClassMethod('object_classes'):
            filter += '(objectClass=' + oc + ')'
        filter += ')'

        return self.searchObjects(lbeObjectTemplate, SCOPE, filter, start, page)
Exemple #6
0
    def delete(self, lbeObjectTemplate, lbeObjectInstance):
        objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)

        rdnAttributeName = lbeObjectTemplate.instanceNameAttribute.name
        dn = rdnAttributeName + '=' + lbeObjectInstance.attributes[rdnAttributeName][
            0] + ',' + objectHelper.callScriptClassMethod('base_dn')

        return self.handler.delete(dn)
Exemple #7
0
 def _getRDN(self, objectTemplate, listID):
     objectHelper = LBEObjectInstanceHelper(objectTemplate)
     baseDN = objectHelper.callScriptClassMethod("base_dn")
     listObjectID = []
     for ID in listID:
         dn = objectTemplate.instanceNameAttribute.name + "=" + ID + "," + baseDN
         listObjectID.append(dn)
     return listObjectID
Exemple #8
0
    def delete(self, lbeObjectTemplate, lbeObjectInstance):
        objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)

        rdnAttributeName = lbeObjectTemplate.instanceNameAttribute.name
        dn = rdnAttributeName + '=' + lbeObjectInstance.attributes[
            rdnAttributeName][0] + ',' + objectHelper.callScriptClassMethod(
                'base_dn')

        return self.handler.delete(dn)
Exemple #9
0
    def create(self, lbeObjectTemplate, lbeObjectInstance):
        objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)

        rdnAttributeName = lbeObjectTemplate.instanceNameAttribute.name
        dn = rdnAttributeName + '=' + lbeObjectInstance.attributes[rdnAttributeName][
            0] + ',' + objectHelper.callScriptClassMethod('base_dn')

        return self.handler.add(dn, lbeObjectInstanceToAddModList(lbeObjectInstance,
                                                                  objectHelper.callScriptClassMethod('object_classes')))
Exemple #10
0
 def update(self, lbeObjectTemplate, lbeObjectInstance, SCOPE):
     objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)
     if not isinstance(lbeObjectTemplate, LBEGroup):
         ignore_attributes = objectHelper.callScriptClassMethod("ignore_attributes")
     else:
         ignore_attributes = []
     # RDN Attribute:
     rdnAttributeName = lbeObjectTemplate.instanceNameAttribute.name
     dn = rdnAttributeName + '=' + lbeObjectInstance.attributes[rdnAttributeName][
         0] + ',' + objectHelper.callScriptClassMethod('base_dn')
     LDAPValues = self.searchObjects(lbeObjectTemplate, SCOPE,
                                     rdnAttributeName + '=' + lbeObjectInstance.attributes[rdnAttributeName][0])[
         0].attributes
     # Need to check if the RDN changed:
     if not lbeObjectInstance.attributes[rdnAttributeName][0] == lbeObjectInstance.changes['set'][rdnAttributeName][
         0] and not lbeObjectInstance.changes['set'][rdnAttributeName][0] == '':
         newDN = rdnAttributeName + '=' + lbeObjectInstance.changes['set'][rdnAttributeName][0]
         self.handler.changeRDN(dn, newDN.encode("utf-8"))
         dn = newDN + ',' + objectHelper.callScriptClassMethod('base_dn')
     # Update:
     for key, value in lbeObjectInstance.changes['set'].items():
         if key in ignore_attributes:
             continue
         noKey = not LDAPValues.has_key(key)# key exists into the object target?
         if isinstance(lbeObjectTemplate, LBEGroup) and value == []:
             objectHelper = GroupInstanceHelper(lbeObjectTemplate, lbeObjectInstance)
             modList = [(ldap.MOD_DELETE, key.encode("utf-8"), LDAPValues[objectHelper.attributeName][0].encode("utf-8") )]
             try:
                 self.handler.update(dn, modList)
             except BaseException:
                 pass # do not care if object does not exist
         elif noKey or not value == LDAPValues[key] and not value[0] == '':
             # 1 value: Replace
             if len(value) == 1:
                 if noKey:
                     # ADD:
                     modList = [(ldap.MOD_ADD, key.encode("utf-8"), value[0].encode("utf-8") )]
                 else:
                     # REPLACE:
                     modList = [(ldap.MOD_REPLACE, key.encode("utf-8"), value[0].encode("utf-8") )]
                 self.handler.update(dn, modList)
             else: # MultiValue:
                 if noKey:
                     # ADD:
                     for val in value:
                         modList = [(ldap.MOD_ADD, key.encode("utf-8"), val.encode("utf-8") )]
                         self.handler.update(dn, modList)
                 else:
                     # REMOVE:
                     for val in LDAPValues[key]:
                         modList = [(ldap.MOD_DELETE, key.encode("utf-8"), val.encode("utf-8") )]
                         self.handler.update(dn, modList)
                     # ADD:
                     for val in value:
                         modList = [(ldap.MOD_ADD, key.encode("utf-8"), val.encode("utf-8") )]
                         self.handler.update(dn, modList)
Exemple #11
0
    def searchNewObjects(self, lbeObjectTemplate, SCOPE, start=0, page=0):
        objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)
        filter = '(&(createTimeStamp>=' + self._ldap_date(
            lbeObjectTemplate.imported_at) + ')'
        for oc in objectHelper.callScriptClassMethod('object_classes'):
            filter += '(objectClass=' + oc + ')'
        filter += ')'

        return self.searchObjects(lbeObjectTemplate, SCOPE, filter, start,
                                  page)
Exemple #12
0
def approvalObjectInstance(request, lbeObject_id, objectName):
    backend = BackendHelper()
    lbeObject = LBEObjectTemplate.objects.get(id=lbeObject_id)
    # change status code user:
    instanceHelper = LBEObjectInstanceHelper(lbeObject)
    instanceHelper.approval(objectName)
    # Current page from the object status changed:
    position = backend.positionObject(lbeObject.name, objectName)
    lengthMax = 10
    page = int(math.ceil(position / float(lengthMax)))
    return HttpResponseRedirect("/")  # return index(request,lbeObject_id,page)
Exemple #13
0
    def searchObjects(self, lbeObjectTemplate, SCOPE, filter=None, start=0, page=0):
        result_set = []
        # Call methods from object's script to get basedn and objectClass
        objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)
        if filter is None:
            filter = '(&'
            for oc in objectHelper.callScriptClassMethod('object_classes'):
                filter += '(objectClass=' + oc + ')'
            filter += ')'#(modifyTimestamp>'+str(calendar.timegm(lbeObjectTemplate.synced_at.utctimetuple()))+'Z))'

        # Search in object's basedn
        if SCOPE != 0 and SCOPE != 1 and SCOPE != 2:
            SCOPE = 0 # BASE

        for dn, entry in self.handler.search(objectHelper.callScriptClassMethod('base_dn'), filter, SCOPE,
                                             ['*', '+']):
            # Create an empty instance
            objectInstance = LBEObjectInstance(lbeObjectTemplate,
                                               name=entry[lbeObjectTemplate.instanceNameAttribute.name][0])
            # Add attributes defined in the template. Other ones are ignored
            try:  # Object
                for attributeInstance in lbeObjectTemplate.lbeattributeinstance_set.all():
                    try:
                        objectInstance.attributes[attributeInstance.lbeAttribute.name] = entry[
                            attributeInstance.lbeAttribute.name]
                    except KeyError, e:
                        logger.warning(
                            'The attribute ' + attributeInstance.lbeAttribute.name + ' does not exist in LDAP object: ' + dn)
                    # Set displayName and few others attributes
                objectInstance.displayName = entry[lbeObjectTemplate.instanceDisplayNameAttribute.name][0]
                objectInstance.status = OBJECT_STATE_IMPORTED
                objectInstance.created_at = datetime.datetime.strptime(entry['createTimestamp'][0], '%Y%m%d%H%M%SZ')
                try:
                    objectInstance.updated_at = datetime.datetime.strptime(entry['modifyTimestamp'][0], '%Y%m%d%H%M%SZ')
                except KeyError:
                    objectInstance.updated_at = datetime.datetime.strptime(entry['createTimestamp'][0], '%Y%m%d%H%M%SZ')
                result_set.append(objectInstance)
            except AttributeError:  # Group:
                groupInstance = GroupInstanceHelper(lbeObjectTemplate)
                objectInstance.displayName = entry['cn'][0]
                objectInstance.attributes[u'cn'] = entry['cn']
                if groupInstance.attributeName in entry:
                    objectInstance.attributes[groupInstance.attributeName] = entry[groupInstance.attributeName]
                else:
                    objectInstance.attributes[groupInstance.attributeName] = []
                objectInstance.status = OBJECT_STATE_IMPORTED
                objectInstance.created_at = datetime.datetime.strptime(entry['createTimestamp'][0], '%Y%m%d%H%M%SZ')
                try:
                    objectInstance.updated_at = datetime.datetime.strptime(entry['modifyTimestamp'][0], '%Y%m%d%H%M%SZ')
                except KeyError:
                    objectInstance.updated_at = datetime.datetime.strptime(entry['createTimestamp'][0], '%Y%m%d%H%M%SZ')
                result_set.append(objectInstance)
Exemple #14
0
    def getInstanceObjectClasses(self, lbeObjectTemplate, lbeObjectInstance, SCOPE):
        objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)

        rdnAttributeName = lbeObjectTemplate.instanceNameAttribute.name
        dn = rdnAttributeName + '=' + lbeObjectInstance.attributes[rdnAttributeName][
            0] + ',' + objectHelper.callScriptClassMethod('base_dn')

        filter = '(objectClass=*)'

        object = self.handler.search(dn, filter, SCOPE)
        if object == []:
            return []
        return object[0][1]["objectClass"]
Exemple #15
0
    def create(self, lbeObjectTemplate, lbeObjectInstance):
        objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)

        rdnAttributeName = lbeObjectTemplate.instanceNameAttribute.name
        dn = rdnAttributeName + '=' + lbeObjectInstance.attributes[
            rdnAttributeName][0] + ',' + objectHelper.callScriptClassMethod(
                'base_dn')

        return self.handler.add(
            dn,
            lbeObjectInstanceToAddModList(
                lbeObjectInstance,
                objectHelper.callScriptClassMethod('object_classes')))
Exemple #16
0
    def getInstanceObjectClasses(self, lbeObjectTemplate, lbeObjectInstance,
                                 SCOPE):
        objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)

        rdnAttributeName = lbeObjectTemplate.instanceNameAttribute.name
        dn = rdnAttributeName + '=' + lbeObjectInstance.attributes[
            rdnAttributeName][0] + ',' + objectHelper.callScriptClassMethod(
                'base_dn')

        filter = '(objectClass=*)'

        object = self.handler.search(dn, filter, SCOPE)
        if object == []:
            return []
        return object[0][1]["objectClass"]
Exemple #17
0
 def upgrade(self, lbeObjectTemplate, lbeObjectInstance, SCOPE):
     objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)
     if not isinstance(lbeObjectTemplate, LBEGroup):
         ignore_attributes = objectHelper.callScriptClassMethod("ignore_attributes")
     else:
         ignore_attributes = []
     # RDN Attribute:
     rdnAttributeName = lbeObjectTemplate.instanceNameAttribute.name
     dn = rdnAttributeName + '=' + lbeObjectInstance.attributes[rdnAttributeName][
         0] + ',' + objectHelper.callScriptClassMethod('base_dn')
     LDAPValues = self.searchObjects(lbeObjectTemplate, SCOPE,
                                     rdnAttributeName + '=' + lbeObjectInstance.attributes[rdnAttributeName][0])[
         0].attributes
     # Update:
     for key, value in lbeObjectInstance.attributes.items():
         if key in ignore_attributes:
             continue
         noKey = not LDAPValues.has_key(key)# key exists into the object target?
         if noKey or not value == LDAPValues[key]:
             # 1 value: Replace
             if len(value) == 1:
                 if noKey:
                     # ADD:
                     modList = [(ldap.MOD_ADD, key.encode("utf-8"), value[0].encode("utf-8") )]
                 else:
                     # REPLACE:
                     modList = [(ldap.MOD_REPLACE, key.encode("utf-8"), value[0].encode("utf-8") )]
                 self.handler.update(dn, modList)
             else: # MultiValue:
                 if noKey:
                     # ADD:
                     for val in value:
                         modList = [(ldap.MOD_ADD, key.encode("utf-8"), val.encode("utf-8") )]
                         self.handler.update(dn, modList)
                 else:
                     # REMOVE:
                     for val in LDAPValues[key]:
                         modList = [(ldap.MOD_DELETE, key.encode("utf-8"), val.encode("utf-8") )]
                         self.handler.update(dn, modList)
                     # ADD:
                     for val in value:
                         modList = [(ldap.MOD_ADD, key.encode("utf-8"), val.encode("utf-8") )]
                         self.handler.update(dn, modList)
Exemple #18
0
 def _notExistObjectLBE(self):
     print '  Checking for Objects which do not exist into LBE but in LDAP Server:'
     for objectTemplate in LBEObjectTemplate.objects.all():
         print "  - \033[35m" + objectTemplate.name + '\033[0m...'
         objHelper = LBEObjectInstanceHelper(objectTemplate)
         try:
             scope = objHelper.callScriptClassMethod("search_scope")
         except BaseException:
             scope = 0
         objTarget = self.target.searchObjects(objectTemplate, scope)
         objBackend = self.backend.searchObjects(objectTemplate)
         number = 0
         for ot in objTarget:
             exist = False
             for ob in objBackend:
                 if ot.name == ob.name:
                     exist = True
                     break
             if not exist:
                 number += 1
                 print "    " + ot.name
         if number == 0:
             print '    \033[91m<None>\033[0m'
     print ""
     print '  Checking for Groups which do not exist into LBE but in LDAP Server:'
     number = 0
     for groupTemplate in LBEGroup.objects.all():
         grpHelper = GroupInstanceHelper(groupTemplate)
         try:
             scope = grpHelper.callScriptClassMethod("search_scope")
         except BaseException:
             scope = 0
         grpTarget = self.target.searchObjects(
             groupTemplate, scope, '(cn=' + groupTemplate.displayName + ')')
         grpBackend = self.backend.searchObjectsByPattern(
             groupTemplate, groupTemplate.displayName)
         if not grpBackend:
             print "   - \033[36m" + groupTemplate.displayName + "\033[0m does not exists."
             number += 1
     if number == 0:
         print '    \033[91m<None>\033[0m'
Exemple #19
0
def deleteObjectInstance(request, lbeObject_id, objectName):
    backend = BackendHelper()
    lbeObject = LBEObjectTemplate.objects.get(id=lbeObject_id)
    # change status code user:
    instanceHelper = LBEObjectInstanceHelper(lbeObject)

    # Remove the object from groups if exists:
    for group in LBEGroup.objects.all():
        groupHelper = GroupInstanceHelper(group)
        try:
            groupHelper.removeObjectInstance(lbeObject, objectName)
        except KeyError:
            pass  # same values

    # Set to Delete for object Instance
    instanceHelper.remove(objectName)
    # Current page from the object deleted:
    position = backend.positionObject(lbeObject.name, objectName)
    lengthMax = 10
    page = int(math.ceil(position / float(lengthMax)))
    return HttpResponseRedirect("/directory/" + lbeObject_id + "/1")
Exemple #20
0
    def changeClass(self,lbeObjectTemplate, lbeObjectInstance,SCOPE, oldClasses, newClasses):
        objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)
        # RDN Attribute:
        rdnAttributeName = lbeObjectTemplate.instanceNameAttribute.name
        dn = rdnAttributeName + '=' + lbeObjectInstance.attributes[rdnAttributeName][
            0] + ',' + objectHelper.callScriptClassMethod('base_dn')
        LDAPValues = self.searchObjects(lbeObjectTemplate, SCOPE,
                                        rdnAttributeName + '=' + lbeObjectInstance.attributes[rdnAttributeName][0])[
            0].attributes

        # Add new classes
        for n in newClasses:
            if n not in oldClasses:
                modList = [(ldap.MOD_ADD, "objectClass", n)]
                self.handler.update(dn, modList)

        # remove old classes
        for o in oldClasses:
            if o not in newClasses:
                modList = [(ldap.MOD_DELETE, "objectClass", o)]
                self.handler.update(dn, modList)
Exemple #21
0
    def _changeClass(self, objectTemplate):
        objHelper = LBEObjectInstanceHelper(objectTemplate)
        try:
            scope = objHelper.callScriptClassMethod("scope_search")
        except BaseException:
            scope = 0

        ob = self.backend.searchObjects(objectTemplate)
        for objectInstance in ob:
            try:
                oldClasses = self.target.getInstanceObjectClasses(objectTemplate, objectInstance, scope)
            except ldap.NO_SUCH_OBJECT:
                continue
            newClasses = objHelper.callScriptClassMethod("object_classes")

            if not sorted(oldClasses) == sorted(newClasses):
                print "    |-> The object classes have changed for '\033[35m" + objectInstance.displayName + "\033[0m'"
                try:
                    self.target.changeClass(objectTemplate, objectInstance, oldClasses, newClasses)
                except ldap.OBJECT_CLASS_VIOLATION as e:
                    print "    *\033[91mError to modify the object class " + str(newClasses) + ", skip it.\033[0m"
                    print "    *\033[91m" + e[0]["info"] + "\033[0m"
Exemple #22
0
 def _notExistObjectLBE(self):
     print '  Checking for Objects which do not exist into LBE but in LDAP Server:'
     for objectTemplate in LBEObjectTemplate.objects.all():
         print "  - \033[35m" + objectTemplate.name + '\033[0m...'
         objHelper = LBEObjectInstanceHelper(objectTemplate)
         try:
             scope = objHelper.callScriptClassMethod("search_scope")
         except BaseException:
             scope = 0
         objTarget = self.target.searchObjects(objectTemplate, scope)
         objBackend = self.backend.searchObjects(objectTemplate)
         number = 0
         for ot in objTarget:
             exist = False
             for ob in objBackend:
                 if ot.name == ob.name:
                     exist = True
                     break
             if not exist:
                 number += 1
                 print "    " + ot.name
         if number == 0:
             print '    \033[91m<None>\033[0m'
     print ""
     print '  Checking for Groups which do not exist into LBE but in LDAP Server:'
     number = 0
     for groupTemplate in LBEGroup.objects.all():
         grpHelper = GroupInstanceHelper(groupTemplate)
         try:
             scope = grpHelper.callScriptClassMethod("search_scope")
         except BaseException:
             scope = 0
         grpTarget = self.target.searchObjects(groupTemplate, scope, '(cn=' + groupTemplate.displayName + ')')
         grpBackend = self.backend.searchObjectsByPattern(groupTemplate, groupTemplate.displayName)
         if not grpBackend:
             print "   - \033[36m" + groupTemplate.displayName + "\033[0m does not exists."
             number += 1
     if number == 0:
         print '    \033[91m<None>\033[0m'
Exemple #23
0
def addObjectInstance(request, lbeObject_id=None):
    lbeObject = LBEObjectTemplate.objects.get(id=lbeObject_id)
    form = None
    helper = LBEObjectInstanceHelper(LBEObjectTemplate.objects.get(id=lbeObject_id))
    # Get multiValue attributes: ('+' button)
    multivalue = []
    # get all attributInstance of ObjectTemplate:
    attributeInstance = LBEAttributeInstance.objects.filter(lbeObjectTemplate=lbeObject).order_by("position")
    for attribute in attributeInstance:
        # check if multivalue is checked (True):
        if attribute.multivalue:
            multivalue.append(attribute.lbeAttribute.name)
    if request.method == "POST":
        form = helper.form(lbeObject, request.POST)
        if form.is_valid():
            try:
                helper.createFromDict(request)
            except BaseException:
                messages.add_message(request, messages.ERROR, "Error when creating object.")
                return render_to_response(
                    "directory/default/object/add.html",
                    {"form": form, "lbeObjectId": lbeObject_id, "multivalue": multivalue},
                    context_instance=RequestContext(request),
                )
            try:
                helper.save()
            except BackendObjectAlreadyExist as e:
                messages.add_message(request, messages.ERROR, "Object already exists")
                return render_to_response(
                    "directory/default/object/add.html",
                    {"form": form, "lbeObjectId": lbeObject_id, "multivalue": multivalue},
                    context_instance=RequestContext(request),
                )
            except ValueError as e:
                messages.add_message(request, messages.ERROR, e)
                return render_to_response(
                    "directory/default/object/add.html",
                    {"form": form, "lbeObjectId": lbeObject_id, "multivalue": multivalue},
                    context_instance=RequestContext(request),
                )
                # Redirect to list
            return redirect("/")
        return render_to_response(
            "directory/default/object/add.html",
            {"form": form, "lbeObjectId": lbeObject_id, "multivalue": multivalue},
            context_instance=RequestContext(request),
        )
    form = helper.form(lbeObject)
    return render_to_response(
        "directory/default/object/add.html",
        {"form": form, "lbeObjectId": lbeObject_id, "multivalue": multivalue},
        context_instance=RequestContext(request),
    )
Exemple #24
0
def manageObjectInstance(request, lbeObject_id, objectName, type):
    lbeObject = LBEObjectTemplate.objects.get(id=lbeObject_id)
    lbeAttribute = LBEAttributeInstance.objects.filter(lbeObjectTemplate=lbeObject)
    instanceHelper = LBEObjectInstanceHelper(lbeObject)
    # Get multiValue attributes: ('+' button)
    multivalue = []
    # get all attributInstance of ObjectTemplate:
    attributeInstance = LBEAttributeInstance.objects.filter(lbeObjectTemplate=lbeObject)
    for attribute in attributeInstance:
        # check if multivalue is checked (True):
        if attribute.multivalue:
            multivalue.append(attribute.lbeAttribute.name)
    if request.method == "POST":
        # Modify part:
        form = instanceHelper.form(objectName, request.POST)
        if form.is_valid():
            try:
                instanceHelper.updateFromDict(objectName, form.clean())
                instanceHelper.modify()
                messages.add_message(request, messages.SUCCESS, "Object saved")
            except ValueError as e:
                messages.add_message(request, messages.ERROR, e)
            except Exception as e:
                messages.add_message(request, messages.INFO, e)
    else:
        # Set values into form:
        form = instanceHelper.form(objectName)
    # Show part:
    return render_to_response(
        "directory/default/object/manage.html",
        {
            "form": form,
            "lbeObjectId": lbeObject_id,
            "lbeAttribute": lbeAttribute,
            "uid": objectName,
            "multivalue": multivalue,
            "status": instanceHelper.getStatus(objectName),
        },
        context_instance=RequestContext(request),
    )
Exemple #25
0
 def __init__(self, lbeObjectTemplate, *args, **kwargs):
     super(forms.Form, self).__init__(*args, **kwargs)
     for attributeInstance in lbeObjectTemplate.lbeattributeinstance_set.all().order_by('position'):
         # Display finals attributes
         if attributeInstance.attributeType == ATTRIBUTE_TYPE_FINAL:
             # Regex attribute value [for final attribute]
             regex = ''
             if not attributeInstance.lbeAttribute.regex == '':
                 regex = ', validators=[RegexValidator(r"' + attributeInstance.lbeAttribute.regex
                 if not attributeInstance.lbeAttribute.errorMessage == '':
                     regex += '","' + attributeInstance.lbeAttribute.errorMessage
                 regex += '","")]'
             exec 'self.fields[attributeInstance.lbeAttribute.name] = ' + attributeInstance.widget + '(' + attributeInstance.widgetArgs + regex + ')'
             try:
                 self.fields[attributeInstance.lbeAttribute.name].label = attributeInstance.lbeAttribute.displayName
                 self.fields[attributeInstance.lbeAttribute.name].required = bool(attributeInstance.mandatory)
             except BaseException:
                 pass
         # Manage & Show references attributes
         elif attributeInstance.attributeType == ATTRIBUTE_TYPE_REFERENCE:
             backend = BackendHelper()
             values = backend.searchObjects(attributeInstance.reference.objectTemplate)
             objectHelper = LBEObjectInstanceHelper(attributeInstance.reference.objectTemplate)
             # Get values into Dict
             listes = dict()
             for value in values:
                 # dict[ID] = Attribute value[0] using ID = frontend's UID
                 key = attributeInstance.reference.objectTemplate.instanceNameAttribute.name + "=" + value.name + "," + objectHelper.callScriptClassMethod(
                     'base_dn')
                 listes[key] = str(value.attributes[attributeInstance.reference.objectAttribute.name][0])
             # Create the Field (Dict to tuples):
             exec 'self.fields[attributeInstance.lbeAttribute.name] = forms.ChoiceField( ' + str(
                 listes.items()) + ' )'
             try:
                 self.fields[attributeInstance.lbeAttribute.name].label = attributeInstance.lbeAttribute.displayName
                 self.fields[attributeInstance.lbeAttribute.name].required = bool(attributeInstance.mandatory)
             except BaseException:
                 pass
Exemple #26
0
 def save(self):
     print 'Checking for Objects which do not exist into LBE Backend but in LDAP Server:'
     for objectTemplate in LBEObjectTemplate.objects.all():
         objectHelper = LBEObjectInstanceHelper(objectTemplate)
         try:
             scope = objectHelper.callScriptClassMethod("search_scope")
         except BaseException:
             scope = 0
         filter = '(&'
         for oc in objectHelper.callScriptClassMethod('object_classes'):
             filter += '(objectClass=' + oc + ')'
         filter += ')'
         print '\033[91m' + objectTemplate.name + '\033[0m: (\033[95m' + objectHelper.callScriptClassMethod(
             "base_dn") + '\033[0m) using \033[95m' + filter + '\033[0m'
         objTarget = self.target.searchObjects(objectTemplate, scope)
         objBackend = self.backend.searchObjects(objectTemplate)
         number = 0
         for ot in objTarget:
             exist = False
             for ob in objBackend:
                 if ot.name == ob.name:
                     exist = True
                     break
             if not exist:
                 number += 1
                 print '=> Adding \033[95m' + ot.name + '\033[0m object into LBE Backend... '
                 print " values: " + str(ot.attributes)
                 try:
                     self.backend.createObject(objectTemplate, ot, True)
                     print "\033[92mDone.\033[0m\n"
                 except BaseException as e:
                     print "\033[91mFail.\033[0m"
                     print "''''''''"
                     print e
                     print "''''''''"
         if number == 0:
             print '<None>'
         # Synced object:
         objectTemplate.synced_at = django.utils.timezone.now()
         objectTemplate.save()
     print '.........................'
     print 'Checking for Groups which do not exist into LBE Backend but in Target:'
     for groupTemplate in LBEGroup.objects.all():
         groupInstance = GroupInstanceHelper(groupTemplate)
         try:
             scope = groupInstance.callScriptClassMethod("search_scope")
         except BaseException:
             scope = 0
         grpTarget = self.target.searchObjects(groupTemplate, scope)
         grpBackend = self.backend.searchObjects(groupTemplate)
         for gt in grpTarget:
             exist = False
             for gb in grpBackend:
                 if gt.name == gb.name:
                     exist = True
                     break
             if not exist:
                 # import only existing group into LBE config
                 try:
                     LBEGroup.objects.get(
                         displayName__iexact=gt.displayName)
                 except BaseException:
                     continue
                 print '=> Adding \033[95m' + gt.name + '\033[0m group into LBE Backend... '
                 print " values: " + str(gt.attributes)
                 try:
                     if groupInstance.attributeName in gt.attributes:
                         gt.attributes[
                             groupInstance.attributeName] = self._getID(
                                 gt.attributes[groupInstance.attributeName])
                     groupHelper = GroupInstanceHelper(groupTemplate, gt)
                     groupHelper.createTemplate(True)
                     #print " >\033[91mThis group does not exists in LBE Configuration Group.\033[0m"
                     #print " >\033[91mIn order to see, manage it, please create it using some extra attribute:"
                     #print "  >\033[91m'Display Name': \033[95m" + gt.name + "\033[0m"
                     #print " >\033[91mInto the Script file:"
                     #print "  >'DN Attribute': \033[95m" + groupHelper.callScriptClassMethod("base_dn") + "\033[91m"
                     #print "  >'Attribute Name' & 'Object Classes': as you wish.\033[0m"
                     print "\033[92mDone.\033[0m\n"
                 except BaseException as e:
                     print "\033[91mFail.\033[0m\n"
                     print "''''''''"
                     print e
                     print "''''''''"
         # Synced group:
         groupTemplate.synced_at = django.utils.timezone.now()
         groupTemplate.save()
     print "End."
Exemple #27
0
    def searchObjects(self,
                      lbeObjectTemplate,
                      SCOPE,
                      filter=None,
                      start=0,
                      page=0):
        result_set = []
        # Call methods from object's script to get basedn and objectClass
        objectHelper = LBEObjectInstanceHelper(lbeObjectTemplate)
        if filter is None:
            filter = '(&'
            for oc in objectHelper.callScriptClassMethod('object_classes'):
                filter += '(objectClass=' + oc + ')'
            filter += ')'  #(modifyTimestamp>'+str(calendar.timegm(lbeObjectTemplate.synced_at.utctimetuple()))+'Z))'

        # Search in object's basedn
        if SCOPE != 0 and SCOPE != 1 and SCOPE != 2:
            SCOPE = 0  # BASE

        for dn, entry in self.handler.search(
                objectHelper.callScriptClassMethod('base_dn'), filter, SCOPE,
            ['*', '+']):
            # Create an empty instance
            objectInstance = LBEObjectInstance(
                lbeObjectTemplate,
                name=entry[lbeObjectTemplate.instanceNameAttribute.name][0])
            # Add attributes defined in the template. Other ones are ignored
            try:  # Object
                for attributeInstance in lbeObjectTemplate.lbeattributeinstance_set.all(
                ):
                    try:
                        objectInstance.attributes[
                            attributeInstance.lbeAttribute.name] = entry[
                                attributeInstance.lbeAttribute.name]
                    except KeyError, e:
                        logger.warning('The attribute ' +
                                       attributeInstance.lbeAttribute.name +
                                       ' does not exist in LDAP object: ' + dn)
                    # Set displayName and few others attributes
                objectInstance.displayName = entry[
                    lbeObjectTemplate.instanceDisplayNameAttribute.name][0]
                objectInstance.status = OBJECT_STATE_IMPORTED
                objectInstance.created_at = datetime.datetime.strptime(
                    entry['createTimestamp'][0], '%Y%m%d%H%M%SZ')
                try:
                    objectInstance.updated_at = datetime.datetime.strptime(
                        entry['modifyTimestamp'][0], '%Y%m%d%H%M%SZ')
                except KeyError:
                    objectInstance.updated_at = datetime.datetime.strptime(
                        entry['createTimestamp'][0], '%Y%m%d%H%M%SZ')
                result_set.append(objectInstance)
            except AttributeError:  # Group:
                groupInstance = GroupInstanceHelper(lbeObjectTemplate)
                objectInstance.displayName = entry['cn'][0]
                objectInstance.attributes[u'cn'] = entry['cn']
                if groupInstance.attributeName in entry:
                    objectInstance.attributes[
                        groupInstance.attributeName] = entry[
                            groupInstance.attributeName]
                else:
                    objectInstance.attributes[groupInstance.attributeName] = []
                objectInstance.status = OBJECT_STATE_IMPORTED
                objectInstance.created_at = datetime.datetime.strptime(
                    entry['createTimestamp'][0], '%Y%m%d%H%M%SZ')
                try:
                    objectInstance.updated_at = datetime.datetime.strptime(
                        entry['modifyTimestamp'][0], '%Y%m%d%H%M%SZ')
                except KeyError:
                    objectInstance.updated_at = datetime.datetime.strptime(
                        entry['createTimestamp'][0], '%Y%m%d%H%M%SZ')
                result_set.append(objectInstance)
Exemple #28
0
 def start(self):
     print "   Upgrade the Target server with the Backend server..."
     for objectTemplate in LBEObjectTemplate.objects.all():
         # need to check if we need to change (before making reconciliation) the RDN attribute
         self._changeRDN(objectTemplate)
         # And the objects class
         self._changeClass(objectTemplate)
         # We're looking for all objects with state = OBJECT_STATE_AWAITING_SYNC
         for objectInstance in self.backend.searchObjectsToUpdate(objectTemplate):
             # First of all, applies all changes stored in backend [ such Virtual attributes ]
             # & create the parent DN if not exist:
             obj = LBEObjectInstanceHelper(objectTemplate, objectInstance)
             try:
                 scope = obj.callScriptClassMethod("search_scope")
             except BaseException:
                 scope = 0
             self._createParent(objectTemplate, obj)
             # obj.compute(objectInstance)
             # then, upgrade:
             if objectInstance.changes["type"] == OBJECT_CHANGE_CREATE_OBJECT:
                 try:
                     print "    |-> Object '\033[35m" + objectInstance.displayName + "\033[0m' is \033[34mcreating\033[0m..."
                     self._createObject(objectTemplate, objectInstance)
                 # TODO: We should have a target exception rather ldap
                 except ldap.ALREADY_EXISTS:
                     print "    |-> Object '\033[35m" + objectInstance.displayName + "'\033[0m already exists"
                     changes = {}
                     changes["status"] = OBJECT_STATE_SYNCED
                     changes["changes"] = {}
                     changes["changes"]["set"] = {}
                     changes["changes"]["type"] = -1
                     changes["synced_at"] = django.utils.timezone.now()
                     self.backend.updateObject(objectTemplate, objectInstance, changes)
                     pass
             elif objectInstance.changes["type"] == OBJECT_CHANGE_DELETE_OBJECT:
                 try:
                     print "    |-> Object '\033[35m" + objectInstance.displayName + "' is \033[33mdeleting\033[0m..."
                     self._deleteObject(objectTemplate, objectInstance)
                 except BaseException as e:
                     print "    |-> Object '\033[35m" + objectInstance.displayName + "'\033[0m does not exist."
                     changes = {}
                     changes["status"] = OBJECT_STATE_DELETED
                     changes["changes"] = {}
                     changes["changes"]["set"] = {}
                     changes["changes"]["type"] = -1
                     changes["synced_at"] = django.utils.timezone.now()
                     self.backend.updateObject(objectTemplate, objectInstance, changes)
                     pass
             elif objectInstance.changes["type"] == OBJECT_CHANGE_UPDATE_OBJECT:
                 try:
                     print "    |-> Object '\033[35m" + objectInstance.displayName + "'\033[0m is \033[36mupdating\033[0m..."
                     # Group
                     for group in LBEGroup.objects.all():
                         if group.objectTemplate.id == objectTemplate.id:
                             GroupInstanceHelper(group).updateMember(obj.getObject(obj.instance.name))
                     self._modifyObject(objectTemplate, objectInstance, scope)
                 except BaseException as e:
                     print e
                     print "    |-> Object '\033[35m" + objectInstance.displayName + "' does not exist, being \033[34mcreated\033[0m..."
                     # Create object if not exists:
                     # Firstly, compute attributes values:
                     # Then, create it:
                     try:
                         self._createObject(objectTemplate, objectInstance)
                     except Exception as e:
                         print e
                         pass
                     pass
                     # Synced object:
                     objectTemplate.synced_at = django.utils.timezone.now()
                     objectTemplate.save()
     print ""
     print "   Upgrade Groups Objects:"
     for groupTemplate in LBEGroup.objects.all():
         for groupInstance in self.backend.searchObjectsToUpdate(groupTemplate):
             grp = GroupInstanceHelper(groupTemplate, groupInstance)
             try:
                 scope = grp.callScriptClassMethod("search_scope")
             except BaseException:
                 scope = 0
             self._createParent(groupTemplate, grp)
             if groupInstance.changes["type"] == OBJECT_CHANGE_CREATE_OBJECT:
                 print "    |-> Group '\033[35m" + groupInstance.displayName + "\033[0m' is \033[34mcreating\033[0m..."
                 try:
                     groupInstance.changes["set"][grp.attributeName] = self._getRDN(
                         groupTemplate.objectTemplate, groupInstance.changes["set"][grp.attributeName]
                     )
                     self._createObject(groupTemplate, groupInstance)
                     ###############################################
                     if not groupInstance.changes["set"] == {}:
                         groupInstance.changes["set"][grp.attributeName] = self._getID(
                             groupInstance.changes["set"][grp.attributeName]
                         )
                         groupInstance.attributes["cn"] = groupInstance.changes["set"]["cn"]
                         self.backend.updateObject(
                             groupTemplate,
                             groupInstance,
                             {"changes": {"set": {"cn": [groupInstance.displayName]}, "type": -1}},
                         )
                     ###############################################
                 except ldap.ALREADY_EXISTS:
                     print "    |-> Group '\033[35m" + groupInstance.displayName + "'\033[0m already exists"
             elif groupInstance.changes["type"] == OBJECT_CHANGE_UPDATE_OBJECT:
                 try:
                     print "    |-> Group '\033[35m" + groupInstance.displayName + "'\033[0m is \033[36mupdating\033[0m..."
                     groupInstance.changes["set"][grp.attributeName] = self._getRDN(
                         groupTemplate.objectTemplate, groupInstance.changes["set"][grp.attributeName]
                     )
                     self._modifyObject(groupTemplate, groupInstance, scope)
                     ###############################################
                     groupInstance.changes["set"][grp.attributeName] = self._getID(
                         groupInstance.changes["set"][grp.attributeName]
                     )
                     groupInstance.attributes["cn"] = groupInstance.changes["set"]["cn"]
                     self.backend.updateObject(
                         groupTemplate,
                         groupInstance,
                         {"changes": {"set": {"cn": [groupInstance.displayName]}, "type": -1}},
                     )
                     ###############################################
                 except BaseException as e:
                     print e
                     print "    |-> Group '\033[35m" + groupInstance.displayName + "' does not exist, being \033[34mcreated\033[0m..."
                     groupInstance.changes["set"][grp.attributeName] = self._getRDN(
                         groupTemplate.objectTemplate, groupInstance.changes["set"][grp.attributeName]
                     )
                     self._createObject(groupTemplate, groupInstance)
                     ###############################################
                     groupInstance.changes["set"][grp.attributeName] = self._getID(
                         groupInstance.changes["set"][grp.attributeName]
                     )
                     groupInstance.attributes["cn"] = groupInstance.changes["set"]["cn"]
                     self.backend.updateObject(
                         groupTemplate,
                         groupInstance,
                         {"changes": {"set": {"cn": [groupInstance.displayName]}, "type": -1}},
                     )
                     ###############################################
             elif groupInstance.changes["type"] == OBJECT_CHANGE_DELETE_OBJECT:
                 print "    |-> Group '\033[35m" + groupInstance.displayName + "' is \033[33mdeleting\033[0m..."
                 self._deleteObject(groupTemplate, groupInstance)
     print "   End."
Exemple #29
0
 def save(self):
     print 'Checking for Objects which do not exist into LBE Backend but in LDAP Server:'
     for objectTemplate in LBEObjectTemplate.objects.all():
         objectHelper = LBEObjectInstanceHelper(objectTemplate)
         try:
             scope = objectHelper.callScriptClassMethod("search_scope")
         except BaseException:
             scope = 0
         filter = '(&'
         for oc in objectHelper.callScriptClassMethod('object_classes'):
             filter += '(objectClass=' + oc + ')'
         filter += ')'
         print '\033[91m' + objectTemplate.name + '\033[0m: (\033[95m' + objectHelper.callScriptClassMethod("base_dn") + '\033[0m) using \033[95m' + filter + '\033[0m'
         objTarget = self.target.searchObjects(objectTemplate, scope)
         objBackend = self.backend.searchObjects(objectTemplate)
         number = 0
         for ot in objTarget:
             exist = False
             for ob in objBackend:
                 if ot.name == ob.name:
                     exist = True
                     break
             if not exist:
                 number += 1
                 print '=> Adding \033[95m' + ot.name + '\033[0m object into LBE Backend... '
                 print " values: " + str(ot.attributes)
                 try:
                     self.backend.createObject(objectTemplate, ot, True)
                     print "\033[92mDone.\033[0m\n"
                 except BaseException as e:
                     print "\033[91mFail.\033[0m"
                     print "''''''''"
                     print e
                     print "''''''''"
         if number == 0:
             print '<None>'
         # Synced object:
         objectTemplate.synced_at = django.utils.timezone.now()
         objectTemplate.save()
     print '.........................'
     print 'Checking for Groups which do not exist into LBE Backend but in Target:'
     for groupTemplate in LBEGroup.objects.all():
         groupInstance = GroupInstanceHelper(groupTemplate)
         try:
             scope = groupInstance.callScriptClassMethod("search_scope")
         except BaseException:
             scope = 0
         grpTarget = self.target.searchObjects(groupTemplate, scope)
         grpBackend = self.backend.searchObjects(groupTemplate)
         for gt in grpTarget:
             exist = False
             for gb in grpBackend:
                 if gt.name == gb.name:
                     exist = True
                     break
             if not exist:
                 # import only existing group into LBE config
                 try:
                     LBEGroup.objects.get(displayName__iexact=gt.displayName)
                 except BaseException:
                     continue
                 print '=> Adding \033[95m' + gt.name + '\033[0m group into LBE Backend... '
                 print " values: " + str(gt.attributes)
                 try:
                     if groupInstance.attributeName in gt.attributes:
                         gt.attributes[groupInstance.attributeName] = self._getID(gt.attributes[groupInstance.attributeName])
                     groupHelper = GroupInstanceHelper(groupTemplate, gt)
                     groupHelper.createTemplate(True)
                         #print " >\033[91mThis group does not exists in LBE Configuration Group.\033[0m"
                         #print " >\033[91mIn order to see, manage it, please create it using some extra attribute:"
                         #print "  >\033[91m'Display Name': \033[95m" + gt.name + "\033[0m"
                         #print " >\033[91mInto the Script file:"
                         #print "  >'DN Attribute': \033[95m" + groupHelper.callScriptClassMethod("base_dn") + "\033[91m"
                         #print "  >'Attribute Name' & 'Object Classes': as you wish.\033[0m"
                     print "\033[92mDone.\033[0m\n"
                 except BaseException as e:
                     print "\033[91mFail.\033[0m\n"
                     print "''''''''"
                     print e
                     print "''''''''"
         # Synced group:
         groupTemplate.synced_at = django.utils.timezone.now()
         groupTemplate.save()
     print "End."