Created
June 29, 2016 14:53
-
-
Save pushpabrol/19e528587701ff61c0e867e1167af41f to your computer and use it in GitHub Desktop.
How to use ldapjs within a custom database connection in Auth0
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
function login(email, password, callback) { | |
var ldap = require('ldapjs'); | |
if (!global.ldapClient) { | |
// console.log('Global Client not found'); | |
var client = ldap.createClient({ | |
url: 'ldap://server:389', | |
idleTimeout: 30000 | |
}); | |
client.bind('uid=admin,ou=system', 'secret', function(err) { | |
if (err) callback(new Error("Error while contacting the authentication source!")); | |
else { | |
global.ldapClient = client; | |
signInUser(email, password, callback, client); | |
} | |
}); | |
} else { | |
//console.log('Global Client found'); | |
signInUser(email, password, callback, global.ldapClient); | |
} | |
function signInUser(email, password, cb, client) { | |
var opts = { | |
filter: '(&(|(mail=' + email + ')(uid=' + email + '))(objectClass=inetOrgPerson))', | |
scope: 'sub', | |
attributes: ['sn', 'cn', 'givenName', 'uid', 'mail'] | |
}; | |
var userExists = false; | |
client.search('ou=users,ou=system', opts, function(err, res) { | |
if (err) return cb(new Error(err.Message)); | |
res.on('searchEntry', function(entry) { | |
userExists = true; | |
client.bind(entry.object.dn, password, function(err) { | |
if (err) | |
{ | |
return cb(new WrongUsernameOrPasswordError('Incorrect Username or Password')); | |
} else { | |
var profile = {}; | |
profile.email = entry.object.mail; | |
profile.email_verified = true; | |
profile.family_name = entry.object.sn; | |
profile.user_id = entry.object.uid; | |
profile.given_name = entry.object.givenName; | |
profile.name = entry.object.cn; | |
profile.nickname = entry.object.uid; | |
return cb(null, profile); | |
} | |
}); | |
}); | |
res.on('searchReference', function(referral) { | |
}); | |
res.on('error', function(err) { | |
return cb(new Error(err.Message)); | |
}); | |
res.on('end', function(result) { | |
if (!userExists) { | |
return cb(new WrongUsernameOrPasswordError(null, 'Incorrect username or password')); | |
} | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment