Skip to content

Instantly share code, notes, and snippets.

@101arrowz
Created March 11, 2024 19:08
Show Gist options
  • Save 101arrowz/602aec6d0935dbcb5621f6c548955f4f to your computer and use it in GitHub Desktop.
Save 101arrowz/602aec6d0935dbcb5621f6c548955f4f to your computer and use it in GitHub Desktop.
TNS lookup with LDAP for Oracle Database
import ldap from 'ldapjs';
const makeLDAPURL = (server: string) => {
const [domain, mainPort, altPort] = server.split(':');
return [mainPort, altPort].map(port => `ldap://${domain}:${port}`);
}
// Finds a TNS string from the LDAP source
// Adapted from https://github.com/oracle/python-oracledb/discussions/71#discussioncomment-3918181
export async function tnsLookupLDAP(dbName: string, directoryServers: string[], defaultContext?: string) {
const client = ldap.createClient({
url: directoryServers.flatMap(makeLDAPURL)
});
const directory = `cn=${dbName},cn=OracleContext${defaultContext ? ',' + defaultContext : ''}`;
const results = await new Promise<ldap.SearchEntryObject[]>((resolve, reject) => {
setTimeout(() => reject(new Error('Request timeout')), 10000);
client.search(directory, {}, (err, res) => {
if (err) return reject(err);
const entries: ldap.SearchEntryObject[] = [];
res.on('searchEntry', entry => {
entries.push(entry.pojo);
});
res.on('end', result => {
if (!result || result.status !== 0) {
reject(new Error(`LDAP request failed${result ? ': ' + result.errorMessage : ''}`))
}
resolve(entries);
})
});
});
if (results.length !== 1 || results[0].objectName !== directory) {
throw new Error('failed to find LDAP result');
}
const tnsAttr = results[0].attributes.find(attr => attr.type === 'orclNetDescString');
if (!tnsAttr || tnsAttr.values.length !== 1) {
throw new Error('failed to locate TNS address');
}
return tnsAttr.values[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment