Mongoose throwing `Authentication failed` - node.js

I am using Mongoose Ver:4.3
I am able to connect to mongoDb using Studio3T mongo client.
But getting an authentication error when trying to connect using Mongoose within NodeJs.
My code looks as below:
const sslOptions = {
server: {
sslValidate: false,
ssl: true,
sslCert: certFileBuf,
sslKey: certFileBuf,
checkServerIdentity: false,
sslPass: 'mysslPass',
},
user: 'myUser',
pass: 'myPass'
};
connName = mongoose.createConnection("mongodb://server.com:27017/db1?tls=true&authSource=db1", sslOptions);
The above throwing an error:
mongodb\node_modules\mongoose\node_modules\mongodb\lib\utils.js:98
process.nextTick(function() { throw err; });
^
Error [MongoError]: Authentication failed.

set username and password in url
connName = mongoose.createConnection("mongodb://myUser:myPass#server.com:27017/db1?tls=true&authSource=db1", {
sslValidate: false,
ssl: true,
sslCert: certFileBuf,
sslKey: certFileBuf,
checkServerIdentity: false,
sslPass: 'mysslPass',
});

Related

connection error while connecting to AWS DocumentDB through lambda

getting the following error while connecting to AWS DocumentDB from node.js through lambda
{"errorMessage":"ENOENT: no such file or directory, open
'rds-combined-ca-bundle.pem'","errorType":"Error","stackTrace":["Object.fs.openSync (fs.js:646:18)","Object.fs.readFileSync
(fs.js:551:33)","Object.
(/var/task/base/mongoose.base.js:8:13)","Module._compile
(module.js:652:30)","Object.Module._extensions..js
(module.js:663:10)","Module.load (module.js:565:32)","tryModuleLoad
(module.js:505:12)","Function.Module._load
(module.js:497:3)","Module.require (module.js:596:17)","require
(internal/module.js:11:18)","Object.
(/var/task/library/mongoLib/room.lib.js:1:84)","Module._compile
(module.js:652:30)","Object.Module._extensions..js
(module.js:663:10)","Module.load (module.js:565:32)","tryModuleLoad
(module.js:505:12)","Function.Module._load (module.js:497:3)"]}
here is my node js file in lambda
var ca = fs.readFileSync(path.join('./','rds-combined-ca-bundle.pem'));
var options = {
keepAlive: true,
poolSize: 30,
socketTimeoutMS: 30000,
autoReconnect: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 500,
useCreateIndex: true,
auth: {authdb: 'admin'},
useFindAndModify: false,
sslValidate: true,
sslCA:ca,
useNewUrlParser: true
}
var uri = 'mongodb://'+globalData.getConfigurationSettings("documentdb_username")+':'+globalData.getConfigurationSettings("documentdb_password")+'#'+globalData.getConfigurationSettings("documentdb_server")+':'+globalData.getConfigurationSettings("documentdb_port")+'/'+globalData.getConfigurationSettings("documentdb_db_name")+'?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred';
mongoose.connect(uri, options)
.then(() => console.log('Connection to DB successful'))
.catch((err) => console.error(err,'Error'));
It should be:
var ca = fs.readFileSync(path.join(__dirname + '/rds-combined-ca-bundle.pem'));
Or you can define :
import caBundle from "./rds-combined-ca-bundle.pem";
var options = {
............
sslCA:caBundle,
The error comes from ENOENT: no such file or directory, open 'rds-combined-ca-bundle.pem
it seems that file doesn't exist there. can you check the path? did you embed the cert with lambda?

Tunnel-SSH doesn't connect to server successful in node application

I'm trying to connect to a cloud server that runs my MongoDB from my local machine. I'm using tunnel-ssh within the Node.js application I'm creating, however, I seem to have multiple problems and I don't fully understand what's going on.
Problems
I'm not 100% sure I'm successfully connecting to the server. There's no error, however, when I console.log(server) it says _connections: 0,. see full log below.
If I am connecting and then I try to run the getDataFromMongoDB function it returns the error, EADDRINUSE: address already in use 127.0.0.1:27000.
I've been trying to wrap my head around this all day and I'm not getting anywhere. Please help.
Error 1 - Is server connecting
Server {
_events:
[Object: null prototype] { connection: [Function], close: [Function] },
_eventsCount: 2,
_maxListeners: undefined,
_connections: 0,
_handle:
TCP {
reading: false,
onread: null,
onconnection: [Function: onconnection],
[Symbol(owner)]: [Circular] },
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: false,
pauseOnConnect: false,
_connectionKey: '4:127.0.0.1:27017',
[Symbol(asyncId)]: 7 }
Code
var config = {
username: "root",
Password: "password on the server",
host: "server IP address",
port: 22,
dstHost: "127.0.0.1",
dstPort: 27017,
localHost: "127.0.0.1",
localPort: 27000
};
var tnl = tunnel(config, function(error, tnl) {
if (error) {
console.log(error);
}
// yourClient.connect();
// yourClient.disconnect();
console.log(tnl);
getDataFromMongoDB();
});
async function getDataFromMongoDB(page) {
const MongoClient = require("mongodb").MongoClient;
const uri = "mongodb://USRNAME:PASSWORD_FOR_MONGDB_DATABASE#localhost:27017";
const client2 = new MongoClient(uri, { useNewUrlParser: true });
const client = await connectToMongodb(client2);
const collection = client.db("my_database_name").collection("jobs");
const jobs = await collection.find().toArray();
console.log("jobs", jobs);
}
function connectToMongodb(client) {
return new Promise((resolve, reject) => {
client.connect(function(err) {
console.log("connected", err);
return resolve(client);
});
});
}

sails.js session data not saved into db

I might be doing something wrong. Please guide me in right direction.
I am trying to implement sails session feature with 'connect-mongo'. I did the implementation same as explained in the docs Sails session mongo. After successful authentication I am trying to save session data into mongoDb. But in my case it is not saved in mongo collection and collection always remains empty.
My configurations in session.js
url: 'mongodb+srv://username:password#cluster0-tkjwp.mongodb.net/mydbname?retryWrites=true',
collection: 'sessions',
auto_reconnect: false,
ssl: false,
stringify: true,
cookie: {
secure: false,
maxAge: 24 * 60 * 60 * 1000
}
and how I am trying to save.
if(user.length && user[0].id){
// save in DB
req.session.authenticated = true;
req.session.authinfo = user[0];
req.session.save(function(err) {
console.log(req.session);
return res.json({
status: 1,
msg: 'Successfull.'
});
})
}else{
return res.send({
status: 0,
msg: 'Invalid'
});
}
Also I am not getting any error
Its working now. Only thing I missed the adapter option. But now I am using it with mysql. Below I posting my working code with MySql.
In session.js
adapter: 'express-mysql-session',
host: 'localhost',
port: 3306,
user: 'root',
password: 'xxxxxxxxx',
database: 'xyz',
ssl: false,
stringify: true,
cookie: {
maxAge: 24 * 60 * 60 * 1000
},

mongoose readPreference in options object?

right now i am connecting to mongodb like this:
uri = 'mongodb://mongodomain1.com:1234,mongodomain2.com:1234/mydb?replicaSet=replicasetname&readPreference=secondaryPreferred';
opts = {
user: 'myuser',
pass: 'mypass',
server: {
auto_reconnect: true,
socketOptions: {
keepAlive: 120
}
},
replset: {
socketOptions: {
keepAlive: 120
}
}
};
mongoose.connect(uri, opts);
now i would like to bring the readPreference url parameter into the options object to be consitent and have all connection variables in the options.
i am struggling to find documentation on how to define the readPreference in the object.
same thing the replicaSet parameter in the url. is that equivalent to the rs_name
is there anything else i could/should improve in the way i am connecting to mongodb?

Can't connect to heroku postgresql database from local node app with sequelize

I'm trying to connect to a Heroku postgresql database from a local nodejs app with Sequelize. I followed this two guides an everything is working perfectly fine on the heroky server side, but my node app won't connect to heroku when I run it locally on my Mac.
http://sequelizejs.com/articles/heroku
https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku
Here is how I start the local app:
DATABASE_URL=$(heroku config:get DATABASE_URL) nodemon
Gets me:
Sequelize: Unable to connect to the database:
But I get the correct URL by doing this:
echo $(heroku config:get DATABASE_URL)
And those commands are working fine:
heroku pg:psql
psql $(heroku config:get DATABASE_URL)
Here is my nodejs code :
var match = process.env.DATABASE_URL.match(/postgres:\/\/([^:]+):([^#]+)#([^:]+):(\d+)\/(.+)/)
sequelize = new Sequelize(match[5], match[1], match[2], {
dialect: 'postgres',
protocol: 'postgres',
port: match[4],
host: match[3],
logging: false
})
sequelize
.authenticate()
.complete(function(err) {
if (!!err) {
log('Sequelize: Unable to connect to the database:', err);
} else {
http.listen(process.env.PORT || config.server.port, function(){
log('Web server listening on port '+process.env.PORT || config.server.port);
});
}
});
I tried to add native: true to the sequelize options, but then I get:
/Users/clement/Projets/XMM/node_modules/sequelize/lib/sequelize.js:188
throw new Error('The dialect ' + this.getDialect() + ' is not supported.
^
Error: The dialect postgres is not supported. (Error: Please install postgres package manually)
at new module.exports.Sequelize (/Users/clement/Projets/XMM/node_modules/sequelize/lib/sequelize.js:188:13)
at Object.<anonymous> (/Users/clement/Projets/XMM/server.js:17:14)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
Even after doing:
npm install pg
npm install -g pg
brew install postgresql
This is working by the way:
var pg = require('pg');
pg.connect(process.env.DATABASE_URL+'?ssl=true', function(err, client, done) {
if (err) return console.log(err);
client.query('SELECT * FROM pg_catalog.pg_tables', function(err, result) {
done();
if(err) return console.error(err);
console.log(result.rows);
});
});
But i'd rather use Sequelize.
OK, found the answer by browsing sequelize source code :
https://github.com/sequelize/sequelize/blob/master/lib/dialects/postgres/connection-manager.js#L39
To activate SSL for PG connections you don't need native: true or ssl: true but dialectOptions.ssl: true so the following did finally work:
sequelize = new Sequelize(process.env.DATABASE_URL, {
dialect: 'postgres',
protocol: 'postgres',
dialectOptions: {
ssl: true
}
});
To work around the self signed certificate bug on node-postgres version 8 mentioned at SequelizeConnectionError: self signed certificate you can use instead:
sequelize = new Sequelize(process.env.DATABASE_URL, {
dialect: 'postgres',
protocol: 'postgres',
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false
}
}
});
You no longer need to parse the DATABASE_URL env variable, there is a Sequelize constructor which accepts the connection URL:
sequelize = new Sequelize(process.env.DATABASE_URL, {
dialect: 'postgres',
protocol: 'postgres',
dialectOptions: {
ssl: true
}
});
One needs to add dialectOptions under ssl
"development": {
"username": process.env.DB_USERNAME,
"password": process.env.DB_PASSWORD,
"database": process.env.DB_NAME,
"host": process.env.DB_HOST,
"dialect": process.env.DB_DIALECT,
"dialectOptions": {
ssl: {
require: true,
rejectUnauthorized: false
}
}
},
Source is as per official sequelize github
You need just these 2 things
Append ?sslmode=require to your POSTGRES DATABASE URI
Make sure you have rejectUnauthorized: false in your dialectOptions
const sequelize = new Sequelize(`${process.env.DATABASE_URI}?sslmode=require`, {
url: process.env.DATABASE_URI,
dialect: 'postgres',
logging: false,
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false, // very important
}
}
}
For More Information, here is an Article on Heroku DevCenter about it
https://devcenter.heroku.com/articles/heroku-postgresql#heroku-postgres-ssl
I had the same problem and for these cases you can consider the following documentation example on how to connect the heroku database:
https://sequelize.readthedocs.io/en/1.7.0/articles/heroku/
At the end i did implement a code like :
const sequelize = new Sequelize(
process.env.DATABASE_NAME_DB_CONFIG,
process.env.USER_NAME_DB_CONFIG,
process.env.USER_PASSWORD_DB_CONFIG,
{
host: process.env.HOST_DB_CONFIG,
dialect: process.env.DIALECT_DB_CONFIG,
protocol: process.env.PROTOCOL_DB_CONFIG,
logging: true,
dialectOptions: {
ssl: true
},
pool: {
max: 5,
min: 0,
idle: 10000
}
}
);
where you need to take account the dialectOptions with ssl: true.
That's all you need to know.

Resources