ldapjs / node-ldapjs

LDAP Client and Server API for node.js
http://ldapjs.org
MIT License
1.61k stars 452 forks source link

Sharing unescape DN code for helper method #968

Open ansibleguy76 opened 9 months ago

ansibleguy76 commented 9 months ago

While implementing ldap authentication against AD with ldapjs, I have noticed the following :

When searching for a user with non-ascii characters, I noticed AD returns the DN encoded.

example : Search for user "kürt" returned : CN=K\c3\bcrt, ... (\c3\bc => hex for ü)

I then need to send the DN again to ldap to authenticate with it. However AD required the non-decoded DN. CN=Kürt ...

function unescapeLdapResult(ldapResult) {
  // Regular expression to match the escaped sequences
  const regex = /\\([0-9a-fA-F]{2})\\([0-9a-fA-F]{2})/g;

  // Replace each escaped sequence with its Unicode character
  return ldapResult.replace(regex, (match, p1, p2) => {
      // Convert the hex codes to a Buffer
      const bytes = Buffer.from([parseInt(p1, 16), parseInt(p2, 16)]);
      // Convert the Buffer to a UTF-8 String
      return bytes.toString('utf8');
  });
}

I have created this function to acquire this, it would nice to have it as a helper method