How to use the ldap3.utils.conv.to_unicode function in ldap3

To help you get started, we’ve selected a few ldap3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cannatag / ldap3 / ldap3 / strategy / MockBase.py View on Github external
node.matched.add(candidate)
                            else:
                                node.unmatched.add(candidate)
        elif node.tag == MATCH_LESS_OR_EQUAL:
            attr_name = node.assertion['attr']
            attr_value = node.assertion['value']
            for candidate in candidates:
                if attr_name in self.entries[candidate]:
                    for value in self.entries[candidate][attr_name]:
                        if value.isdigit() and attr_value.isdigit():  # int comparison
                            if int(value) <= int(attr_value):
                                node.matched.add(candidate)
                            else:
                                node.unmatched.add(candidate)
                        else:
                            if to_unicode(value).lower() <= to_unicode(attr_value).lower():  # case insentive string comparison
                                node.matched.add(candidate)
                            else:
                                node.unmatched.add(candidate)
        elif node.tag == MATCH_EXTENSIBLE:
            pass
        elif node.tag == MATCH_PRESENT:
            attr_name = node.assertion['attr']
            for candidate in candidates:
                if attr_name in self.entries[candidate]:
                    node.matched.add(candidate)
                else:
                    node.unmatched.add(candidate)
        elif node.tag == MATCH_SUBSTRING:
            attr_name = node.assertion['attr']
            # rebuild the original substring filter
            if node.assertion['initial']:
github cannatag / ldap3 / ldap3 / extend / microsoft / modifyPassword.py View on Github external
def ad_modify_password(connection, user_dn, new_password, old_password, controls=None):
    # old password must be None to reset password with sufficient privileges
    if connection.check_names:
        user_dn = safe_dn(user_dn)
    if str is bytes:  # python2, converts to unicode
        new_password = to_unicode(new_password)
        if old_password:
            old_password = to_unicode(old_password)

    encoded_new_password = ('"%s"' % new_password).encode('utf-16-le')

    if old_password:  # normal users must specify old and new password
        encoded_old_password = ('"%s"' % old_password).encode('utf-16-le')
        result = connection.modify(user_dn,
                                   {'unicodePwd': [(MODIFY_DELETE, [encoded_old_password]),
                                                   (MODIFY_ADD, [encoded_new_password])]},
                                   controls)
    else:  # admin users can reset password without sending the old one
        result = connection.modify(user_dn,
                                   {'unicodePwd': [(MODIFY_REPLACE, [encoded_new_password])]},
                                   controls)
github cannatag / ldap3 / ldap3 / strategy / mockBase.py View on Github external
else:
                for match in matched:
                    responses.append({
                        'object': match,
                        'attributes': [{'type': attribute,
                                        'vals': [] if request['typesOnly'] else self.connection.server.dit[match][attribute]}
                                       for attribute in self.connection.server.dit[match]
                                       if attribute.lower() in attributes or ALL_ATTRIBUTES in attributes]
                    })

                result_code = 0
                message = ''

        result = {'resultCode': result_code,
                  'matchedDN': '',
                  'diagnosticMessage': to_unicode(message, SERVER_ENCODING),
                  'referral': None
                  }

        return responses[:request['sizeLimit']] if request['sizeLimit'] > 0 else responses, result
github cannatag / ldap3 / ldap3 / protocol / formatters / validators.py View on Github external
"""
    Active Directory stores date/time values as the number of 100-nanosecond intervals
    that have elapsed since the 0 hour on January 1, 1601 till the date/time that is being stored.
    The time is always stored in Greenwich Mean Time (GMT) in the Active Directory.
    """
    if not isinstance(input_value, SEQUENCE_TYPES):
        sequence = False
        input_value = [input_value]
    else:
        sequence = True  # indicates if a sequence must be returned

    valid_values = []
    changed = False
    for element in input_value:
        if str is not bytes and isinstance(element, bytes):  # python3 try to converts bytes to string
            element = to_unicode(element)
        if isinstance(element, NUMERIC_TYPES):
            if 0 <= element <= 9223372036854775807:  # min and max for the AD timestamp starting from 12:00 AM January 1, 1601
                valid_values.append(element)
            else:
                return False
        elif isinstance(element, STRING_TYPES):  # tries to check if it is already be a AD timestamp
            if isinstance(format_ad_timestamp(to_raw(element)), datetime):  # valid Generalized Time string
                valid_values.append(element)
            else:
                return False
        elif isinstance(element, datetime):
            changed = True
            if element.tzinfo:  # a datetime with a timezone
                valid_values.append(to_raw((timegm(element.utctimetuple()) + 11644473600) * 10000000, encoding='ascii'))
            else:  # datetime without timezone, assumed local and adjusted to UTC
                offset = datetime.now() - datetime.utcnow()
github cannatag / ldap3 / ldap3 / strategy / MockBase.py View on Github external
for candidate in candidates:
                if attr_name in self.entries[candidate]:
                    node.matched.add(candidate)
                else:
                    node.unmatched.add(candidate)
        elif node.tag == MATCH_SUBSTRING:
            attr_name = node.assertion['attr']
            # rebuild the original substring filter
            if node.assertion['initial']:
                substring_filter = to_unicode(node.assertion['initial'])
            else:
                substring_filter = ''

            if node.assertion['any']:
                for middle in node.assertion['any']:
                    substring_filter += '.*' + to_unicode(middle)

            if node.assertion['final']:
                substring_filter += '.*' + to_unicode(node.assertion['final'])

            regex_filter = re.compile(substring_filter, flags=re.UNICODE)
            for candidate in candidates:
                if attr_name in self.entries[candidate]:
                    for value in self.entries[candidate][attr_name]:
                        if regex_filter.match(to_unicode(value)):
                            node.matched.add(candidate)
                        else:
                            node.unmatched.add(candidate)
                else:
                    node.unmatched.add(candidate)
        elif node.tag == MATCH_EQUAL or node.tag == MATCH_APPROX:
            attr_name = node.assertion['attr']
github cannatag / ldap3 / ldap3 / strategy / MockBase.py View on Github external
attribute = request['attribute']
        value = request['value']
        if dn in self.entries:
            if attribute in self.entries[dn]:
                if self.entries[dn][attribute] == value:
                    result_code = 6
                    message = ''
                else:
                    result_code = 5
                    message = ''
        else:
            result_code = 32
            message = 'object not found'

        return {'resultCode': result_code,
                'matchedDN': to_unicode(''),
                'diagnosticMessage': to_unicode(message),
                'referral': None
                }
github cannatag / ldap3 / ldap3 / operation / search.py View on Github external
def decode_vals_fast(vals):
    try:
        return [to_unicode(val[3], from_server=True) for val in vals if val] if vals else None
    except UnicodeDecodeError:
        return [val[3] for val in vals if val] if vals else None
github cannatag / ldap3 / ldap3 / strategy / mockBase.py View on Github external
self._paged_sets.append(paged_set)
                            return response, result
                        else:
                            return [], result
                    else:
                        for paged_set in self._paged_sets:
                            if paged_set.cookie == decoded_control[1]['value']['cookie']: # existing paged set
                                response, result = paged_set.next()  # returns next bunch of entries as per paged set specifications
                                if paged_set.done:
                                    self._paged_sets.remove(paged_set)
                                return response, result
                        # paged set not found
                        message = 'Invalid cookie in simple paged search'
                        result = {'resultCode': RESULT_OPERATIONS_ERROR,
                                  'matchedDN': '',
                                  'diagnosticMessage': to_unicode(message, SERVER_ENCODING),
                                  'referral': None
                                  }
                        return [], result

        else:
            return self._execute_search(request)
github cannatag / ldap3 / ldap3 / strategy / MockBase.py View on Github external
value = request['value']
        if dn in self.entries:
            if attribute in self.entries[dn]:
                if self.entries[dn][attribute] == value:
                    result_code = 6
                    message = ''
                else:
                    result_code = 5
                    message = ''
        else:
            result_code = 32
            message = 'object not found'

        return {'resultCode': result_code,
                'matchedDN': to_unicode(''),
                'diagnosticMessage': to_unicode(message),
                'referral': None
                }
github cannatag / ldap3 / ldap3 / operation / bind.py View on Github external
def bind_response_to_dict_fast(response):
    response_dict = dict()
    response_dict['result'] = int(response[0][3])  # resultCode
    response_dict['description'] = RESULT_CODES[response_dict['result']]
    response_dict['dn'] = to_unicode(response[1][3], from_server=True)  # matchedDN
    response_dict['message'] = to_unicode(response[2][3], from_server=True)  # diagnosticMessage
    response_dict['referrals'] = None  # referrals
    response_dict['saslCreds'] = None  # saslCreds
    for r in response[3:]:
        if r[2] == 3:  # referrals
            response_dict['referrals'] = referrals_to_list(r[3])  # referrals
        else:
            response_dict['saslCreds'] = bytes(r[3])  # saslCreds

    return response_dict