i have tried using express-mysql-session
const MySQLStore = require('express-mysql-session')(session);
app.use(cookieParser())
const sessionStore = new MySQLStore(db);
const sessionConfig = {
name: 'session',
// store: sessionStore,
secret: '25658595',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
},
};
const mysql = require('mysql');
require('dotenv').config();
const connection = mysql.createConnection({
socketPath:'',
host: '',
user: '',
password: '',
database: '',
multipleStatements: true
})
connection.connect((err) => {
if (err) throw err;
console.log('Database Connected')
})
module.exports = connection;
When i able session store property the server respond with an error 502 and when i disable session store property all things work fine
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
on port 8081
Because of this message i have used express-mysql-session
Related
`Hi Experts,
I am enabling Allow only SSL connection and with below knex configuration
`
const Knex = require('knex');
const fs = require('fs');
const createTcpPool = async config => {
const dbConfig = {
client: 'pg',
connection: {
host: process.env.INSTANCE_HOST, // e.g. '127.0.0.1'
port: process.env.DB_PORT, // e.g. '5432'
user: process.env.DB_USER, // e.g. 'my-user'
password: process.env.DB_PASS, // e.g. 'my-user-password'
database: process.env.DB_NAME, // e.g. 'my-database'
},
...config,
};
if (process.env.DB_ROOT_CERT) {
dbConfig.connection.ssl = {
rejectUnauthorized: false,
ca: fs.readFileSync(process.env.DB_ROOT_CERT), // e.g., '/path/to/my/server-ca.pem'
key: fs.readFileSync(process.env.DB_KEY), // e.g. '/path/to/my/client-key.pem'
cert: fs.readFileSync(process.env.DB_CERT), // e.g. '/path/to/my/client-cert.pem'
};
}
return Knex(dbConfig);
};
module.exports = createTcpPool;
`
and when i try to execute query with createTcpPool, I get an error that The server doesnt support SSL connection. I am not sure what i else I am missing
i am using connect-mongo for storing sessions in the database and locals for sending flash to the frontend, but this is causing an error with connect-flash: sometimes when i flash a message in the backend the popup won't show up.
// sessions
const session = require('express-session');
var MongoDBStore = require('connect-mongo');
var store = MongoDBStore.create({
mongoUrl: MONGO_URI,
ttl: 7 * 24 * 60 * 60,
touchAfter: 24 * 60 * 60,
});
store.on('error', function(error) {
console.log(error);
});
const sessionConfig = {
store: store,
name: "sid",
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7,
},
};
app.use(session(sessionConfig))
when i remove store: store; the code works fine
I'm using Express Session along with Mongo Store. My session is configured so that it stores it's sessions in a Mongo Database. When I visit the app, a new session is being created. I want it so that a session is created ONLY when a user signs up and a session is resumed when the user logs in. I also want to remove a session after 24 days.
This is my configuration code: (I put an actually mongo url when I was testing)
app.use(session({
secret: "secretakey",
resave: false,
saveUninitialized: true,
store: MongoStore.create({ mongoUrl: "mongourlwenthereintesting", autoRemove: "native", touchAfter: 24 * 24 * 3600 }),
cookie: { secure: false, maxAge: 1000 * 60 * 60 * 24 * 20 },
rolling: true
}));
I am getting error while trying to save session on mongodb. Here is my code..
const express = require("express");
const session = require("express-session");
const MongoStore = require("connect-mongo").default;
const app = express();
let sessionOptions = session({
secret: "JavaScript is cool",
store: MongoStore.create({ client: require("./db") }),
resave: false,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24, httpOnly: true },
});
app.use(sessionOptions);
const router = require("./router");
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.static("public"));
app.set("views", "views");
app.set("view engine", "ejs");
app.use("/", router);
module.exports = app;
and db.js
const dotenv = require("dotenv");
dotenv.config();
const mongodb = require("mongodb");
mongodb.connect(
process.env.CONNECTIONSTRING,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err, client) => {
module.exports = client;
const app = require("./app");
app.listen(process.env.PORT);
}
);
And the error is here..
Assertion failed: You must provide either mongoUr|clientPromise in options
/home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/connect-mongo/build/main/lib/MongoStore.js:121
throw new Error('Cannot init client');
^
Error: Cannot init client
at new MongoStore (/home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/connect-mongo/build/main/lib/MongoStore.js:121:19)
at Function.create (/home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/connect-mongo/build/main/lib/MongoStore.js:137:16)
at Object.<anonymous> (/home/irfan/Desktop/Brad_Sciff/Complex_App/app.js:9:21)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
I tried to change from const MongoStore = require("connect-mongo").default to const MongoStore = require("connect-mongo")(session)
But the error is showing..
const MongoStore = require("connect-mongo")(session);
^
TypeError: require(...) is not a function
at Object.<anonymous> (/home/irfan/Desktop/Brad_Sciff/Complex_App/app.js:4:44)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at mongodb.connect (/home/irfan/Desktop/Brad_Sciff/Complex_App/db.js:10:17)
at /home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/mongodb/lib/utils.js:693:5
Using Connect-mongo 4.2, express-session 1.17.1 express 4.17.1 mongodb 3.6.4
Don't know what I am missing.
Please help.
Thanks in Advance.
Irfan.
So it looks like connect-mongo has been updated recently. I came across this issue today as well and here's how I fixed it.
How it used to be:
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
app.use(
session({
...options
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
);
How it is now:
const session = require('express-session');
const MongoStore = require('connect-mongo').default;
app.use(
session({
store: MongoStore.create({ mongoUrl: process.env.MONGO_URI }),
...options
})
);
Try passing your connection string into mongoURL instead of client and see if that helps.
You can read more about connect-mongo in their docs.
the following is worked for me.
const mongoose = require("mongoose");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const url = 'mongodb://localhost/mydb';
mongoose.connect(url, { useNewUrlParser: true, useCreateIndex: true,
useUnifiedTopology: true, useFindAndModify: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("database connected successfully...");
}).catch(err => {
console.log("connection failed...");
});
// session store
let store = new MongoStore({
mongoUrl: url,
collection: "sessions"
});
// session config
app.use(session({
secret: process.env.COOKIE_SECRET,
resave: false,
store: store,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24 }, // 24 hours
}));
what I did was to downgrade from mongodb version 4 to version 3. Hence, in your terminal, uninstall connect-mongo and reinstall lower version.
"npm uninstall connect-mongo"
"npm i connect-mongo#3"
this allows you to be able to pass in your session to the MongoStore.
"const path = require('path')
const express = require('express')
const mongoose = require ('mongoose')
const dotenv = require('dotenv')
const morgan = require('morgan')
const exphbs = require ('express-handlebars')
const passport = require('passport')
const session = require ('express-session')
const MongoStore = require('connect-mongo')(session)"
This is latest solution
add this lines
First
var session = require('express-session');
var MongoStore = require ('connect-mongo');
Second
app.use(session(
{
secret: '**something** like mysupersecret',
store: MongoStore.create({
mongoUrl: '**your url**like mongodb://localhost/test-app'}),
}));
There is an another npm package connect-mongodb-session,
https://www.npmjs.com/package/connect-mongodb-session
Install it and it should work.
const MongoDBStore = require('connect-mongodb-session')(session);
This worked for me,
const session = require('express-session');
const MongoStore = require('connect-mongo');
const dbUrl = process.env.DB_URL;
app.use(session({
secret: 'thisismysecret',
resave: false,
saveUninitialized: false,
store: MongoStore.create( {
mongoUrl: dbUrl,
touchAfter: 24 * 3600
}) }));
Is there a way by which I can store user cookies (jwt) in my mongodb database with express-rate-limit and rate-limit-mongo packages?
Code that I am currently using :
var limiter = new RateLimit({
store: new MongoStore({
uri: process.env.MONGO_URI,
expireTimeMs: 60 * 1000 * 60,
}),
max: 150,
windowMs: 10 * 60 * 1000,
message: "Too many requests in a short duration, IP Banned for an hour.",
});
I want to know the jwt cookie (if it exists) associated with the request too somehow so that I can know who the culprit was.
Basically, how can I access the request object and store it in the rate limiting database
I was able to do this with the onLimitReached function available in express-rate-limit like so:
var queslimiter = new RateLimit({
store: new MongoStore({
uri: process.env.MONGO_URI,
expireTimeMs: 60 * 1000 * 60,
collectionName: "ansForce",
}),
max: 30,
message: "Too many requests in a short duration, IP Banned for an hour.",
onLimitReached: async function (req, res) {
try {
const blacklist = new Blacklist({
team: req.cookies.team,
});
try {
const bad = await blacklist.save();
} catch (e) {
console.log(e);
}
} catch (e) {}
},
});