I have a project in which I use Express.js and activedirectory package for LDAP authentication.
I have a file called ad.js which includes-
exports.authUser = (username, password) => {
ad.authenticate(username, password, function (err, auth) {
if (err) {
console.log('ERROR: ' JSON.stringify(err));
return;
}
if (auth) {
console.log('Authenticated!');
} else {
console.log('Authentication failed!');
}
})
}
I call authUser
in app.js-
app.post("/login", (req, res) => {
let username = req.body.username;
let password = req.body.password;
authUser(username, password);
})
The authentication works but I want to access the value of auth
in app.js.
What is the correct way to perform that?
Thanks for any advice.
CodePudding user response:
You can "promisify" your function and then await
for the result. The main function returns a promise object and the route awaits for that promise to resolve.
exports.authUser = (username, password) => {
return new Promise((resolve, reject) => {
ad.authenticate(username, password, (err, auth) => {
if (err) {
console.log(`ERROR: ${JSON.stringify(err)}`);
return reject(err);
}
console.log(auth ? 'Authenticated!' : 'Authentication failed!');
return resolve(auth);
});
});
};
app.post("/login", async (req, res) => {
const username = req.body.username;
const password = req.body.password;
try {
const auth = await authUser(username, password);
} catch (error) {
// do something
}
});