Created
July 22, 2019 01:06
-
-
Save JackyYin/5ac639c259c4bcdb0e818b7a0b1cf1e9 to your computer and use it in GitHub Desktop.
a node.js ldap service use IIFE implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ldapjs = require('ldapjs'); | |
const url = process.env.LDAP_URL; | |
const LDAP_BIND_DN = process.env.LDAP_BIND_DN; | |
const LDAP_BIND_PWD = process.env.LDAP_BIND_PWD; | |
const SEARCH_DN = process.env.SEARCH_DN; | |
module.exports = (() => { | |
let client; | |
const connect = () => { | |
client = ldapjs.createClient({ | |
url, | |
tlsOptions: { | |
rejectUnauthorized: false | |
}, | |
reconnect: true | |
}); | |
client.on('error', err => { | |
console.warn('LDAP connection failed, but fear not, it will reconnect OK', err); | |
}); | |
} | |
const bind = (username, password) => { | |
return new Promise((resolve, reject) => { | |
client.bind(username, password, (err, result) => { | |
if (err) { | |
console.error('error!!!!'); | |
return reject(err); | |
} | |
resolve(result); | |
console.log('bind!!!!'); | |
}); | |
}) | |
}; | |
const bindAdPwd = () => { | |
return new Promise((resolve, reject) => { | |
client.bind(LDAP_BIND_DN, LDAP_BIND_PWD, (err, result) => { | |
if (err) { | |
console.error('error!!!!'); | |
return reject(err); | |
} | |
resolve(result); | |
console.log('bind!!!!'); | |
}); | |
}) | |
}; | |
const unbind = () => { | |
return new Promise((resolve, reject) => { | |
client.unbind(err => { | |
if (err) return reject(err); | |
resolve('unbind!!'); | |
console.log('unbind!!!!'); | |
}) | |
}) | |
}; | |
const search = (username) => { | |
const opts = { | |
filter: `(&(objectClass=user)(sAMAccountName=${username}))`, | |
scope: 'sub' | |
}; | |
let result = []; | |
return new Promise((resolve, reject) => { | |
client.search(SEARCH_DN, opts, (err, search) => { | |
if (err) reject(err); | |
search.on('searchEntry', entry => { | |
result.push(entry.object); | |
}); | |
search.on('end', () => { | |
resolve(result); | |
}); | |
}); | |
}) | |
}; | |
const modifyPwd = (dn, newPassword) => { | |
return new Promise((resolve, reject) => { | |
client.modify(dn, [ | |
new ldapjs.Change({ | |
operation: 'replace', | |
modification: { | |
unicodePwd: Buffer.from('"' + newPassword + '"', 'utf16le').toString() | |
} | |
}) | |
], (err, result) => { | |
if (err) reject(err); | |
resolve(result); | |
}); | |
}); | |
}; | |
connect(); | |
return { | |
bind, | |
bindAdPwd, | |
unbind, | |
search, | |
modifyPwd | |
} | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment