Sailsjs session error - sails.js

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

Related

Getting correct socketPath for TypeORM config

I'm trying to connect a Cloud Run service to Cloud SQL postgres instance. I believe I'm nearly there, but am having some trouble getting the deployed instance to connect properly. My local environment can connect (via SSL) to the database intended for production, but the deployed version can't...
I'm using TypeORM, and have everything setup properly in the configuration...
#Module({
imports: [
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => {
const socketPath = configService.get('DB_SOCKET_PATH');
const extra = socketPath ? {
socketPath: socketPath,
ssl: {
rejectUnauthorized: false,
ca: Buffer.from(process.env.DB_SSL_CA, 'base64').toString('ascii'),
cert: Buffer.from(process.env.DB_SSL_CERT, 'base64').toString('ascii'),
key: Buffer.from(process.env.DB_SSL_KEY, 'base64').toString('ascii'),
}
} : { };
return ({
type: 'postgres',
host: socketPath || configService.get('DB_HOST'),
port: configService.get('DB_PORT'),
username: configService.get('DB_USER'),
password: configService.get('DB_PASS'),
database: configService.get('DB_NAME'),
extra: extra,
entities: [__dirname + '/../../modules/**/*.entity{.ts,.js}'],
namingStrategy: new SnakeNamingStrategy(),
synchronize: true,
});
}
})
]
})
export class DatabaseModule { }
Despite that I'm getting an error when I try to use the socketPath as the host rather than the actual host variable (necessary for GCP). It seems that TypeORM is adding extra characters, /.s.PGSQL.5432, at the end of my connection string that I don't want. And just to clarify, the socket path is in the form of /cloudsql/<PROJECT_ID>:<REGION>:<INSTANCE>.
[Nest] 28532 - 02/15/2021, 2:25:07 PM [ExceptionHandler] connect ENOENT <DB_SOCKET_PATH>/.s.PGSQL.5432 +3ms
Error: connect ENOENT <DB_SOCKET_PATH>/.s.PGSQL.5432
at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
At an older point in time, this used to work for me but I guess something changed in the TypeORM library. Does anybody have any ideas on this? Thanks!
EDIT: As of now I've gotten it to connect to the server correctly, but it's now giving me an error that says the server doesn't support SSL connections, which makes no sense given that I can connect via SSL fine on my local machine...?
SOLUTION: The issue does not seem to any code's fault, but rather some networking stuff on the GCP side. I configured the service and database to run through a VPC then just used a private IP address for the host.
It seems that TypeORM is adding extra characters, /.s.PGSQL.5432
This is actually intended - the Postgres spec requires that the unix sockets end with this suffix.
[Nest] 28532 - 02/15/2021, 2:25:07 PM [ExceptionHandler] connect ENOENT <DB_SOCKET_PATH>/.s.PGSQL.5432 +3ms
The error means that the socket wasn't found - usually because there was a misconfiguration and the Cloud SQL proxy couldn't start. You can check your logs at the instance start up to see if the proxy left any errors, but generally it'll come down to the following:
The Cloud SQL Admin API needs to be enabled
Your service account needs to have Cloud SQL Connect IAM role (or equivalent)
The service needs to be configured for Cloud SQL.
For a full list of instructions, see the Connecting from Cloud Run to Cloud SQL page.

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)

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

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.

Check mongo status on Meteor?

I'm trying to create an alarm system for my application, that will trigger when one of the services (e.g. MongoDB) is not working.
What I'm doing is, once the application is started, I shut down my MongoDB server and try to connect to it, but instead of receiving an error my application just gets stuck into the execution of the method. The server console looks like something is in execution.
My current code (coffeescript) is:
checkMongoService: ()->
mongo = Npm.require 'mongodb'
assert = Npm.require 'assert'
url = 'mongodb://....'
mongo.connect url, (err, db) ->
assert.equal null, err
console.log 'Connected correctly to server'
db.close()
return
I've also been trying by doing a simple
Meteor.users.find().count();
or using MongoInternals with
testConnection = new MongoInternals.RemoteCollectionDriver("mongodb://...);
but still same issue, when mongo is not running no error is thrown and the console stops to work. If then I start Mongo again, it will just return the result (in this case the log 'Connected correctly to server')
Something that I've noticed is if I try with meteor shell to execute testConnection = new MongoInternals.RemoteCollectionDriver("mongodb://...); I get an error "Error: failed to connect to [127.0.0.1:27017]"
TL;DR
Do you might have an idea on how I can check if mongo is reachable or do you know if I'm doing something wrong with the code above?
Try setting the timeouts to be a bit shorter than the default 30 seconds:
mongo.connect(url, {
connectTimeoutMS: 1000,
socketTimeoutMS: 1000,
reconnectTries: 1
}, function(err, db) {...}
(Full set of connection params are here)
Meteor.status().status
from the docs
This method returns the status of the connection between the client and the server. The return value is an object with the following fields:
connected (Boolean)
True if currently connected to the server. If false, changes and method invocations will be queued up until the connection is reestablished.
status (String)
Blockquote
Describes the current reconnection status. The possible values are connected (the connection is up and running), connecting (disconnected and trying to open a new connection), failed (permanently failed to connect; e.g., the client and server support different versions of DDP), waiting (failed to connect and waiting to try to reconnect) and offline (user has disconnected the connection).
https://docs.meteor.com/api/connections.html

Connection to mongoose causes ECONNREFUSE [duplicate]

I've got a problem to connect my socketIO application (made with nodeJS) with my mongoDB.
I try to connect on an remote server, but its throws me error
Here's my code (there's no user/password set in the mongoDB) :
var url = "mongodb://192.168.1.5:27017/DB"
MongoClient.connect(url, function(err, db) {
console.log("test")
if (!err) {
console.log("test");
}
else {
console.dir(err)
throw err
}
// db.close();
});
And here's when I launch the server and I tried to launch the app in a navigator :
Server listening at port 80:
{ [MongoError: connect ECONNREFUSED] name: 'MongoError', message: 'connect ECONNREFUSED' }
/root/fys-realtime/examples/chat/node_modules/mongodb/lib/server.js:228
process.nextTick(function() { throw err; })
^
Error
at Error.MongoError (/root/fys-realtime/examples/chat/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:13:17)
at Server.destroy (/root/fys-realtime/examples/chat/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:629:47)
at Server.close (/root/fys-realtime/examples/chat/node_modules/mongodb/lib/server.js:344:17)
at Db.close (/root/fys-realtime/examples/chat/node_modules/mongodb/lib/db.js:267:19)
at /root/fys-realtime/examples/chat/node_modules/mongodb/lib/db.js:196:12
at null.<anonymous> (/root/fys-realtime/examples/chat/node_modules/mongodb/lib/server.js:226:9)
at g (events.js:180:16)
at emit (events.js:98:17)
at null.<anonymous> (/root/fys-realtime/examples/chat/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:238:68)
at g (events.js:180:16)
This error is returned for several errors like :
server is not running
you need to authenticate user
this database does not exists
the mongodb port is not the default port
Check this. Normaly your problem is just one of these causes
For this to work you have to make the changes in /etc/mongod.conf
comment bind_ip=127.0.0.1 As if this line in not commented it Listen to local interface only.
One of the solutions is to change 127.0.0.1 to public ip or whatever the router provided you with in mongodb config file located in /etc
There could be few reasons for ECONNREFUSED error.
Checkpoints
Check if your port is not serving any other process.
Check if your mongod is running.
Check if you localHost is configured correctly with your id or not.
for more you can see this