Example #1
0
    def _set_password(self, name, password, by_cn=True):
        unicode_pass = '******' + password + '\"'
        password_value = unicode_pass.encode('utf-16-le')

        ldap_client = self._bind()

        if by_cn:
            dn = self._str('CN=%(cn)s,%(user_dn)s' % {
                        'cn': name,
                        'user_dn': self.userdn
                       })
        else:
            dn = self._str(name)

        attrs = {}

        attrs['unicodePwd'] = self._str(password_value)

        ldif = modlist.modifyModlist({'unicodePwd': 'tmp'}, attrs)
        ldap_client.modify_s(dn, ldif)

        del(attrs['unicodePwd'])
        attrs['UserAccountControl'] = str(NORMAL_ACCOUNT)
        ldif = modlist.modifyModlist({'UserAccountControl': 'tmp'}, attrs)
        ldap_client.modify_s(dn, ldif)
Example #2
0
    def fllow_kehuclass_change(self):
        _logger.info(u'当客户班级改变时,重写Ldap班级字段')
        _logger.info(u'当前客户关联班级字段是%s' % self.kehu_id.name)
        if self.cuid == '/':
            return None
        con = self._get_ldap_connection()[0]
        try:
            mail = self.res_email or self.email
            dn = "mail=%s,%s" % (mail, self._get_ldap_basedn()[0])
            #如果更换班级,修改Ldap对应的班级字段,否则设置为None
            new = {}
            if self.kehu_id.class_number:
                new['roomNumber'] = self.kehu_id.class_number.encode('utf-8')
                old = {'roomNumber': ' '}

                ldif = modlist.modifyModlist(old, new)
                con.modify_s(dn, ldif)
            else:
                new['roomNumber'] = 'None'.encode('utf-8')
                old = {'roomNumber': ' '}

                ldif = modlist.modifyModlist(old, new)
                con.modify_s(dn, ldif)

        except ldap.LDAPError, e:
            _logger.error(u'注意%s' % e.message)
            raise UserError(u'您提前为此客户归属了班级,请悉知,并继续您的下一步')
            return False
Example #3
0
    def _set_password(self, name, password, by_cn=True):
        unicode_pass = '******' + password + '\"'
        password_value = unicode_pass.encode('utf-16-le')

        ldap_client = self._bind()

        if by_cn:
            dn = self._str('CN=%(cn)s,%(user_dn)s' % {
                'cn': name,
                'user_dn': self.userdn
            })
        else:
            dn = self._str(name)

        attrs = {}

        attrs['unicodePwd'] = self._str(password_value)

        ldif = modlist.modifyModlist({'unicodePwd': 'tmp'}, attrs)
        ldap_client.modify_s(dn, ldif)

        del (attrs['unicodePwd'])
        attrs['UserAccountControl'] = str(NORMAL_ACCOUNT)
        ldif = modlist.modifyModlist({'UserAccountControl': 'tmp'}, attrs)
        ldap_client.modify_s(dn, ldif)
Example #4
0
    def _set_password(self, name, password, by_cn=True):
        unicode_pass = '******' + password + '\"'
        password_value = unicode_pass.encode('utf-16-le')

        ldap_client = self._bind()

        if by_cn:
            dn = self._byte_p2('CN=%(cn)s,%(user_dn)s' % {
                'cn': name,
                'user_dn': self.userdn
            })
        else:
            dn = self._byte_p2(name)

        attrs = {}

        attrs['unicodePwd'] = self._modlist(self._byte_p2(password_value))

        ldif = modlist.modifyModlist({'unicodePwd': 'tmp'}, attrs)
        ldap_client.modify_s(dn, ldif)

        del (attrs['unicodePwd'])
        #attrs['UserAccountControl'] = self._modlist(
        #    self._tobyte(NORMAL_ACCOUNT)
        #)
        attrs['pwdLastSet'] = self._modlist(self._tobyte(0))
        attrs['UserAccountControl'] = self._modlist(
            self._tobyte(PASSWORD_EXPIRED))
        ldif = modlist.modifyModlist({'UserAccountControl': 'tmp'}, attrs)
        ldap_client.modify_s(dn, ldif)
Example #5
0
	def modify(self, dn, oldattrs, newattrs):
		if not dn or newattrs is None:
			return
		modstruct = modlist.modifyModlist(oldattrs, newattrs)
		Info("Ldap style struct: %s" % modstruct)
		if modstruct:
			self.l.modify(dn, modlist.modifyModlist(oldattrs, newattrs))
Example #6
0
def modUser(user):
    check = False
    try:
        # Open a connection
        con = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)

        # Bind/authenticate with a user with apropriate rights to add objects
        con.simple_bind_s(settings.AUTH_LDAP_BIND_DN,str(settings.AUTH_LDAP_BIND_PASSWORD))
        # The dn of our new entry/object
        dn="uid="+user.getUid()+","+str(settings.AUTH_LDAP_BASE_USER_DN)

        userOld=getUser(user.getUid())
        # A dict to help build the "body" of the object
        # TODO: clean this
        attrs = {}
        attrs['cn'] = [str(user.getFirstname()).encode('utf-8')]
        attrs['mail'] = [str(user.getMail()).encode('utf-8')]
        attrs['sn'] = [str(user.getLastname()).encode('utf-8')]
        attrs['userpassword'] = [str(lsm.encrypt(user.getPassword())).encode('utf-8')]

        oldValue = {'cn': [str(userOld.getFirstname()).encode('utf-8')]}
        newValue = {'cn': [str(user.getFirstname()).encode('utf-8')]}
        # Convert our dict to nice syntax for the add-function using modlist-module
        ldif = modlist.modifyModlist(oldValue,newValue)
        con.modify_s(dn,ldif)

        oldValue = {'mail': [str(userOld.getMail()).encode('utf-8')]}
        newValue = {'mail': [str(user.getMail()).encode('utf-8')]}
        # Convert our dict to nice syntax for the add-function using modlist-module
        ldif = modlist.modifyModlist(oldValue,newValue)
        con.modify_s(dn,ldif)

        oldValue = {'sn': [str(userOld.getLastname()).encode('utf-8')]}
        newValue = {'sn': [str(user.getLastname()).encode('utf-8')]}
        # Convert our dict to nice syntax for the add-function using modlist-module
        ldif = modlist.modifyModlist(oldValue,newValue)
        con.modify_s(dn,ldif)

        if user.getPassword():
            oldValue = {'userpassword': [str(userOld.getPassword()).encode('utf-8')]}
            newValue = {'userpassword': [str(lsm.encrypt(user.getPassword())).encode('utf-8')]}
            # Convert our dict to nice syntax for the add-function using modlist-module
            ldif = modlist.modifyModlist(oldValue,newValue)
            con.modify_s(dn,ldif)

        # Do the actual synchronous add-operation to the ldapserver
        #print('add_s')
        #print(type(dn))
        #print(type(ldif))

        # Its nice to the server to disconnect and free resources when done
        con.unbind_s()
        check = True
    except ldap.LDAPError:
    #except Exception:
        traceback.print_exc(file=sys.stdout)
    return check
Example #7
0
    def update_person(self, unique_id, form):
        """
        Updates a person's LDAP directory record
        based on phonebook.forms.ProfileForm.

        Method always uses master.
        """
        conn = self._ensure_conn(WRITE)

        dn = Person.dn(unique_id)

        person = self.get_by_unique_id(unique_id)
        form['unique_id'] = person.unique_id

        if 'email' not in form:
            form['email'] = person.username

        newp = Person.form_to_profile_attrs(form)
        modlist = modifyModlist(person.ldap_attrs(),
                                newp,
                                ignore_oldexistent=1)
        if modlist:
            conn.modify_s(dn, modlist)

        services = self.profile_service_ids(unique_id)
        oldservs = dict((k, v.ldap_attrs()) for k, v in services.iteritems())
        newservs = SystemId.form_to_service_ids_attrs(form)
        for service_uri in KNOWN_SERVICE_URIS:
            newserv = newservs[service_uri]

            if service_uri in oldservs:
                oldserv = oldservs[service_uri]
                newserv['uniqueIdentifier'][0] = oldserv['uniqueIdentifier'][0]
                sys_id_dn = SystemId.dn(unique_id,
                                        oldserv['uniqueIdentifier'][0])

                if newserv['mozilliansServiceID'][0]:
                    modlist = modifyModlist(oldserv, newserv)
                    if modlist:
                        conn.modify_s(sys_id_dn, modlist)
                else:
                    conn.delete_s(sys_id_dn)
            else:
                sys_id_dn = SystemId.dn(unique_id,
                                        newserv['uniqueIdentifier'][0])
                if newserv['mozilliansServiceID'][0]:
                    modlist = addModlist(newserv)
                    if modlist:
                        conn.add_s(sys_id_dn, modlist)
        return True
Example #8
0
    def update_person(self, unique_id, form):
        """
        Updates a person's LDAP directory record
        based on phonebook.forms.ProfileForm.

        Method always uses master.
        """
        conn = self._ensure_conn(WRITE)

        dn = Person.dn(unique_id)

        person = self.get_by_unique_id(unique_id)
        form['unique_id'] = person.unique_id

        if 'email' not in form:
            form['email'] = person.username

        newp = Person.form_to_profile_attrs(form)
        modlist = modifyModlist(person.ldap_attrs(), newp,
                                ignore_oldexistent=1)
        if modlist:
            conn.modify_s(dn, modlist)

        services = self.profile_service_ids(unique_id)
        oldservs = dict((k, v.ldap_attrs()) for k, v in services.iteritems())
        newservs = SystemId.form_to_service_ids_attrs(form)
        for service_uri in KNOWN_SERVICE_URIS:
            newserv = newservs[service_uri]

            if service_uri in oldservs:
                oldserv = oldservs[service_uri]
                newserv['uniqueIdentifier'][0] = oldserv['uniqueIdentifier'][0]
                sys_id_dn = SystemId.dn(unique_id,
                                        oldserv['uniqueIdentifier'][0])

                if newserv['mozilliansServiceID'][0]:
                    modlist = modifyModlist(oldserv, newserv)
                    if modlist:
                        conn.modify_s(sys_id_dn, modlist)
                else:
                    conn.delete_s(sys_id_dn)
            else:
                sys_id_dn = SystemId.dn(unique_id,
                                        newserv['uniqueIdentifier'][0])
                if newserv['mozilliansServiceID'][0]:
                    modlist = addModlist(newserv)
                    if modlist:
                        conn.add_s(sys_id_dn, modlist)
        return True
Example #9
0
	def check_employment_state(self):
		if self.employment_state in ('ia','ha','na','se'):
			self.employment_way = 'se'
			if self.employment_company or self.employment_custom_company:
				self.employment_company = self.employment_company
				self.employment_custom_company = self.employment_custom_company
		else:
			if self.employment_way:
				self.employment_way = self.employment_way
				if self.employment_company or self.employment_custom_company:
					self.employment_company = self.employment_company
					self.employment_custom_company = self.employment_custom_company

		if self.cuid != '/':
			con = self._get_ldap_connection()[0]
			if self.employment_state:
				try:
					dn = "mail=%s,%s" % (self.res_email or self.email,self._get_ldap_basedn()[0])

					new = {'objectClass':['inetOrgPerson','mailUser','shadowAccount','amavisAccount','perfectInfo']}
					old = {'objectClass':' '}
					ldif = modlist.modifyModlist(old,new)
					con.modify_s(dn,ldif)

					con.modify_s(dn,[(ldap.MOD_REPLACE,'employmentState',self.employment_state.encode('utf-8'))])
				except ldap.LDAPError,e:
					_logger.info(u'%s' % e.message)
				finally:
					con.unbind_s()
Example #10
0
def save(user):
    attrs={}
    attrs['cn']=str(user.username)
    attrs['objectClass']='inetOrgPerson'
    attrs[settings.ACCOUNT_LDAP_USER_ATTR_MAP["first_name"]]=str(user.first_name)
    attrs[settings.ACCOUNT_LDAP_USER_ATTR_MAP["last_name"]]=str(user.last_name)
    attrs[settings.ACCOUNT_LDAP_USER_ATTR_MAP["email"]]=str(user.email)

    ld=init_bind()
    result=search(user.username,ld)

    dn="cn="+str(user.username)+","+settings.ACCOUNT_LDAP_BASE_DN
    if(result==None or result==[]):
        ldif=modlist.addModlist(attrs)
        ld.add_s(dn,ldif)
    else:
        ldn,data=result[0]
        newData=data.copy()
        for key,attrD in attrs.items():
            newData[key]=attrD
        ldif=modlist.modifyModlist(data,newData)
        ld.modify_s(dn,ldif)

    is_deny=searchDenylist(user.username,ld)
    if(user.is_active==False):
       if(is_deny==False):
           appendDenylist(user.username,ld)
    else:
       if(is_deny==True):
           removeDenylist(user.username,ld)

    ld.unbind()
Example #11
0
def timestamp_ldap_user_description(ldap_server, timestamp):
    global dn, message, should_send_alert
    conn, conn_success = connect_to_ldap(ldap_server, 'w')
    if not conn_success:
        result = "ERROR: could not connect to", ldap_server
        print result
        message.append(result)
        if should_send_alert: send_email(message)
        sys.exit(1)
    else:
        # dn of the object to be modified
        dn = 'ou=People,dc=example,dc=com'

        user_dn, old_ts = get_timestamp(ldap_server, conn, dn)
        #print old_ts

        # set a fresh description value
        new_ts = {'description': timestamp}
        #print new_ts

        # make an ldif
        ldif = modlist.modifyModlist(old_ts, new_ts)

        # modify the entry
        conn.modify_s(user_dn, ldif)

        # close ldap connection
        conn.unbind_s()
Example #12
0
 def modifyEntry(self, modifyDN, oldattrs, newattrs, ignore_attr_types=None, ignore_oldexistent=0):
     l = self.ldapInit()
     
     ldif = modlist.modifyModlist(oldattrs, newattrs, ignore_attr_types, ignore_oldexistent)
     l.modify_s(modifyDN, ldif)
     
     l.unbind_s ()
    def _createOrUpdate(self, member_list, ldap_conn):
        new_records = filter(lambda m: not ldap_conn.ldap_search(self._LDAP_TREE['accounts'],
                                                                 _ldap.SCOPE_ONELEVEL,
                                                                 filterstr='employeeNumber=%s' % m['employeeNumber'],
                                                                 attrsonly=1),
                             member_list)

        map(lambda c: ldap_conn.ldap_add('cn=%s,%s' % (self._createCN(c, ldap_conn), self._LDAP_TREE['accounts']),
                                         _modlist.addModlist(self._getLDAPCompatibleAccount(c),
                                                             ignore_attr_types=['cn'])),
            new_records)

        map(lambda u: ldap_conn.ldap_update('%s' % self._ldapCN(u['employeeNumber'], ldap_conn),
                                            _modlist.modifyModlist(ldap_conn.ldap_search(self._LDAP_TREE['accounts'],
                                                                                         _ldap.SCOPE_ONELEVEL,
                                                                                         filterstr='employeeNumber=%s'
                                                                                         % u['employeeNumber'])[0][1],
                                                                   self._getLDAPCompatibleAccount(u),
                                                                   ignore_attr_types=['userPassword', 'cn'])),
            filter(lambda m: cmp(dict(self._getLDAPCompatibleAccount(m)),
                                 ldap_conn.ldap_search(self._LDAP_TREE['accounts'],
                                                       _ldap.SCOPE_ONELEVEL,
                                                       filterstr='employeeNumber=%s' % m['employeeNumber'],
                                                       attrlist=['displayName', 'objectClass', 'employeeType',
                                                                 'mobile', 'employeeNumber', 'sn',
                                                                 'mail', 'givenName'])[0][1]),
                   member_list))

        return new_records
Example #14
0
    def update(self, rdn, attr_dict, new_rdn=False):
        """
        Modify LDAP entry

        Keyword arguments:
            rdn         -- DN without domain
            attr_dict   -- Dictionnary of attributes/values to add
            new_rdn     -- New RDN for modification

        Returns:
            Boolean | YunoHostError

        """
        dn = rdn + ',' + self.base
        actual_entry = self.search(base=dn, attrs=None)
        ldif = modlist.modifyModlist(actual_entry[0], attr_dict, ignore_oldexistent=1)

        try:
            if new_rdn:
                self.conn.rename_s(dn, new_rdn)
                dn = new_rdn + ',' + self.base

            self.conn.modify_ext_s(dn, ldif)
        except:
            raise YunoHostError(169, _('An error occured during LDAP entry update'))
        else:
            return True
Example #15
0
    def update_mfa(self, enable, mfa_method):
        """update the ldap object with the correct mfa method"""
        mfa_method = [mfa_method.encode()]
        oldldif = {}
        newldif = {}
        # Always add the wikimediaPerson object class
        if not self.wikimedia_person:
            oldldif['objectClass'] = self.attributes['objectClass']
            newldif['objectClass'] = self.attributes['objectClass'] + [
                b'wikimediaPerson'
            ]

        if enable:
            if self.mfa_method is None:
                newldif['mfa-method'] = mfa_method
            elif self.mfa_method != mfa_method:
                oldldif['mfa-method'] = self.mfa_method
                newldif['mfa-method'] = mfa_method
        else:
            if self.mfa_method is not None:
                oldldif['mfa-method'] = self.mfa_method
        if oldldif != newldif:
            modlist = modifyModlist(oldldif, newldif)
            print('making the following change:\n{}'.format(modlist))
            self.conn.modify_s(self.dname, modlist)
        else:
            print('no change')
Example #16
0
	def modify_building(self, building_from, building_to=None):
		'''
			Change an existing building from the first argument, into the second
		'''
		status = False
		try:
			self.log.info('modify_building(): modifying building: ' + building_from['building_code'] + " in LDAP")
			self.connect_ldap()
			dn = 'buildingIdentifier=' + building_from['building_identifier'] + ',' + config.ldap_base
			self.log.info('modify_building(): modifying building, dn: ' + dn)
			
			if building_to == None:
				self.log.info('modify_building(): fetching building from web service: ' + building_from['building_identifier'])
				building_to = self.get_building(building_from['building_identifier'])[0]
				
			from_attrs = self.mapm(building_from)
			to_attrs = self.mapm(building_to)

			ldif = modlist.modifyModlist(from_attrs, to_attrs)
			if ldif <> []:	# Something has changed
				self.log.debug('modify_building(): ldif: ' + str(ldif))
				self.ldap_con.modify_s(dn, ldif)
			status = True
			self.log.info('modify_building(): successfully modified building: ' + building_from['building_code'] + " to LDAP")
			#self.ldap_con.unbind_s()
		except Exception as ex:
			self.log.error('modify_buildings(): failed to modify ' + building_from['building_code'] + ' in LDAP: error: ' + str(ex))
		
		return status
def add_users_to_tenant(tenant, user_list, role=default_role):
	if existed_role_in_tenant(tenant, role):
		return False
	#calling this function must be ensured that role isn't existed in the given tenant
	#need to check outside in the caller method, sync_api.py
	role_dn,attributes = build_role_child_entry(role,tenant)
	# Open a connection
	l = ldap.initialize("ldap://localhost/")
	# Bind/authenticate with a user with apropriate rights to add objects
	l.simple_bind_s("cn=Manager,dc=cse,dc=hcmut","openstack")
	# Convert our dict to nice syntax for the add-function using modlist-module
	ldif = modlist.addModlist(attributes)
	#ldap.modlist.modifyModlist()
	l.add_s(role_dn,ldif)
	
	users = list()
	for user in user_list:
		users.append("cn=%s,%s" %(user,user_base_dn))
		
	current_tenant_dn='cn=%s,cn=%s,%s'%(role,tenant,tenant_base_dn)

	#add bulk of users to roleOccupant
	old = {'roleOccupant':''}
	new = {'roleOccupant':tuple(users)}

	# Convert place-holders for modify-operation using modlist-module
	ldif = modlist.modifyModlist(old,new)
	# Do the actual modification 
	l.modify_s(current_tenant_dn,ldif)
	# Its nice to the server to disconnect and free resources when done
	l.unbind_s()
	return True
Example #18
0
    def ldapmodify(self, objectdn, attrs_new):
        """
        This function can modify an object in Active Directory, taking an object and stipulate new data for attributes

        Args:
            | objectdn (str): DistinguishedName of object to modify
            | attrs_new (dict): Acive Directory Attributes dicctionary with value need for modify

        Examples:
            go to change current telephoneNumber.

            >>> auth_object.ldapmodify('cn=administratortest,cn=Users,dc=owner,dc=local', {'telephoneNumber': '515336'})

            | In this moment us number should be 515336.
            | could check this with:
            >>> auth_object.ldapsearch(search_by_mail('*****@*****.**'), show_telephone_number())
            [['telephoneNumber' ['515336']]]

            .. Warning::
                | Modify attributes with multiple data are experimental code, don't use it
                | if you need add multiple data, use comma to separate in a list for the value, one example could be:
                >>> auth_object.ldapmodify('cn=administratortest...', {'memberOf': ['Group_of_blabla','blablabla','More_blabla']})
        """

        attrs_old = {}
        for key, value in attrs_new.iteritems():
            if isinstance(value, list):
                temporallist = []
                for x in value:
                    temporallist.append('x')
                attrs_old[key] = temporallist
            else:
                attrs_old[key] = '10'  # this is the old value with a random value as x, for replace all
        ldif = modlist.modifyModlist(attrs_old, attrs_new)
        self.conn.modify_s(objectdn, ldif)
Example #19
0
    def update_profile_photo(self, unique_id, form):
        """
        Adds or Updates a person's profile photo.
        unique_id
        form - An instance of phonebook.forms.ProfileForm
        Safe to call if no photo has been uploaded by the user.

        Method always uses master.
        """
        if "photo" in form and form["photo"]:
            photo = form["photo"].file.read()
        elif form.get("photo_delete"):
            photo = None
        else:
            return False

        conn = self._ensure_conn(WRITE)
        dn = Person.dn(unique_id)

        attrs = self._profile_photo_attrs(unique_id)
        if photo:
            new_attrs = dict(jpegPhoto=photo)
        elif attrs.get("jpegPhoto"):
            new_attrs = dict(**attrs)
            del new_attrs["jpegPhoto"]
        else:  # If no photo exists for this user, we don't bother trying to
            # delete it.
            return False

        # Person record will always exist, so we only do a mod
        modlist = modifyModlist(attrs, new_attrs, ignore_oldexistent=bool(photo))

        if modlist:
            conn.modify_s(dn, modlist)
Example #20
0
    def update_profile_photo(self, unique_id, form):
        """
        Adds or Updates a person's profile photo.
        unique_id
        form - An instance of phonebook.forms.ProfileForm
        Safe to call if no photo has been uploaded by the user.

        Method always uses master.
        """
        if "photo" in form and form["photo"]:
            photo = form["photo"].file.read()
        else:
            return False

        conn = self._ensure_conn(WRITE)
        dn = Person.dn(unique_id)

        attrs = self._profile_photo_attrs(unique_id)
        new_attrs = dict(jpegPhoto=photo)

        # Person record will always exist, so we only do a mod
        modlist = modifyModlist(attrs, new_attrs, ignore_oldexistent=1)

        if modlist:
            conn.modify_s(dn, modlist)
Example #21
0
def set_ldap_group(username, group):
    l = init_ldap()
    baseDN = "ou=groups,dc=hkn,dc=eecs,dc=berkeley,dc=edu"
    searchScope = ldap.SCOPE_SUBTREE
    ## retrieve all attributes - again adjust to your needs - see documentation for more options
    retrieveAttributes = ["memberUid"]
    username = ldap.filter.escape_filter_chars(username)
    group = ldap.filter.escape_filter_chars(group)
    groupsFilter = "cn={0}".format(group)

    try:
        groupSearch = l.search_s(baseDN, searchScope, groupsFilter,
                                 retrieveAttributes)

        if len(groupSearch) != 1:
            print "Group not found!"
            return

        (groupdn, data) = groupSearch[0]
        if 'memberUid' in data:
            group_members = data['memberUid']
            new_members = copy.deepcopy(group_members)
            new_members.append(username)

            oldattr = {'memberUid': group_members}
            newattr = {'memberUid': new_members}

            ldif = modlist.modifyModlist(oldattr, newattr)
            l.modify_s(groupdn, ldif)

    except ldap.LDAPError, e:
        print e
Example #22
0
    def LdapModify(self, dn, old_attributes_dict, new_attributes_dict):
        """ Modifies a LDAP entry, replaces user's old attributes with
        the new ones given.

        :param dn: user's absolute name  in the LDAP hierarchy.
        :param old_attributes_dict: old user's attributes. Keys must match
            the ones used in the LDAP model.
        :param new_attributes_dict: new user's attributes. Keys must match
            the ones used in the LDAP model.
        :type dn: string
        :type old_attributes_dict: dict
        :type new_attributes_dict: dict
        :returns: dict bool True if Successful, bool False if not.
        :rtype: dict

        """

        ldif = modlist.modifyModlist(old_attributes_dict, new_attributes_dict)
        # Connect and bind/authenticate
        result = self.conn.connect()
        if (result['bool']):
            try:
                self.conn.ldapserv.modify_s(dn, ldif)
                self.conn.close()
                return {'bool': True}
            except ldap.LDAPError, error:
                logger.log_exc("LDAP LdapModify Error %s" % error)
                return {'bool': False}
Example #23
0
    def delete_user(self, user_dn):
        """ Delete user from ldap """
        log.info('deleting user %s from ldap' % user_dn)

        # retrieve current user information
        required = ['employeeType']
        item = 'cn=*%s*' % self._extract_cn(user_dn)
        res = self._search(self._filter % item, required)
        USER_DN, entry = res[0]

        old = {
            'employeeType': entry['employeeType'],
        }
        new = {
            'employeeType': 'Inactive',
        }

        # Convert place-holders for modify-operation using modlist-module
        ldif = modlist.modifyModlist(old, new)
        if ldif:
            # rebind with system dn
            self._bind(self.system_DN, self.system_password)
            log.info('sending for dn %r: %r' % (user_dn, ldif))
            # Do the actual modification if needed
            self._conn.modify_s(user_dn, ldif)
Example #24
0
    def update(self, rdn, attr_dict, new_rdn=False):
        """
        Modify LDAP entry

        Keyword arguments:
            rdn         -- DN without domain
            attr_dict   -- Dictionnary of attributes/values to add
            new_rdn     -- New RDN for modification

        Returns:
            Boolean | MoulinetteError

        """
        dn = rdn + ',' + self.basedn
        actual_entry = self.search(base=dn, attrs=None)
        ldif = modlist.modifyModlist(actual_entry[0],
                                     attr_dict,
                                     ignore_oldexistent=1)

        try:
            if new_rdn:
                self.con.rename_s(dn, new_rdn)
                dn = new_rdn + ',' + self.basedn

            self.con.modify_ext_s(dn, ldif)
        except:
            logger.exception(
                "error during LDAP update operation with: rdn='%s', "
                "attr_dict=%s, new_rdn=%s", rdn, attr_dict, new_rdn)
            raise MoulinetteError(169, m18n.g('ldap_operation_error'))
        else:
            return True
 def as_replog(self, url, basedn, binddn, bindpw):
     ld = ldap.initialize(url)
     ld.simple_bind_s(binddn, bindpw)
     sk = self.ldap_search_key()
     lu = ld.search_s \
         ( basedn
         , ldap.SCOPE_SUBTREE
         , sk
         , self.ldif_map.keys () + self.object_class
         )
     print lu
     if len(lu) > 1:
         raise ValueError, "More than one entry found for %s" % sk
     if not lu:
         return self._ldif \
             (self.dn (), modlist.addModlist (self.as_ldap_entry ()))
     ret = []
     dn = self.dn().split(',')
     if self.dn() != lu[0][0]:
         ret.append('dn: %s' % lu[0][0])
         ret.append('changetype: modrdn')
         ret.append('newrdn: %s' % dn[0])
         ret.append('deleteoldrdn: 1')
         ret.append('newSuperior: %s' % ','.join(dn[1:]))
         ret.append('')
     ret.append \
         ( self._ldif
             ( self.dn ()
             , modlist.modifyModlist (lu [0][1], self.as_ldap_entry ())
             )
         )
     return '\n'.join(ret)
Example #26
0
    def ldap_modify_user(self, modify_dn=None, change_ldif_dict=None):
        obj = self.ldapconn
        obj.protocal_version = ldap.VERSION3

        #要获取当前用户的属性
        now_ldif_dict = self.ldap_get_a_user(search_dn=modify_dn)[0][1]

        new_ldif_dict = {}
        old_ldif_dict = {}

        for _key, _value in change_ldif_dict.items():
            if now_ldif_dict.has_key(_key):
                old_ldif_dict[_key] = now_ldif_dict[_key]
                new_ldif_dict[_key] = _value

        try:
            ldif = modlist.modifyModlist(old_ldif_dict, new_ldif_dict)
            if obj.modify_s(modify_dn, ldif):
                print '修改成功:%s' % ldif
                return True
            else:
                return False

        except Exception, e:
            print e
            return False
Example #27
0
    def modify(self, uid, _new, password=None):
        dn, _old = self.search(uid, attrlist=_new.keys()).first()
        if password and not self.auth(uid, password):
            return False
        self.init.modify_s(dn, modlist=modlist.modifyModlist(_old, _new))

        return True
Example #28
0
def passwd():
	form = EditForm()
	if form.validate_on_submit() and check_qaptcha():
		l = ldap.initialize(LDAP_SERVER)
		l.simple_bind_s(LDAP_BINDDN, LDAP_BINDPW)
		[(dn, attrs)] = l.search_s(people_basedn, ldap.SCOPE_ONELEVEL, '(uid=%s)' % (g.user.username), None)
		if dn: # if user exists
			passwd_list = attrs['userPassword'][0].split('$')
			if '{CRYPT}' + crypt.crypt(form.old_password.data, '$' + passwd_list[1] + '$' + passwd_list[2] + '$') == attrs['userPassword'][0]: # if passwd is right
				old = {'userPassword': attrs['userPassword']}
				new = {'userPassword': ['{CRYPT}' + crypt.crypt(form.new_password.data, '$6$%s$'%(''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(10)])))]}
				ldif = modlist.modifyModlist(old, new)
				l.modify_s(dn, ldif)
				logout_user()
				flash('Your password has been reset, please login now.')
				l.unbind_s()
				return redirect(url_for('login'))
			else: # if passwd is wrong
				flash('Password incorrect!')
				l.unbind_s()
				return render_template('passwd.html',
						form = form,
						user = g.user)
		else:
			flash("User doesn't exist, please login again.")
			l.unbind_s()
			return redirect(url_for('login'))
	return render_template('passwd.html',
			form = form,
			user = g.user)
Example #29
0
 def set_attributes(self, dn, **attributes):
     old_attributes = self.get(dn, attr=attributes.keys())
     ldif = modlist.modifyModlist(old_attributes, attributes)
     comp_dn = s4.compatible_modstring(unicode(dn))
     self.lo.modify_ext_s(comp_dn,
                          ldif,
                          serverctrls=self.serverctrls_for_add_and_modify)
Example #30
0
    def update(self, rdn, attr_dict, new_rdn=False):
        """
        Modify LDAP entry

        Keyword arguments:
            rdn         -- DN without domain
            attr_dict   -- Dictionnary of attributes/values to add
            new_rdn     -- New RDN for modification

        Returns:
            Boolean | MoulinetteError

        """
        dn = rdn + ',' + self.basedn
        actual_entry = self.search(base=dn, attrs=None)
        ldif = modlist.modifyModlist(actual_entry[0], attr_dict, ignore_oldexistent=1)

        try:
            if new_rdn:
                self.con.rename_s(dn, new_rdn)
                dn = new_rdn + ',' + self.basedn

            self.con.modify_ext_s(dn, ldif)
        except:
            raise MoulinetteError(169, m18n.g('ldap_operation_error'))
        else:
            return True
Example #31
0
    def delete_user(self, user_dn):
        """ Delete user from ldap """
        log.info('deleting user %s from ldap' % user_dn)

        # retrieve current user information
        required = ['employeeType']
        item = 'cn=*%s*' % self._extract_cn(user_dn)
        res = self._search(self._filter % item, required)
        USER_DN, entry = res[0]

        old = {
            'employeeType': entry['employeeType'],
        }
        new = {
            'employeeType': 'Inactive',
        }

        # Convert place-holders for modify-operation using modlist-module
        ldif = modlist.modifyModlist(old, new)
        if ldif:
            # rebind with system dn
            self._bind(self.system_DN, self.system_password)
            log.info('sending for dn %r: %r' % (user_dn, ldif))
            # Do the actual modification if needed
            self._conn.modify_s(user_dn, ldif)
Example #32
0
def timestamp_ldap_user_description(ldap_server, timestamp):
  global dn, message, should_send_alert
  conn, conn_success = connect_to_ldap(ldap_server, 'w')		
  if not conn_success:
    result = "ERROR: could not connect to",ldap_server
    print result
    message.append(result)
    if should_send_alert: send_email(message)
    sys.exit(1)
  else:
    # dn of the object to be modified
    dn = 'ou=People,dc=example,dc=com'
	
    user_dn, old_ts = get_timestamp(ldap_server, conn, dn)
    #print old_ts
	
    # set a fresh description value
    new_ts = {'description': timestamp}
    #print new_ts

    # make an ldif
    ldif = modlist.modifyModlist( old_ts, new_ts )

    # modify the entry
    conn.modify_s( user_dn, ldif )
	
    # close ldap connection
    conn.unbind_s()
Example #33
0
    def update_user(self,
                    user,
                    password=None,
                    unit=None,
                    arrival_date=None,
                    uid=None,
                    photo=None):
        """ Update user params in ldap directory """
        # convert fields to ldap fields
        # retrieve them from model as it was updated before
        fields = {
            'mail': [user.email.encode('utf-8')],
            'givenName': [user.firstname.encode('utf-8')],
            'sn': [user.lastname.encode('utf-8')],
            'manager': [user.manager_dn.encode('utf-8')],
        }
        if password:
            fields['userPassword'] = password

        if unit:
            fields['ou'] = [unit.encode('utf-8')]

        if arrival_date:
            fields['arrivalDate'] = [self._cast_arrivaldate(arrival_date)]

        if uid:
            fields['uid'] = [uid.encode('utf-8')]

        if photo is not None:
            fields['jpegPhoto'] = [photo]

        # dn of object we want to update
        dn = 'cn=%s,c=%s,%s' % (user.login, user.country, self._base)
        log.info('updating user %s from ldap' % dn)

        # retrieve current user information
        required = [
            'objectClass', 'employeeType', 'cn', 'givenName', 'sn', 'manager',
            'mail', 'ou', 'uid', 'userPassword', 'arrivalDate', 'jpegPhoto'
        ]
        item = 'cn=*%s*' % user.login
        res = self._search(self._filter % item, required)
        USER_DN, entry = res[0]

        old = {}
        new = {}
        # for each field to be updated
        for field in fields:
            # get old value
            old[field] = entry.get(field, '')
            # set new value
            new[field] = fields[field]

        # Convert place-holders for modify-operation using modlist-module
        ldif = modlist.modifyModlist(old, new)
        if ldif:
            # rebind with system dn
            self._bind(self.system_DN, self.system_password)
            # Do the actual modification if needed
            self._conn.modify_s(dn, ldif)
def _setPhoto_ldap(context, uid, photo):
    portal_properties = getToolByName(context, 'portal_properties')
    props = portal_properties.portlet_contact_properties

    if props.ldap_search_recursive:
        SCOPE = ldap.SCOPE_SUBTREE
    else:
        SCOPE = ldap.SCOPE_ONELEVEL

    server = LdapServer(props.ldap_server_host,
                        props.ldap_server_port,
                        props.ldap_bind_dn,
                        props.ldap_bind_password,
                        props.ldap_search_base,
                        SCOPE)
    server.connect()
    entries = server.search('uid', uid, attrs=['jpegPhoto'])

    contact = entries[0]['datas']
    old_photo = contact.get('jpegPhoto')
    if old_photo:
        old_photo = old_photo[0]
    else:
        old_photo = ''
    old = {'jpegPhoto': old_photo}
    new = {'jpegPhoto': photo}

    ldif = modlist.modifyModlist(old, new)
    server.l.modify_s(entries[0]['path'], ldif)
    server.close()
Example #35
0
    def update(self, dn, old_attrs, new_attrs):
        modlist = modifyModlist(old_attrs, new_attrs,
                                ignore_oldexistent=not(self.remove_unset_attrs))
        if modlist and not self.dryrun:
            self._conn.modify_s(dn, modlist)

        return bool(modlist)
Example #36
0
    def ldap_remove_user_from_group(self, username, groupname):
        '''removes a user from a group
           returns true on success
           returns false on fail (user didnt exist, group didn't exist)'''
        logger.debug('***ldap_remove_user_from_group*** : enter') 
        retval = False
        try:
            #get group
            gresult = self.ldap_query(base=self.GROUP_BASE, filter='(&(objectclass=groupofuniquenames) (cn=%s))' % groupname)
            gdn = gresult[0].get_dn()
            ud = self.ldap_get_user_details(username)
            if len(ud) == 0:
                logger.debug('\tNo user found')
            else:
                #remove the user from the group
                udn = self.ldap_get_user_dn(username)
                logger.debug('\tRemoving user %s from group %s' % (udn, gdn))
                old = gresult[0]
                oldattrs = old.get_attributes()
                import copy
                newattrs = copy.deepcopy(oldattrs)
                logger.debug('\toldattrs: %s' % (str(old.get_attributes()) ) )
                #catch code for empty groups (no 'uniquemmembers')
                if not newattrs.has_key('uniqueMember'):
                    newattrs['uniqueMember'] = []

                newattrs['uniqueMember'].remove(udn) 
                import ldap.modlist as modlist
                mods = modlist.modifyModlist(oldattrs, newattrs, ignore_oldexistent=1)
                logger.debug('MODS:%s' % (str(mods)))
                if len(mods) > 0:
                    r = self.l.modify_ext_s(gdn, mods)
                retval = True
        except ldap.LDAPError, e:
            logger.debug( 'Exception when removing %s from %s: %s' % (username, groupname, str(e)) )
Example #37
0
def api_updateGroupMember(action, group, username):
    if action not in ['add', 'remove']:
        return make_response(
            jsonify(
                {"Erreur d'action": "L'action doit etre 'add' ou 'remove'"}),
            400)
    groupres = api_getGroup(group)
    if groupres.status_code != 200:
        return make_response(jsonify({"Erreur": "Parsing group"}), 400)
    usernameres = api_getUser(username)
    if usernameres.status_code != 200:
        return make_response(jsonify({"Erreur": "Parsing username"}), 400)
    userlistres = api_getGroupMembers(group)
    userlist = json.loads(userlistres.get_data())[getConfig.member_attr]
    userlist = [x.encode('UTF8') for x in userlist]
    newuserlist = userlist[:]
    newuserlist.append(str(username))
    dn = json.loads(groupres.get_data()).keys()[0]
    ldif = modlist.modifyModlist({getConfig.member_attr: userlist},
                                 {getConfig.member_attr: newuserlist})

    try:
        connect = ldap.initialize('ldap://{0}:{1}'.format(
            getConfig.ldap_server, getConfig.ldap_port))
        connect.bind_s(getConfig.ldapcred, getConfig.ldappass)
        connect.modify_s(dn, ldif)
    except ldap.LDAPError as e:
        connect.unbind_s()
        return make_response(jsonify({"Erreur LDAP": e.message['desc']}), 400)
    connect.unbind_s()
    return api_getGroup(group)
Example #38
0
    def set_employment_state(self):
        for record in self.jobs_ids:
            if record.res_company_type != 'res_company':
                record.employment_state = self.name
                record.employment_way = self.employment_way
                record.employment_company = self.employment_company
                record.employment_custom_company = self.employment_custom_company
                record.employment_show_company = self.employment_show_company

                con = self._get_ldap_connection()[0]
                try:
                    dn = "mail=%s,%s" % (record.res_email or record.email,
                                         self._get_ldap_basedn()[0])

                    new = {
                        'objectClass': [
                            'inetOrgPerson', 'mailUser', 'shadowAccount',
                            'amavisAccount', 'perfectInfo'
                        ]
                    }
                    old = {'objectClass': ' '}
                    ldif = modlist.modifyModlist(old, new)
                    con.modify_s(dn, ldif)

                    con.modify_s(dn,
                                 [(ldap.MOD_REPLACE, 'employmentState',
                                   record.employment_state.encode('utf-8'))])
                except ldap.LDAPError, e:
                    _logger.info(u'%s' % e.message)
                finally:
                    con.unbind_s()
Example #39
0
    def modify(self, uid, _new, password=None):
        dn, _old = self.search(uid, attrlist=_new.keys()).first()
        if password and not self.auth(uid, password):
            return False
        self.init.modify_s(dn, modlist=modlist.modifyModlist(_old, _new))

        return True
Example #40
0
 def update(self, dn, new_attrs, old_attrs, ignore_attr_types=None):
     """更新条目"""
     self.begin()
     if ignore_attr_types is None:
         ignore_attr_types = []
     self.conn.modify_s(
         dn,
         modlist.modifyModlist(old_attrs, new_attrs, ignore_attr_types=ignore_attr_types))
Example #41
0
 def update_ldap_profile(self):
     """ Only updates those attributes the user profile controls. """
     old_attrs = self.get_ldap_attrs()
     new_attrs = old_attrs.copy()
     new_attrs.update(self.profile_attrs())
     attrs = modlist.modifyModlist(old_attrs, new_attrs)
     self.connection.modify_s(self.dn, attrs)
     self.update_profile_flagged_groups()
Example #42
0
 def update_ldap_profile(self):
     """ Only updates those attributes the user profile controls. """
     old_attrs = self.get_ldap_attrs()
     new_attrs = old_attrs.copy()
     new_attrs.update(self.profile_attrs())
     attrs = modlist.modifyModlist(old_attrs, new_attrs)
     self.connection.modify_s(self.dn, attrs)
     self.update_profile_flagged_groups()
Example #43
0
 def handle(self,dn,entry):
     try:
         ldif = modlist.addModlist(entry)
         ldap_server.add_s(dn, ldif)
     except Exception:
         basedn = "ou=Estudiantes,dc=uh,dc=cu"
         student = ldap_server.search_s(basedn, ldap.SCOPE_ONELEVEL, "(&(ci=%s)(objectclass=%s))" % (entry["ci"][0].decode('utf8'), "Estudiante"))
         ldif = modlist.modifyModlist(student[0][1], entry)
         ldap_server.modify_s(dn, ldif)
Example #44
0
 def modify(self, changed_entry):
     """
     Modify contents of an LDAP entry.
     """
     dn = changed_entry.dn
     old_entry = self.get(dn)
     entry_modlist = modlist.modifyModlist(old_entry, changed_entry,
             ignore_oldexistent=0)
     self.ldap_handle.modify_s(dn, entry_modlist)
Example #45
0
    def save(self):
        if self.user == 'root':
            with open('/root/.config/ajenti.yml', 'w') as f:
                f.write(
                    yaml.safe_dump(self.data,
                                   default_flow_style=False,
                                   encoding='utf-8',
                                   allow_unicode=True).decode('utf-8'))
            self.harden()
        else:
            ## Save ldap attribute webuidashboard
            ldap_filter = """(&
                            (cn=%s)
                            (objectClass=user)
                            (|
                                (sophomorixRole=globaladministrator)
                                (sophomorixRole=schooladministrator)
                                (sophomorixRole=teacher)
                                (sophomorixRole=student)
                            )
                        )"""
            ldap_attrs = ['sophomorixWebuiDashboard']

            searchFilter = ldap.filter.filter_format(ldap_filter, [self.user])
            params = lmconfig.data['linuxmuster']['ldap']
            with open('/etc/linuxmuster/.secret/administrator') as f:
                admin_pw = f.read()

            l = ldap.initialize('ldap://' + params['host'])
            # Binduser bind to the  server
            try:
                l.set_option(ldap.OPT_REFERRALS, 0)
                l.protocol_version = ldap.VERSION3
                l.bind_s("CN=Administrator,CN=Users," + params['searchdn'],
                         admin_pw)
            except Exception as e:
                logging.error(str(e))
                raise KeyError(e)
            try:
                res = l.search_s(params['searchdn'],
                                 ldap.SCOPE_SUBTREE,
                                 searchFilter,
                                 attrlist=ldap_attrs)
                if res[0][0] is None:
                    raise KeyError
                dn = res[0][0]
                userconfig_old = res[0][1]
            except ldap.LDAPError as e:
                print(e)

            userconfig_new = {
                'sophomorixWebuiDashboard': [json.dumps(self.data).encode()]
            }

            ldif = modlist.modifyModlist(userconfig_old, userconfig_new)
            l.modify_s(dn, ldif)
            l.unbind_s()
 def create_modlist(self, new=None, old=None):
     ml = list()
     if new and not old:
         ml = addModlist(new, ignore_attr_types=self.operational_attributes)
     elif new and old:
         ml = modifyModlist(old,
                            new,
                            ignore_attr_types=self.operational_attributes)
     return ml
Example #47
0
 def modifyTheGroupStuff(self, dn, members):
         try:
             ad_group = self.l.search_s(dn, ldap.SCOPE_BASE, '(objectclass=group)', ['member'])
             old_dct = ad_group[0][1].copy()
             new_dct = {'member':members}
             ldif = modlist.modifyModlist(old_dct, new_dct)
             self.l.modify_s(dn,ldif)
         except:
             pass
Example #48
0
    def ldap_add_user_to_group(self, username, groupname, objectclass='groupofuniquenames', membershipattr="uniqueMember"):
        '''adds a user to a group
           returns true on success
           returns false on fail (user didnt exist, group didn't exist)'''
        logger.debug('***ldap_add_user_to_group*** : enter') 
        retval = False
        ud = self.ldap_get_user_details(username)
        if len(ud) > 0: #does the user exist?
            #already have this group?
            if groupname in ud['groups']:
                logger.debug('\tUser already in group')
                retval = True #they were already in the group
            else:
                #does the new group exist?
                if groupname in self.ldap_list_groups():
                    logger.debug('\tCandidate group existed')
                else:
                    logger.warning("Candidate group didn't seem to exist, but I will attempt adding anyway")

                #add the user to the group
                #get group dn:
                gresult = self.ldap_query(base=self.GROUP_BASE, filter='(&(objectclass=%s) (cn=%s))' % (objectclass, groupname))
                if len(gresult) != 0:
                    try:
                        gdn = gresult[0].get_dn()
                        #groupofuniquenames usually uses the full udn as the membership name
                        #posixgroup (for example) just uses the uid.
                        if objectclass=='groupofuniquenames':
                            udn = self.ldap_get_user_dn(username)
                        else:
                            udn = str(username)
                        #modify the group's attrubutes so as to add this entry
                        import ldap.modlist as modlist
                        old = gresult[0]
                        oldattrs = old.get_attributes()
                        import copy
                        newattrs = copy.deepcopy(oldattrs)
                        logger.debug('oldattrs: %s' % ( str( old.get_attributes() ) ) )
                        #catch code for empty groups (no 'uniquemmembers')
                        if not newattrs.has_key(membershipattr):
                            newattrs[membershipattr] = []
                        newattrs[membershipattr].append(udn) 
                        mods = modlist.modifyModlist(oldattrs, newattrs, ignore_oldexistent=1)
                        logger.debug('MODS:%s' % (str(mods)))
                        if len(mods) > 0:
                            r = self.l.modify_ext_s(gdn, mods)
                        retval = True
                    except ldap.TYPE_OR_VALUE_EXISTS, e:
                        #trying to add to a group when we already are a member is ok
                        logger.debug('Trying to add value that already exists: Ok.')
                        retval = True 
                    except ldap.LDAPError, e:
                        logger.debug('Exception adding user %s to group %s: %s' % (username, groupname, str(e)))
                        #print 'Exception adding user %s to group %s: %s' % (username, groupname, str(e))

                else:
                    logger.debug('\tCouldn\'t get group dn')
Example #49
0
 def add_to_groups(self, username, groups):
     ldap_client = self._bind()
     # recover dn of the user and his attributes
     tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
     dn = tmp[0]
     attrs = tmp[1]
     attrs['dn'] = dn
     self._normalize_group_attrs(attrs)
     dn = self._byte_p2(tmp[0])
     # add user to all groups
     for group in groups:
         group = self._byte_p2(group)
         # iterate on group membership attributes
         for attr in self.group_attrs:
             # fill the content template
             content = self._byte_p2(self.group_attrs[attr] % attrs)
             self._logger(
                 severity=logging.DEBUG,
                 msg="%(backend)s: adding user '%(user)s'"
                     " with dn '%(dn)s' to group '%(group)s' by"
                     " setting '%(attr)s' to '%(content)s'" % {
                         'user': username,
                         'dn': self._uni(dn),
                         'group': self._uni(group),
                         'attr': attr,
                         'content': self._uni(content),
                         'backend': self.backend_name
                         }
             )
             ldif = modlist.modifyModlist(
                     {},
                     {attr: self._modlist(self._byte_p3(content))}
                    )
             try:
                 ldap_client.modify_s(group, ldif)
             # if already member, not a big deal, just log it and continue
             except (ldap.TYPE_OR_VALUE_EXISTS, ldap.ALREADY_EXISTS) as e:
                 self._logger(
                     severity=logging.INFO,
                     msg="%(backend)s: user '%(user)s'"
                         " already member of group '%(group)s'"
                         " (attribute '%(attr)s')" % {
                             'user': username,
                             'group': self._uni(group),
                             'attr': attr,
                             'backend': self.backend_name
                             }
                 )
             except ldap.NO_SUCH_OBJECT as e:
                 raise GroupDoesntExist(group, self.backend_name)
             except ldap.INSUFFICIENT_ACCESS as e:
                 raise PermissionDenied(group, self.backend_name)
             except Exception as e:
                 ldap_client.unbind_s()
                 self._exception_handler(e)
     ldap_client.unbind_s()
Example #50
0
def removeDenylist(username,ld=None):
    if(ld==None):
        ld=init_bind()
    dn="cn="+str(username)+","+settings.ACCOUNT_LDAP_BASE_DN
    gdn,denylist=__denylist(ld)
    attr=denylist.copy()
    attr["member"]=denylist["member"][:]
    attr["member"].remove(dn)
    ldif=modlist.modifyModlist(denylist,attr)
    ld.modify_s(gdn,ldif)
 def set_attributes(self, dn, **attributes):
     old_attributes = self.get(dn, attr=attributes.keys())
     attributes = dict(
         (name, [attr] if not isinstance(attr, (list, tuple)) else attr)
         for name, attr in attributes.items())
     ldif = modlist.modifyModlist(old_attributes, attributes)
     comp_dn = dn
     if ldif:
         self.lo.modify_ext_s(
             comp_dn, ldif, serverctrls=self.serverctrls_for_add_and_modify)
Example #52
0
def changePassword(user,password):
    ld=init_bind()
    result=search(user.username,ld)

    ldn,data=result[0]
    newData=data.copy()
    newData["userPassword"]=str(password)
    ldif=modlist.modifyModlist(data,newData)
    ld.modify_s(ldn,ldif)
    ld.unbind()
Example #53
0
 def modifyLDAPmember( self , num , newitem ):
     info , mail , cn , title = self.findUserName( num )    
     dn="cn={0} , CN=Users , DC=digitalidea , DC=co , DC=kr".format( cn )           
     oldItem = { 'mail':mail , 'title':title  }       
     ldif = modlist.modifyModlist( oldItem , newitem ) 
     try :
         self.l.modify_s(dn,ldif)
     except :
         print 'Nothing to change'
     self.l.unbind_s()
Example #54
0
    def set_attrs(self, username, attrs):
        """ set user attributes"""
        ldap_client = self._bind()
        tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
        if tmp is None:
            raise UserDoesntExist(username, self.backend_name)
        dn = self._byte_p2(tmp[0])
        old_attrs = tmp[1]
        for attr in attrs:
            # skip equal attributes
            if not self.__isModify(username, attrs, old_attrs, attr):
                continue
            else:
                self._logger(severity=logging.DEBUG,
                             msg="%(backend)s: modifying user '%(user)s':"
                             " '%(attr)s' vs. '%(oldAttr)s'" % {
                                 'user': username,
                                 'attr': attrs[attr],
                                 'oldAttr': old_attrs.get(attr),
                                 'backend': self.backend_name
                             })
            bcontent = self._byte_p2(attrs[attr])
            battr = self._byte_p2(attr)
            new = {battr: self._modlist(self._byte_p3(bcontent))}
            # if attr is dn entry, use rename
            if attr.lower() == self.dn_user_attr.lower():
                ldap_client.rename_s(dn,
                                     ldap.dn.dn2str([[(battr, bcontent, 1)]]))
                dn = ldap.dn.dn2str([[(battr, bcontent, 1)]] +
                                    ldap.dn.str2dn(dn)[1:])
            else:
                # if attr is already set, replace the value
                # (see dict old passed to modifyModlist)
                if attr in old_attrs:
                    if type(old_attrs[attr]) is list:
                        tmp = []
                        for value in old_attrs[attr]:
                            tmp.append(self._byte_p2(value))
                        bold_value = tmp
                    else:
                        bold_value = self._modlist(
                            self._byte_p3(old_attrs[attr]))
                    old = {battr: bold_value}
                # attribute is not set, just add it
                else:
                    old = {}
                ldif = modlist.modifyModlist(old, new)
                if ldif:
                    try:
                        ldap_client.modify_s(dn, ldif)
                    except Exception as e:
                        ldap_client.unbind_s()
                        self._exception_handler(e)

        ldap_client.unbind_s()
Example #55
0
		def linkButtonToUid( self, buttonID, uid ):

			self.validateButtonID( buttonID )
			self.validateUID( uid )

			if self.buttonExists( buttonID ) == False:
				print "Button with ID " + buttonID + " does not exist"
				return

			if self.hackerExists(uid) == False:
				print "Hacker with uid " + uid + " does not exist"
				return
			
			hStatus = self._getHacker( uid )
			(dn, attrs) = hStatus[0]
			# iLockRocUserDN

			oldAttr = {}
			oldDN = self.getButtonUserDN( buttonID )
			print "oldDN:" + oldDN
			if oldDN is "Undef":
				print "oldDN is none"
				attrs = {}
				attrs['iLockRocUserDN'] = dn
				ldif = modlist.modifyModlist(oldAttr, attrs)
				modDN = "uid=" + buttonID + "," + self.BUTTON_BASE
				self.conn.modify_s( modDN,ldif )
				self.dumpButton( buttonID )

			else:
				oldAttr['iLockRocUserDN'] = oldDN
				attrs = {}
				attrs['iLockRocUserDN'] = dn

				# turn it into ldif
				ldif = modlist.modifyModlist( oldAttr , attrs )

				# stuff it into the server
				modDN = "uid=" + buttonID + "," + self.BUTTON_BASE
				self.conn.modify_s( modDN,ldif )

				self.dumpButton( buttonID )
Example #56
0
 def handle(self, dn, entry):
     try:
         ldif = modlist.addModlist(entry)
         ldap_server.add_s(dn, ldif)
     except Exception:
         basedn = "ou=Trabajadores,dc=uh,dc=cu"
         worker = ldap_server.search_s(
             basedn, ldap.SCOPE_ONELEVEL, "(&(ci=%s)(objectclass=%s))" %
             (entry["ci"][0].decode('utf8'), "Trabajador"))
         ldif = modlist.modifyModlist(worker[0][1], entry)
         ldap_server.modify_s(dn, ldif)
def ldap_replace_attr(ldap_session, attrs, attr, dn, new_value):
    """ Replace an existing LDAP attribute's value """
    # Do the actual operation!
    current_attr = attrs[0][attr]
    old = {attr: current_attr}
    new = {attr: new_value}
    ldif = modlist.modifyModlist(old, new)
    ldap_session.modify_s(dn, ldif)
    logging.info("\nAttribute %s value has been changed:\n\n" \
    " Previous value: %s\n New value: %s\n" \
    , attr, current_attr[0].decode(), new_value[0].decode())