Search in ldapjs - javascript

I am trying to use the search method of Ldap.js in my node.js code. Here is my code for the client side. It adds successfully a user, but searching for the newly added user does not yield any results. (The ldap server is running in a docker container from https://github.com/osixia/docker-openldap)
var ldap = require("ldapjs");
var assert = require("assert");
var client = ldap.createClient({
url: "ldap://localhost:389",
});
client.bind("cn=admin,dc=example,dc=org", "admin", function (err) {
assert.ifError(err);
let newUser = {
cn: "userId7",
userPassword: "password",
objectClass: "person",
sn: "efub",
};
// Here i successfully add this user "userId7"
client.add(
"cn=userId7,dc=example,dc=org",
newUser,
(err, response) => {
if (err) return console.log(err);
return response;
}
);
var options = {
filter: "(objectClass=*)",
scope: "sub",
};
// Now the search, it runs without error, but does never receive a searchEntry
client.search(
"cn=userId7,dc=example,dc=org",
options,
function (error, search) {
console.log("Searching.....");
client.on("searchEntry", function (entry) {
console.log("I found a result in searchEntry");
});
client.on("error", function (error) {
console.error("error: " + error.message);
});
client.unbind(function (error) {
if (error) {
console.log(error.message);
} else {
console.log("client disconnected");
}
});
}
);
});
client.on('error', function (err) {
if (err.syscall == "connect") {
console.log(err);
}
});
Also, if it helps, this is how the newly added user looks like when i display all users from ldap by running docker exec my-openldap-container ldapsearch -x -H ldap://localhost:389 -b dc=example,dc=org -D "cn=admin,dc=example,dc=org" -w admin
# userId7, example.org
dn: cn=userId7,dc=example,dc=org
cn: userId7
userPassword:: cGFzc3dvcmQ=
objectClass: person
sn: efub
Update: I can successfully search for the user "userId7" with the shell command: docker exec ldap-service ldapsearch -LLL -x -D "cn=admin,dc=example,dc=org" -w "admin" -b "cn=userId7,dc=example,dc=org" "(objectclass=*)". How can i make ldapJS also run this search successfully?
Update 2: I can also successfully search by using the frontend "phpLDAPadmin" as seen in the screenshots below:

So i solved it. The correct client.search code is:
client.search(
"cn=userId7,dc=example,dc=org",
options,
function (error, res) {
console.log("Searching.....");
res.on("searchEntry", function (entry) {
console.log("I found a result in searchEntry", JSON.stringify(entry.object));
});
res.on("error", function (error) {
console.error("error: " + error.message);
});
client.unbind(function (error) {
if (error) {
console.log(error.message);
} else {
console.log("client disconnected");
}
});
}
);
Inside function (error, res) { I listened for the events via client.on("searchEntry", instead of res.on("searchEntry", therefore missing the events from the search results. The root cause was a classic copy and paste error and changing the variable while misunderstanding the origin of the event.

Related

Displaying output message only on success within NodeJS

var abc = require("expect-telnet");
abc("linux123:2031",
console.log("Telnet working"),
function(err) {
if (err) console.error(err);
});
It is displaying the message Telnet working in all scenarios.
I want it to be displayed only when we have successful telnet connection.
From the looks of your code you don't have to authenticate your telnet since I don't see you sending a username or password. If that's not the case you'll need to send your authentication.
You'll want to change it to something like the code shown below.
Remove the lines for authentication if not needed.
var abc = require("expect-telnet");
abc("linux123:2031", [
{expect: "Username", send: "username\r"},
{expect: "Password", send: "password\r"},
{expect: "#" , send: "command\r" },
{expect: "#" , out: function(output) {
console.log("telnet working");
}, send: "status\r"}
], function(err) {
if (err) console.error(err);
});
Give this a try when no authentication is needed:
This code waits for telnet to respond with the '#' character once connected. Once it sees that, you should get the console.log info.
I hope this helps.
var abc = require("expect-telnet");
abc("linux123:2031", [
{expect: "#" , out: function(output) {
console.log("telnet working");
}, send: "status\r"}
], function(err) {
if (err) console.error(err);
});
Try this one.
var abc = require("expect-telnet");
abc("linux123:2031",function(err,data) {
if (err) {
console.error(err);
}else {
console.log("Telnet working")
}
});

MongoClient not returning data in cucumberjs test

I've taken this apart several different ways. The find happens after the remove, and the find never finds anything. If I comment out the this.accounts.remove... the find works. If I leave the remove line in there it doesn't. My understanding of cucumberjs, mongo client and node indicates that the find should work.
I've even tried moving the remove/find sequence into its own file, and it works there. It seems to be only when I'm running it in cucumber that the sequence fails. I suspect because of the way of cucumber loads the files, but I'm not sure.
Can someone help me figure out how to get this working?
World.js:
var db = new Db('FlashCards', new Server('localhost', 27017));
db.open(function(err, opened) {
if (err) {
console.log("error opening: ", err);
done(err);
}
db = opened;
});
var {
defineSupportCode
} = require('cucumber');
function CustomWorld() {
this.db = db;
this.accounts = db.collection('accounts');
hooks.js:
Before(function(result, done) {
//comment this out, and leave a done(), it works!!!!
this.accounts.remove(function(error, result){
if( error) {
console.log("Error cleaning the database: ", error);
done(error);
}
done();
})
});
user_steps.js:
Then('I will be registered', function(done) {
let world = this;
this.accounts.find({
username: world.user.username
}).toArray(
function(err, accounts) {
if (err) {
console.log("Error retrieveing data: ", err);
done(err);
}
console.log("Accounts found: ", accounts);
expect(accounts).to.be.ok;
expect(accounts.length).to.be.equal(1);
done();
});
});
Inovcation:
cucumber-js --compiler es6:babel-core/register
You are missing the item to be removed in the remove method. I am assuming the item to be removed is
this.accounts.remove(function(error, result){
You are missing one parameter to remove method. The parameter is query to remove. I am assuming, the remove query is {username: world.user.username}
var qry={username: world.user.username};
Please try with the following:
Before(function(result, done) { //comment this out, and leave a done(), it works!!!!
var qry={username: world.user.username};
this.accounts.remove(qry, function(error, result){
if( error) {
console.log("Error cleaning the database: ", error);
done(error);
}
done();
}) });

Cannot insert to collection from NPM using Meteor 1.3

I am using the imap-simple NPM package to check emails, and I am having trouble getting the insert to work properly.
I have already read through this page: https://guide.meteor.com/using-npm-packages.html#async-callbacks - and I have tried the suggestions but none of them are working!
I've also simplified the code a bit just to try to get it working, but still have no luck.
The problem should be very easy to reproduce - meteor npm install imap-simple, throw the above code on the server, add some email credentials, and call the method.
Here is my code:
var imaps = require('imap-simple');
var config = {
imap: {
user: '<removed>',
password: '<removed>',
host: 'imap.gmail.com',
port: 993,
tls: true,
authTimeout: 3000
}
};
Meteor.methods({
api_connectEmail: function () {
console.log('Received call to connect email');
imaps.connect(config).then(function (connection) {
return connection.openBox('INBOX').then(function () {
var searchCriteria = [
'UNSEEN'
];
var fetchOptions = {
bodies: ['HEADER', 'TEXT'],
markSeen: true
};
return connection.search(searchCriteria, fetchOptions).then(function (results) {
results.map(function (res) {
var subject = res.parts.filter(function (part) {return part.which === 'HEADER';})[0].body.subject[0];
console.log("Subject: " + subject);
// insert
var attributes = {
subject: subject
};
console.log("Attempting to insert to collection...");
var newData = TempEmailCollection.insert(attributes);
console.log("New Database Entry ID: " + newData);
});
});
});
})
}
});
The console.log with the subject is working. The insert is not working. No error, no console.log post insert, nothing.
I've tried both strategies recommended in the guide, neither work.
The problem is that you are calling a Meteor function inside asynchronously called Promise handlers.
However, all Meteor functions that are called on the server have to run in a fiber.
Meteor actually throws an error in this case but you are ignoring it because you haven't specified catch functions for the Promises.
Consider the following simplified example (it just connects to the server and tries to insert a new document):
import { Meteor } from 'meteor/meteor';
import imaps from 'imap-simple';
const Storage = new Mongo.Collection('storage');
const config = {
imap: {
…
}
};
Meteor.methods({
connect() {
console.log('Method called');
imaps.connect(config).then(function(connection) {
console.log('Connected');
Storage.insert({
value: 'success'
});
console.log('Document inserted');
})
.catch(function(err) {
console.error(err);
});
}
});
The following message will arrive in the catch function:
[Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.]
You could do something like this to wrap the insert call:
Meteor.methods({
connect() {
console.log('Method called');
const insert = Meteor.bindEnvironment(function() {
Storage.insert({
value: 'success'
});
});
imaps.connect(config).then(function(connection) {
console.log('Connected');
insert();
console.log('Document inserted');
})
.catch(function(err) {
console.error(err);
});
}
});
Then the document will be inserted as expected.

Call Magento SOAP inside Meteor method invoked by the client

I'm using zardak:soap package in Meteor to connect with Magento SOAP v2 API. I've created a file inside the 'server' folder where I create a soap connection on Meteor.startup. Then I run a ticker that invokes random soap method every 30sec just to keep the connection up.
let soapConnection;
Meteor.startup(() => {
soapConnection = createAPIConnection('http://magento.site.com/api/v2_soap/?wsdl=1', {username: 'user', apiKey: 'password'});
});
function createAPIConnection(url, credentials) {
try {
let client = Soap.createClient(url);
let loginResult = client.login(credentials);
let sessionId = loginResult.loginReturn.$value;
return {
conn: client,
sessionId: sessionId
};
} catch (e) {
if (e.error === 'soap-creation') {
console.log('SOAP Client creation failed');
}
return null;
}
}
function tick() {
try {
soapConnection.conn.catalogCategoryInfo({
sessionId: soapConnection.sessionId,
categoryId: 1
}, (err, result) => { });
} catch (e) { }
}
Then I have a Meteor method that is called from the client. When it is called, the soap method call fails and I'm getting a 'soap error' message in console.
Meteor.methods({
'createMagentoCustomer'(customer) {
try {
soapConnection.conn.customerCustomerCreate({
sessionId: soapConnection.sessionId,
customerData: customer
}, (err, res) => {
if (err)
console.log('soap error');
else
console.log(res);
});
} catch (e) {
console.log('SOAP Method <customerCustomerCreate> call failed');
}
},
});
So, the ticker works well with no problems, but when I try to call soap via Meteor method, it fails. Notice that the soapConnection method is not null and I do receive error in the soap method callback.
Any suggestions?
Meteor version 1.3.4.1

Mocha/Node.js/PostgreSQL integration testing

I have been trying to get this to work for days. I've looked around the internets and on StackOverflow. There are examples of how to test APIs using MongoDB and how to write Mocha tests that execute PSQL commands. That's not what I want.
I created a wrapper for pg, called db.js from the instructions in this SO question (note my comments in the calls to console.log():
pg = require("pg");
config = require("./../config.js");
module.exports = {
query: function(text, values, cb) {
console.log("I get to this in Mocha");
pg.connect(config.connectionString, function(err, client, done) {
console.log("I never get here");
if (err) return console.error("error connecting to postgres: ", err);
client.query(text, values, function(err, result) {
console.log("I most certainly never get here");
done();
cb(err, result);
})
});
}
}
With that, I can do the following:
$ node
$ var db = require ("./path/to/db.js");
$ db.query("insert into sometable(id, value) values(1, \"blah\")", {}, function (err, result) {
if (err) { console.error ("db errored out man"); }
console.log("no error...");
console.log(result);
});
Believe it or not, that works without a hitch!
What I can't do is the same thing in a mocha test (i.e., db.spec.js):
var db = require("./../../../Data/db.js");
// These tests assume you have run the scripts in the -SQL repo
describe("module: db", function() {
it("provides a wrapper for the execution of queries", function () {
db.query("insert into employer.profile \
(id, returncustomer, receiveupdates, name, email, password, active) \
values (4, true, true, 'someNameLol', 'ce#spam.org', 'change_me', true)", {},
function (err, stdout, stderr) {
console.log(err || "");
console.log(stdout || "");
console.log(stderr || "");
}
);
});
});
Help! I want to be able to write integration tests using my database connection. Are there components I'm missing? Required libraries?
This is all hand-rolled, I'm not using an IDE, because I want to understand how it's supposed to work by myself.
Thanks in advance.
You need to include the done parameter, and call it at the end of your test.
describe("module: db", function() {
it("provides a wrapper for the execution of queries", function (done) {
db.query("insert into employer.profile \
(id, returncustomer, receiveupdates, name, email, password, active) \
values (4, true, true, 'someNameLol', 'ce#spam.org', 'change_me', true)", {},
function (err, stdout, stderr) {
console.log(err || "");
console.log(stdout || "");
console.log(stderr || "");
done();
}
);
});
});

Categories

Resources