Mongoose keeps trying to authenticate with wrong admin db even though it is specified - mongodb

The initial connection to the database seems to authenticate fine with this:
mongoose.connect('mongodb://user:pass#localhost/traderdb/?authSource=admin', {
auth: {
authdb: "admin"
}
}, function(e) {
//other things
});
After that however, when I try to create a new session and authenticate the user everything crashes and in the mongo logs I can see that the application tried to authenticate with mongodb using the traderdb database and not the admin database, even though I have authSource set correctly and it connects fine the first time with the same URI.
This is where I initialize the session store. This is placed inside the callback of the mongoose.connect call.
app.use(session({
secret: 'secrettexthere',
saveUninitialized: true,
resave: true,
store: new MongoStore({
url: 'mongodb://user:pass#localhost/traderdb/?authSource=admin',
db: 'traderdb',
collection: 'sessions',
auto_reconnect: true
})
}));
Nothing fails on application startup, and the mongo logs confirm that a connection was successfully made and authenticated with the admin database. After that however, when I try to actually use the session store the application crashes with the error Error: Error setting TTL index on collection : sessions. And in the mongo server logs I can see that my application tried connecting and authenticating with traderdb instead of admin as the authentication source.

Related

(PostgreSQL) 12.7 (Ubuntu 12.7-0ubuntu0.20.04.1) can't connect to the database?

This is on WSl 2 following the instructions from the official documentation
I created a simple postgresql and I try to connect to it like so:
const Sequelize = require("sequelize");
const sequelize = new Sequelize('postgres://postgres:w#localhost:5432/messenger', {
logging: false,
dialect: 'postgre'
});
async function test(){
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
test();
This will tell me if the connection was successful or not, but for some reason, I keep getting this error. The URI string seems correct, the only user is the default created Postgres where I changed the password to be "w" for testing purposes.
Not sure what that 12/main part is about but the server is online so I am really not sure what the problem is.
Either you specified the wrong password for the database user "postgres", or your server isn't configured to allow password authentication on localhost. You can see this link: https://www.postgresql.org/docs/current/auth-methods.html for more information on the authentication methods postgresql supports, or this one: https://www.postgresql.org/docs/current/auth-pg-hba-conf.html for information on how to set up authentication on your postgresql server.

Unable to create connection to MongoDB server in `mongod` shell

My MongoDB was working fine but at some point, I was facing issues to connect my express server with the DB. when I start the DB using mongod it shows me 2020-05-21T14:36:41.819+0600 I NETWORK [initandlisten] waiting for connections on port 27017 which seems like a normal "running" entry. Then I run my express server where I connect the DB like this:
...
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/db_name';
const connect = mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});
connect.then(
(db) => {
console.log('Connected correctly to server');
},
(err) => {
console.log(err);
}
);
...
which log Connected correctly to server but when I see the mongod running shell then there still the message which showed that it still waiting for the connection. And the most surprising issue is I can perform database related work in my express server. when I check the document using mongo, I see they correctly added to the database. I can't understand then why mongod behave like this. here is the full log of the mongod shell.
Update:
I forgot to add one important piece of information which is whenever I start my MongoDB server using mongod, in the C:\data\db directory there generate a new mongod.lock file. I tried to delete it and restart my server but eventually it generates again.

VOMongoRepository fails to connect to MongoDB replicaset with user credentials (Pharo/Voyage)

I am trying to save a root Object (MyDocument) into a mongoDB with authentication enabled and a ReplicaSet consisting of 3 Nodes (as inserted into mongoUrls)
With this call:
(VOMongoRepository
mongoUrls: {'127.0.0.1:27017' . '127.0.0.1:27018' . '127.0.0.1:27019'}
database: 'myDB'
username: 'myUser'
password: 'myPass') enableReplication
I receive a VOMongoConnectionError without any deeper information.
Trying the same with this:
VOMongoRepository
mongoUrls: {'myUser:myPass#127.0.0.1:27017/?replicaSet=myRepl' }
database: 'myDB'
I then receive a VOMongoError "not authorized for Query on myDB.MyDocument"
The credentials are double checked with mongo client and Compass, also the read/write permissions (actually the role is dbOwner).
Interestingly my testDocumentLifeCycle is able to create the object and to send a message to save, that returns without signaling an error, although it does not create the document in MongoDB. But the selectOne: is then returning the VOMongoError:
| doc |
MyDocument new
identity: 'me#there.com';
save.
user := MyDocument selectOne: [ :each | each identity = 'me#there.com'].
Just to mention: the above test for MyDocument class did work with a standalone mongod without authentication enabled. The only thing changed is the repository.
So what am I doing wrong?
Actually there is a bug in the replicaSet part of VoyageMongo. It is not using the credentials provided. It has been posted at https://github.com/pharo-nosql/voyage/issues/104

Sails.js - Authorisation issues with remote MongoDB on mLab but working fine locally

Recently, I took over a Sails.js application created for our company by a small team of web developers. They provided me with the source and a database dump. Now, my task is to get it up and running on Heroku. While everything is working okay when I run the app locally, with the remote connection there is an error on startup that says:
MongoError: not authorized on heroku_gbntc8sf to execute command { createIndexes: "agendaJobs", indexes: [ { key: { name: 1, priority: -1, lockedAt: 1, nextRunAt: 1, disabled: 1 }, name: "findAndLockNextJobIndex1" }, { key: { name: 1, lockedAt: 1, priority: -1, nextRunAt: 1, disabled: 1 }, name: "findAndLockNextJobIndex2" } ] }
at Function.MongoError.create ([ROOT_DIR]/node_modules/mongodb-core/lib/error.js:31:11)
at [ROOT_DIR]/node_modules/mongodb-core/lib/topologies/server.js:793:66
at Callbacks.emit ([ROOT_DIR]/node_modules/mongodb-core/lib/topologies/server.js:94:3)
at null.messageHandler ([ROOT_DIR]/node_modules/mongodb-core/lib/topologies/server.js:235:23)
at Socket.<anonymous> ([ROOT_DIR]/node_modules/mongodb-core/lib/connection/connection.js:259:22)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:146:16)
at Socket.Readable.push (_stream_readable.js:110:10)
at TCP.onread (net.js:523:20)
Here's a quick checklist of what I've done already:
checked the build log on Heroku - no errors or warnings;
set up mLab Heroku add-on, exported the database, done some manual checks from the mLab dashboard - everything looks okay;
logged in to the database remotely from the mongo command and a mongo:// URL, ran a few simple queries, and obtained information on the database user privileges;
created an identical user (with the heroku_gbntc8sf username, same password, same role, etc.) in the local database.
Here's what the connection configuration looks like:
// config/connections.js
module.exports.connections = {
mongodb: {
adapter: 'sails-mongo',
user: 'heroku_gbntc8sf',
password: [HIDDEN],
host: 'ds159387.mlab.com',
port: 59387,
database: 'heroku_gbntc8sf'
},
// ...
}
// config/env/development.js
module.exports = {
models: {
connection: 'mongodb'
},
// ...
}
// config/env/production.js
module.exports = {
models: {
connection: 'mongodb'
},
// ...
}
At the moment I'm running the server locally, trying to connect to the remote database, to eliminate as many variables as possible. Like I mentioned above, when I set host to '127.0.0.1' and port to 27017, everything works okay. The heroku_gbntc8sf user has basic readWrite permissions in both databases (local and remote). In fact, those two databases are pretty much identical, as far as I know. And yet...
I've read a sizeable chunk of the Sails.js documentation, as well as, the documentation on the sails-mongo adapter. I've searched for similar questions, but I couldn't find anything relevant. I've tried many different things, including a couple of different ways to configure the database connection, but that error is always there.
The reason why I'm posting to StackOverflow is that I cannot rely on the support from the original authors of the app at the moment. Also, I'm new to Sails.js, so I might be doing something wrong without even knowing. I was hoping that I could get away with treating the app as a 'black box' (or like a generic Node application), since my job is only to start the app on Heroku.
I've successfully used mLab in a Sails project recently, but I've used the Mongo URL string format, for example...
mongodbServer: {
adapter: 'sails-mongo',
url : "mongodb://dandanknight:som3P455w0rd#ds044979.mlab.com:44979/databasename"
}
Not sure if it helps, but can't hurt to try! It's also the only way I've successfully got a replicaSet working in Sails incidentally.
It's confusing, but I read the sails-mongo docs as "URL is the way forward, and passing an object is legacy usage" (here)

Sailsjs session error

Keep getting this warning & error when I lift my app and can't figure it out. Hoping someone has an idea about this:
warn: Socket disconnected, but session could not be loaded to pass to configured disconnect handler: sails.config.sockets.onDisconnect(). Will pass a fake, empty session as argument to lifecycle callback. Details:
Error: Session could not be loaded
at _createError (/Users/JAT/Dropbox/Bottage/bottage_app/node_modules/sails/lib/hooks/session/index.js:271:21)
at Immediate._onImmediate (/Users/JAT/Dropbox/Bottage/bottage_app/node_modules/sails/lib/hooks/session/index.js:274:13)
at processImmediate [as _immediateCallback] (timers.js:358:17) { [Error: Session could not be loaded] code: 'E_SESSION' }
wZVanG Edit: The problem is already fixed, however I wonder if I have the correct configuration:
sailsrc (I removed the models from Sails created by default because I just use mongoose), However the sockets I did not have to remove them:
"hooks": {"orm": false, "pubsub": false, "blueprints": false}
/config/sessions.js
adapter: 'mongo',
host: 'localhost',
port: 27017,
db: 'page',
collection: 'sessions',
This stores it in my Mongo database:
{
"_id" : "Nt90RxTcHkOT9aM3qJ1QzxyHlnvFoUuw",
"session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\"passport\":{}}",
"expires" : ISODate("2015-07-24T10:59:42.551Z")
}
It is correct?
The reason for the message is that when you restart sails the session info is deleted on the server side but the client side still has a session cookie and when it reconnects it reuses the previous session cookie to identify which is no longer valid and therefore the server logs this warning.
There are a number of ways to prevent this message:
Use an external session store such as redis which will detach the session data from sails and will keep it even when you restart sails. see here: http://sailsjs.org/documentation/reference/configuration/sails-config-session
if socket.io is not required remove it from the project for removing the client side delete assets/js/dependencies/sails.io.js and sails.io.js include file in tasks/pipeline.js and for the server side
add this to .sails.rc:
{
"hooks": {
"sockets": false,
"pubsub": false
}
}
just reopen the browser window which will start a new socket session