Search in Ldap.js - javascript

I am trying to use the search method of Ldap.js in my node.js code. But it doesn't work. Here is my code:
searchFunc : function (){
console.log('inside search');
client.bind('cn=Manager,dc=foo,dc=com', kredito231, function(err) {
if (err) {
console.log(err);
client.unbind();
return;
}
var opts = {
filter: (('Email=*#foo.com'))
} ;
//This search works correct:
//client.search( 'cn=x,ou=users' + ',' + 'dc=foo,dc=com', function(err,res){
//This one doesn't work. But everything is done according api
client.search('dc=foo,dc=com', opts, function(err, res) {
res.on('searchEntry', function(entry) {
console.log('hit');
console.log('entry: ' + JSON.stringify(entry.object));
});
res.on('searchReference', function(referral) {
console.log('referral: ' + referral.uris.join());
});
res.on('error', function(err) {
console.log('searchFailed') ;
console.error('error: ' + err.message);
});
res.on('end', function(result) {
console.log('4') ;
console.log('status: ' + result.status);
});
});
});
}
When I use the search method by with dn name, it returns the correct object with its attributes (res.on('searchEntry', function(entry) part executed, because it can find the record in Ldap). But when I use client.search('dc=foo,dc=com', opts, function(err, res) with opt defined above, it always goes to branch 4: res.on('end', function(result) and never returns an error status of 0.
API documentation of Ldap.

This does not work for dc=foo,dc=com because that entry in the LDAP directory does not have the attribute Email and hence your filter does not match. The entry 'cn=x,ou=users,dc=foo,dc=com' in LDAP directory probably has this attribute which is why it works.

In the following way we can able to search user data
function searchUser() {
var opts = {
filter: '(objectClass=*)', //simple search
// filter: '(&(uid=2)(sn=John))',// and search
// filter: '(|(uid=2)(sn=John)(cn=Smith))', // or search
scope: 'sub',
attributes: ['sn']
};
client.search('ou=users,ou=system', opts, function (err, res) {
if (err) {
console.log("Error in search " + err)
} else {
res.on('searchEntry', function (entry) {
console.log('entry: ' + JSON.stringify(entry.object));
});
res.on('searchReference', function (referral) {
console.log('referral: ' + referral.uris.join());
});
res.on('error', function (err) {
console.error('error: ' + err.message);
});
res.on('end', function (result) {
console.log('status: ' + result.status);
});
}
});
}

Related

sending JSON from node js to jquery client but it cannot

I try to send JSON data to client. I test typeof dataJ and it return object at console dataJ is printed dataJ=[object Object],[object Object]. At client, it displays nothing and it alert XMLHttpRequest.responseText is null and textStatus is error messages and errorThrown is null. Since it doesn't say error, I don't know what does I do wrong.
server site:
app.post('/myaction', async function (req, res) {
async function next_func(req, res) {
var myJson = await show();
return myJson;
}
dataJ = await next_func(req, res);
console.log("dataJ=" + dataJ);
console.log(typeof dataJ)
res.status(200);
res.contentType('application/json');
res.send(dataJ);
});
app.listen(8081, function () {
console.log('Server running at http://127.0.0.1:8081/');
});
async function show() {
var con = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "aaaaaaaa",
database: "doto"
});
var sql = "select * from task_list";
resultsArray = [];
await new Promise((resolve, reject) => {
con.connect((err, connection) => {
if (err) return reject(err)
con.query(sql, (err, rows, fields) => {
if (err) return reject(err)
resolve(rows.forEach((row) => {
resultsArray.push({
detail: row.details,
status: row.status,
subject: row.subject
});
})
)
})
})
})
console.log("resultsArray" + resultsArray);
return resultsArray;
}
client site:
$.fn.ajaxShow = function (st) {
xhrct = $.ajax({
type: 'POST',,
data: {
status: st
},
url: 'http://127.0.0.1:8081/myaction',
success: function (data) {
alert("function");
$('#tb').empty();
if (data != null) {
var fotoData = $.parseJSON(data);
$(fotoData).each(function (i, obx) {
alert("fotoData");
$('#tb').append('<tr>')
.append('<td>' + obx.detail + '</td>')
.append('<td>' + obx.status + '</td>')
.append('<td>' + obx.subject + '</td>')
.append('</tr>');
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest: " + XMLHttpRequest.responseText);
alert("textStatus: " + textStatus);
alert("errorThrown: " + errorThrown);
}
});
}

NodeJS Async Database fetch server freezing

I have an application running on NodeJS(express + mongoose + jade).
I have a post-route /search (all routes are in a separate module) which should handle fetching data from mongo database and inserting it into jade template(in this case just printing th console):
router.post('/search', function (req,res) {
var componentsArray = null;
function getArray(){
console.log('Initializing...');
componentsArray = dataExchanger.search(req.body.select, req.body.selectType, req.body.searchField);
}
getArray(function () {
console.log('Documents returned.');
console.log('Printing array...');
console.log('Array: ' + componentsArray);
console.log('Array type: ' + typeof (componentsArray));
console.log('Rendering page...');
res.render('search_results');
});
});
Searching and fetching function implemented in a different module dataExchanger:
exports.search = function(select, type, data) {
console.log('Fetching documents...');
componentsModel.find({name: data}, function (err, docs) {
if(!err) {
console.log('Returning documents...');
return docs;
} else {
console.log('Can\'t return documents!');
throw err;
}
});
};
The problem is that when I am using a callback function for getArray(), the server just freezes at the moment of returning docs and stops responding.
What am I doing wrong?
Try to use async/await
router.post('/search', async (req,res) => {
let componentsArray;
try {
componentsArray = await dataExchanger.search(req.body.select, req.body.selectType, req.body.searchField);
} catch(e){
//If error in request and no data.
console.error('Error', e.message);
return res.render('error_message');
}
console.log('Documents returned.');
console.log('Printing array...');
console.log('Array: ' + componentsArray);
console.log('Array type: ' + typeof (componentsArray));
console.log('Rendering page...');
res.render('search_results');
});
And here is your dataExchanger
exports.search = function(select, type, data) {
console.log('Fetching documents...');
return new Promise((resolve, reject) => {
componentsModel.find({name: data}, function (err, docs) {
if(err) return reject(err);
resolve(docs);
});
})
};
Further reading: promises, async/await
router.post('/search', function (req,res) {
var componentsArray = null;
function getArray(cb){
console.log('Initializing...');
componentsArray = dataExchanger.search(req.body.select, req.body.selectType, req.body.searchField);
//Execute the callback
cb();
}
getArray(function () {
console.log('Documents returned.');
console.log('Printing array...');
console.log('Array: ' + componentsArray);
console.log('Array type: ' + typeof (componentsArray));
console.log('Rendering page...');
res.render('search_results');
});
});
Looks like your search method is async as well, so you will need to pass the callback down to that to get the desired result.

ldapjs client.search results to be accessed outside of the function

I am using ldapjs library in nodejs. I want to access the results of client.search outside of the function.
Here is my code
items = [];
client.search('cn=users,dc=test,dc=com', opts, function (err, res) {
if (err)
console.log(err);
res.on('searchEntry', function (entry) {
items.push(entry.object);
});
res.on('error', function (err) {
console.error('error: ' + err.message);
});
res.on('end', function (result) {
console.log('status: ' + result.status);
console.log(items[0]); **//Prints results correctly**
});
});
console.log(items[0]); **//Prints []**
I tried return items inside search. Still doesn't print. Any suggestions?
I encountered the same problem. Since res.on 'searchEntry' is an event emitter
, a simple solution that I use is to wrap the whole thing in a promise and return that.
let search = function( 'cn=users,dc=test,dc=com', opts ) {
return new Promise( ( resolve, reject ) => {
items = [];
client.search('cn=users,dc=test,dc=com', opts, function (err, res) {
if (err)
console.log(err);
reject( err )
res.on('searchEntry', function (entry) {
items.push(entry.object);
});
res.on('error', function (err) {
console.error('error: ' + err.message);
reject( error )
});
res.on('end', function (result) {
console.log('status: ' + result.status);
console.log(items[0]); **//Prints results correctly**
resolve( items )
});
});
}
};
Then you can do something like this:
let entries = await search( 'cn=users,dc=test,dc=com', opts );
You can use a wrapper function and a callback
function search(dn, options, callback){
// your code ...
res.on('end', function (result) {
callback(items);
}
});
and to call it like this
search(dn, options, function(err, result) {
//your result ...
console.log(result);
}

nested Async not executing as expected

I am new to node js and I am trying to use async module to eliminate the setTimeouts. Here I am facing a problem. It is not working as expected. It calls the second function even before the first function completes execution. I searched for answers and tried multiple ways. But it doesn't seem to work. It prints "Inside db insert in async series" even before the async.forEach finishes. Can anyone please check the code and tell me where I'm going wrong?
setTimeout(function() {
async.series([function(callback1) {
console.log("Inside async series");
try {
var msg = "";
var datas = [];
for (var i = 0; i < service_name.length; i++) {
console.log("Inside for loop service names");
var child = {
"space_guid": space_guid,
"name": service_name[i],
"service_plan_guid": service_plan_guid[i]
};
datas.push(child);
console.log("datas array===" + JSON.stringify(datas))
}
async.forEach(datas, function(data1, callback) {
console.log("Inside async task");
var data = JSON.stringify(data1);
console.log("data value===" + JSON.stringify(data));
var options = {
host: 'api.ng.bluemix.net',
path: '/v2/service_instances' +
'?accepts_incomplete=true',
method: 'POST',
headers: {
'Authorization': full_token_new
}
};
console.log("options is" + JSON.stringify(options));
var reqst = http.request(options, function(res) {
console.log("Sent for request");
res.setEncoding('utf8');
res.on('data', function(chunk) {
msg += chunk;
});
res.on('end', function() {
try {
console.log("message =======", msg);
console.log("-----------------------------------------");
msg = JSON.stringify(msg);
msg1 = JSON.parse(msg);
console.log("printing msg--" + msg1);
console.log("-----------------------------------------");
console.log("here i am", i);
console.log(service_name.length - 1);
callback();
} catch (err) {
console.log(err);
}
});
});
reqst.on('error', function(e) {
console.log(e);
});
reqst.write(data);
reqst.end();
}, function(err) {
console.log("for each error" + err);
});
callback1(null, null);
} catch (err) {
console.log(err);
}
},
function(callback1) {
console.log("Inside db insert in async series")
db_insert(service_name, solnName, full_token_new, uname, version);
callback1(null, null);
}
],
function(err, results) {
if (err) {
console.log("There's an error" + err);
} else {
console.log("result of async", results);
}
})
}, 3000)
You are mixing try...catch with asynchronous code, this is bad practice and almost impossible to do right.
Also, your error stem from the fact you are calling callback just after async.forEach, which don't finish, and go to the next step.
Also, what do you mean by "eliminate the timeout"? Your whole code is in it, you can remove it whenever you want.
'use strict';
async.series([
(callback) => {
let msg = "",
datas = [],
i = 0;
while(i < service_name.length) {
let child = {
"space_guid": space_guid,
"name": service_name[i],
"service_plan_guid": service_plan_guid[i]
};
datas.push(child);
i = i + 1;
}
async.forEach(datas, (data1, callback) => {
let data = JSON.stringify(data1),
options = {
host: 'api.ng.bluemix.net',
path: '/v2/service_instances?accepts_incomplete=true',
method: 'POST',
headers: {
'Authorization': full_token_new
}
},
reqst = http.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', (chunk) => {
msg += chunk;
});
res.on('end', () => {
msg = JSON.stringify(msg);
msg1 = JSON.parse(msg);
callback();
});
});
reqst.on('error', (error) => {
callback(error);
});
reqst.write(data);
reqst.end();
}, (error) => {
callback(error);
});
},
(callback) => {
db_insert(service_name, solnName, full_token_new, uname, version);
callback();
}
],
(error, results) => {
if (error) {
console.log("There's an error" + error);
} else {
console.log("result of async", results);
}
});
Since this smell heavily like a plssendzecode question, I've removed every console.log and gone ES6 to make sure you will not be able to use it as such and need to read the change I made.
I simplify code a little.
datas and processData aren't good names.
setTimeout(onTimer, 3000);
function onTimer() {
var datas = service_name.map(function(name, i) {
return {
space_guid: space_guid,
name: name,
service_plan_guid: service_plan_guid[i]
}
});
function processData(data, callback) {
var options = {
host: 'api.ng.bluemix.net',
path: '/v2/service_instances?accepts_incomplete=true',
method: 'POST',
headers: {
'Authorization': full_token_new
}
};
var reqst = http.request(options, function(res) {
var msg = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
msg += chunk;
});
res.on('end', function() {
try {
msg = JSON.parse(msg);
callback(null, msg);
} catch (err) {
callback(err);
}
});
});
reqst.on('error', callback);
reqst.write(JSON.stringify(data));
reqst.end();
}
async.map(datas, processData, function(err, results) {
if (err);
return console.log(err);
// process msg of each request db_insert(...);
});
};

MongoDB Error 2nd time calling function: TypeError: Cannot call method 'collection' of null

I'm using the following function to add an array of documents to a MongoDB collection.
function recipesToDB(recipes) {
mongo.connect(uristring, function (err, db) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Succeeded connected to: ' + uristring);
db.createCollection('recipes', function(err, collection) {});
var collection = db.collection('recipes');
collection.insert(recipes, {continueOnError: true}, function(err, result) {
if (err) {
console.log('ERROR:' + err);
} else {
console.log('success');
}
});
}
});
}
The above function works to add my recipes array to the MongoDB recipes collection. But, when I call the function twice(30 seconds apart), it fails the second time with the following error:
TypeError: Cannot call method 'collection' of null
If mongodb has mongod.lock,this error should come,
This is the way to remove mongod.lock: sudo rm mongod.lock,after you must restart the mongodb,that is sudo service mongod restart
This is likely because connecting a second time isn't working. Instead, connect once in a more global location and then access the global connection from this function.
var mongoDb;
function connectToDb(done){
mongo.connect(uristring, function (err, db) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Succeeded connected to: ' + uristring);
mongoDb = db;
done();
}
}
}
connectToDb(function(){
recipesToDB(yourRecipesObject);
});
function recipesToDB(recipes) {
mongoDb.createCollection('recipes', function(err, collection) {});
var collection = mongoDb.collection('recipes');
collection.insert(recipes, {continueOnError: true}, function(err, result) {
if (err) {
console.log('ERROR:' + err);
} else {
console.log('success');
}
});
}
});
}

Categories

Resources