"""filters.py - misc stuff for handling LDAP filter strings (see RFC2254)"""importsix
[docs]defescape_filter_chars(assertion_value,escape_mode=0):""" Replace all special characters found in assertion_value by quoted notation. escape_mode If 0 only special chars mentioned in RFC 4515 are escaped. If 1 all NON-ASCII chars are escaped. If 2 all chars are escaped. """ifisinstance(assertion_value,six.text_type):assertion_value=assertion_value.encode("utf_8")s=[]forcinassertion_value:do_escape=Falseifstr!=bytes:# Python 3passelse:# Python 2c=ord(c)ifescape_mode==0:ifc==ord('\\')orc==ord('*') \
orc==ord('(')orc==ord(')') \
orc==ord('\x00'):do_escape=Trueelifescape_mode==1:ifc<'0'orc>'z'orcin"\\*()":do_escape=Trueelifescape_mode==2:do_escape=Trueelse:raiseValueError('escape_mode must be 0, 1 or 2.')ifdo_escape:s.append(b"\\%02x"%c)else:b=Noneifstr!=bytes:# Python 3b=bytes([c])else:# Python 2b=chr(c)s.append(b)returnb''.join(s)
[docs]deffilter_format(filter_template,assertion_values):""" filter_template String containing %s as placeholder for assertion values. assertion_values List or tuple of assertion values. Length must match count of %s in filter_template. """assertisinstance(filter_template,bytes)returnfilter_template%(tuple(map(escape_filter_chars,assertion_values)))