Exemple #1
0
def viewUserObjectAJAX(request, group_id, name):
    if request.is_ajax():
        group = LBEGroup.objects.get(id=group_id)
        backend = BackendHelper()
        objects = backend.searchObjectsByPattern(group.objectTemplate, name)
        list = []
        for o in objects:
            list.append(o.name)
        return HttpResponse(json.dumps(list), mimetype="application/json")
Exemple #2
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 #3
0
def searchAJAX(request, lbeObject_id, search):
    if len(search) == 0:
        return HttpResponse('/')
    backend = BackendHelper()
    objects = backend.searchObjectsByPattern(
        LBEObjectTemplate.objects.get(id=lbeObject_id), search)
    return render_to_response('ajax/directory/search.html', {
        'lbeObjectId': lbeObject_id,
        'objects': objects
    },
                              context_instance=RequestContext(request))
Exemple #4
0
 def _executeOU(self, userID):
     # backend db:
     backend = BackendHelper()
     values = self.word[2].split(',')
     for objectName in values:
         obj = LBEObjectTemplate.objects.filter(
             Q(name=objectName) | Q(displayName=objectName))[0]
         if backend.getUserUIDForObject(obj, userID):
             return True
     # No value:
     return False
Exemple #5
0
def listObjects(request, lbeObject_id=1, page=1):
    # init object:
    if lbeObject_id is None:
        lbeObject_id = 1
    if settings.PAGINATION is None:
        lengthMax = 25
    else:
        lengthMax = settings.PAGINATION
        # init pagination:
    if page is None:
        page = 1
    else:
        page = int(page)
    if page == 1:
        index = 0
    else:
        index = int(page) + lengthMax - 2
    backend = BackendHelper()
    objects = backend.searchObjects(
        LBEObjectTemplate.objects.get(id=lbeObject_id), index, lengthMax)
    lbeObject = LBEObjectTemplate.objects.get(id=lbeObject_id)
    lbeObjects = LBEObjectTemplate.objects.all()
    # Pagination:
    size = int(
        math.ceil(
            backend.lengthObjects(
                LBEObjectTemplate.objects.get(id=lbeObject_id)) /
            float(lengthMax)))
    if page < 3:
        min = 1
    else:
        min = page - 2
    if size - page > 2:
        max = page + 2
    else:
        max = size
    tabSize = []
    tabSize.append(min)
    for i in range(min, max):
        tabSize.append(i + 1)
    return render_to_response('directory/default/object/listObjects.html', {
        'objects': objects,
        'lbeObjectId': lbeObject.id,
        'objectTemplateName': lbeObject.displayName,
        'lbeObjects': lbeObjects,
        'length': tabSize,
        'page': int(page),
        'minCPage': min,
        'maxCPage': max,
        'maxPage': size
    },
                              context_instance=RequestContext(request))
Exemple #6
0
 def handle(self, *args, **options):
     try:
         backend = BackendHelper()
         target = TargetHelper()
     except Exception as e:
         print >> sys.stderr, e
         sys.exit(1)
     for lbeObjectTemplate in LBEObjectTemplate.objects.all():
         now = datetime.datetime.now(utc)
         # the searchNewObjectcs methods search for backend object where createTimestamp > objectTemplate.imported_at
         for lbeObject in target.searchNewObjects(lbeObjectTemplate):
             #
             # TODO: take care about virtual/reference attributes
             # Example: an object where uid is computed as 'bbonfils', but backend value is 'asyd'
             lbeObject.synced_at = now
             backend.createObject(lbeObjectTemplate, lbeObject)
         lbeObjectTemplate.imported_at = now
         lbeObjectTemplate.save()
Exemple #7
0
 def clean(self):
     if not self.cleaned_data == {}: # no value 
         tab = []
         backend = BackendHelper()
         values = backend.searchObjects(self.template)
         list = []
         for value in values:
             if value.changes['set'] == {}:
                 list.append(value.attributes[self.template.instanceNameAttribute.name][0])
             else:
                 list.append(value.changes['set'][self.template.instanceNameAttribute.name][0])
         for value in self.cleaned_data[self.groupHelper.attributeName].split('\0'):
             if not value == "":
                 if not value in list:
                     raise forms.ValidationError("'" + value + "' is not into " + self.template.displayName)
                 tab.append(value)
         return tab
     return self.cleaned_data
Exemple #8
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 #9
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 #10
0
def index(request):
    objects = LBEObjectTemplate.objects.all()
    groups = LBEGroup.objects.all()
    backend = BackendHelper()
    # Objects
    statObjects = []
    for object in objects:
        lbeObjects = backend.searchObjects(object)
        ok = 0
        approval = 0
        needSync = 0
        delete = 0
        reconciliation = False
        for lbeobject in lbeObjects:
            if lbeobject.status == 0:
                ok += 1
            elif lbeobject.status == 1:
                needSync += 1
            elif lbeobject.status == 2:
                approval += 1
            elif lbeobject.status == 3:
                reconciliation = True
            elif lbeobject.status == 4:
                delete += 1
        statObjects.append({
            'name': object.displayName,
            'total': len(lbeObjects),
            'ok': ok,
            'approval': approval,
            'sync': needSync,
            'reconciliation': reconciliation,
            'delete': delete
        })
    # Groups
    statGroups = []
    try:
        for group in groups:
            groupHelper = GroupInstanceHelper(group)
            groupHelper.get()
            if groupHelper.attributeName in groupHelper.instance.changes['set'] and not \
            groupHelper.instance.changes['set'][groupHelper.attributeName] == []:
                total = len(groupHelper.instance.changes['set'][
                    groupHelper.attributeName])
            else:
                total = len(
                    groupHelper.instance.attributes[groupHelper.attributeName])
        status = groupHelper.instance.status
    except BaseException as e:
        total = 0
        status = -1
    statGroups.append({
        'name': group.displayName,
        'total': total,
        'object': groupHelper.template.objectTemplate.displayName,
        'status': status
    })
    return render_to_response('directory/default/index.html', {
        'objects': statObjects,
        'groups': statGroups
    },
                              context_instance=RequestContext(request))
Exemple #11
0
 def __init__(self):
     self.backend = BackendHelper()
     self.target = TargetHelper()
     self.start_date = django.utils.timezone.now()
Exemple #12
0
 def __init__(self):
     self.backend = BackendHelper()
     self.target = TargetHelper()
Exemple #13
0
 def __init__(self):
     self.backend = BackendHelper()
Exemple #14
0
 def _executePerson(self, userID):
     # backend db:
     backend = BackendHelper()
     obj = backend.getUserUIDForObject(self.object, userID)
     # check if characters:
     if self.word[3] != '':
         # split ',' values:
         val = self.word[3].split(',')
         try:
             for value in obj['attributes'][self.attribute]:
                 for attrValue in val:
                     if self.operator == '=':
                         if attrValue == value:
                             return True
                     elif self.operator == '!=':
                         if attrValue == value:
                             return False
         except BaseException as e:
             # e
             # attribute does not exist for user:
             pass
         return self.operator == '!='
     # only a number:
     elif self.number:
         try:
             if self.operator == '=':
                 number = self.number.split(',')
                 for nb in number:
                     if int(nb) == int(
                             obj['attributes'][self.attribute][0]):
                         return True
                 return False
             elif self.operator == '!=':
                 number = self.number.split(',')
                 for nb in number:
                     if int(nb) == int(
                             obj['attributes'][self.attribute][0]):
                         return False
                 return True
             elif self.operator == '>':
                 return int(
                     obj['attributes'][self.attribute][0]) > self.number
             elif self.operator == '<':
                 return int(
                     obj['attributes'][self.attribute][0]) < self.number
             elif self.operator == '<=':
                 return int(
                     obj['attributes'][self.attribute][0]) <= self.number
             elif self.operator == '>=':
                 return int(
                     obj['attributes'][self.attribute][0]) >= self.number
         except:
             # wrong key
             self.traceback = "The key " + self.attribute + "does not exist to the Backend Server for " + userID + "."
             return False
     # number range:
     elif self.numberTo and self.numberFrom:
         try:
             if self.operator == '=':
                 return self.numberTo <= int(obj['attributes'][self.attribute][0]) and \
                        self.numberFrom >= int(obj['attributes'][self.attribute][0])
             elif self.operator == '!=':
                 return self.numberTo <= int(obj['attributes'][self.attribute][0]) and \
                        self.numberFrom >= int(obj['attributes'][self.attribute][0])
         except:
             # wrong key
             self.traceback = "The key " + self.attribute + "does not exist to the Backend Server for " + userID + "."
             return False
     # not necessary:
     return False
Exemple #15
0
def modifyObject(request, obj_id=None, instance_id=None):
    objectForm = None
    lbeObjectTemplate = LBEObjectTemplate.objects.get(id=obj_id)
    if request.method == 'POST':
        # we can't modify the Synced_at value
        POST = request.POST.copy()
        POST['synced_at'] = lbeObjectTemplate.synced_at
        # POST modification
        objectForm = LBEObjectTemplateForm(POST, instance=lbeObjectTemplate)
        oldNAttribute = lbeObjectTemplate.instanceNameAttribute.name
        oldDNAttribute = lbeObjectTemplate.instanceDisplayNameAttribute.id
        if objectForm.is_valid():
            # change the _id value if changed:
            if not oldNAttribute == request.POST['instanceNameAttribute']:
                changeID = True
            else:
                changeID = False
                # change the displayName value if changed:
            if not oldDNAttribute == int(
                    request.POST['instanceDisplayNameAttribute']):
                DN = True
            else:
                DN = False
            if changeID or DN:
                if changeID is True:
                    objectForm.instance.instanceNameBeforeAttribute = LBEAttribute.objects.get(
                        name__iexact=oldNAttribute)
                    objectForm.instance.needReconciliationRDN = True
                backend = BackendHelper()
                ob = backend.searchObjects(lbeObjectTemplate)
                try:
                    for o in ob:
                        if changeID:
                            # change the _id value
                            backend.update_id(
                                lbeObjectTemplate, o, o.attributes[
                                    request.POST['instanceNameAttribute']][0])
                            # the RDN Attribute from Target Server is replace into the Reconciliation
                        if DN:
                            attribute = LBEAttribute.objects.get(
                                id=request.POST['instanceDisplayNameAttribute']
                            )
                            backend.modifyDisplayName(
                                lbeObjectTemplate, o.name,
                                o.attributes[attribute.name][0])
                    # Groups
                    if changeID:
                        groups = LBEGroup.objects.filter(
                            objectTemplate=lbeObjectTemplate)
                        for group in groups:
                            InstanceHelper = GroupInstanceHelper(group)
                            InstanceHelper.changeIDObjects()
                except KeyError:
                    messages.add_message(
                        request, messages.ERROR,
                        'Error while saving object, "' +
                        request.POST['instanceNameAttribute'] +
                        '" does not exist for the Object.')
                    return redirect('/config/object/modify/' + obj_id)
            objectForm.save()
            messages.add_message(request, messages.SUCCESS, 'Object saved')
            return redirect('/config/object/modify/' + obj_id)
        else:
            messages.add_message(request, messages.ERROR,
                                 'Error while saving object.')
    else:
        if obj_id is None:
            messages.add_message(request, messages.INFO,
                                 'Object id is missing.')
            return render_to_response(
                'config/object/list.html',
                {'objects': LBEObjectTemplate.objects.all()})
        else:
            objectForm = LBEObjectTemplateForm(instance=lbeObjectTemplate)
    attForm = LBEAttributeInstanceForm()
    instances = LBEAttributeInstance.objects.filter(
        lbeObjectTemplate=lbeObjectTemplate).order_by('position')
    # which attribute have ajax request:
    ajaxAttribute = 'instanceNameAttribute'
    defaultValue = lbeObjectTemplate.instanceNameAttribute.name
    # Ajax function to call (js):
    ajaxFunction = 'selectFrom(\'' + reverse(
        'config.views.showAttributeAJAX'
    )[:-1] + '\',\'' + ajaxAttribute + '\');'
    info_missing_policy = "Variable used for setting if the Object is deleted into the Target or <br> if we need to add "
    info_missing_policy += " to the Backend"
    info_different_policy = "Variable enables to set which Server, we need to upgrade values:<br> If the value is TARGET"
    info_different_policy += ", then the Backend object will replace the Target object <br>else, the opposite."
    if lbeObjectTemplate.instanceNameBeforeAttribute is not None:
        attributeBefore = lbeObjectTemplate.instanceNameBeforeAttribute.name
    else:
        attributeBefore = lbeObjectTemplate.instanceNameAttribute.name
    return render_to_response('config/object/modify.html', {
        'attributeInstances': instances,
        'lbeObject': lbeObjectTemplate,
        'objectForm': objectForm,
        'attributeForm': attForm,
        'ajaxAttribute': ajaxAttribute,
        'ajaxFunction': ajaxFunction,
        'defaultValue': defaultValue,
        'info_missing_policy': info_missing_policy,
        'info_different_policy': info_different_policy,
        'attributeInstanceBefore': attributeBefore
    },
                              context_instance=RequestContext(request))