MongoError: not authorized on (DB name) to execute command - node.js

I'm using Node.Js, Expressjs, mLab (to host my database) and mongoDB
Im getting an error of not being Authorized on Streetinform(my DB name) to execute command. {listIndexes: "sessions", cursor: {}}
this is the error.
this is how I connect to my Database
var dbHost = process.env.DB_HOST || 'localhost';
var dbPort = process.env.DB_PORT || 3002;
var dbName = process.env.DB_NAME || 'Mongodb';
var dbURL = 'mongodb://'+dbHost+':'+dbPort+'/'+dbName;
if (app.get('env') == 'development'){
// prepend url with authentication credentials //
dbURL = 'mongodb://'+process.env.DB_USER+':'+process.env.DB_PASS+'#'+dbHost+':'+dbPort+'/'+dbName;
}
app.use(session({
secret: 'secret',
proxy: true,
resave: true,
saveUninitialized: true,
store: new MongoStore({ url: dbURL })
})
);
this is my library
var http = require('http');
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var errorHandler = require('errorhandler');
var cookieParser = require('cookie-parser');
var MongoStore = require('connect-mongo')(session);
var dotenv = require('dotenv')
dotenv.load();
var app = express();
Establish Connection to Database
var crypto = require('crypto');
var MongoDB = require('mongodb').Db;
var Server = require('mongodb').Server;
var moment = require('moment');
/*
ESTABLISH DATABASE CONNECTION
*/
var dbName = process.env.DB_NAME || 'mongodb';
var dbHost = process.env.DB_HOST || 'localhost'
var dbPort = process.env.DB_PORT || 3002;
var db = new MongoDB(dbName, new Server(dbHost, dbPort, {autoReconnect: true}), {w: 1});
db.open(function(err, d){
if (err) {
console.log(err);
} else {
if (process.env.NODE_ENV == 'live') {
db.authenticate(process.env.DB_USER, process.env.DB_PASS, function(e, res) {
if (e) {
console.log('mongo :: error: not authenticated', e);
}
else {
console.log('mongo :: authenticated and connected to database :: "'+dbName+'"');
}
});
} else{
console.log('mongo :: connected to database :: "'+dbName+'"');
}
}
});

I to use mLabs to, it appears that you have not created a database uses due to which it cannot execute any commands.
You can enable it using the following steps:
Go to https://mlab.com/home
Click on the database which you are using from the Development and Utility
Click on the Users tab
Click the Add database user button
Enter you desired credentials
So now when you are authenticating pass in the username and password that you have entered in step 5

Related

swagger not preserving sessions

I am trying to set up a simple login endpoint in swagger:
//login.js
'use strict';
function login(req, res){
const userId = req.swagger.params.user_id.value;
const user = {
_id: userId
}
if(req.session.userId){
return res.json([req.session.userId, 'hello']);
}
global.app.db.collection('users').insertOne(user, function(err, b){
req.session.userId = userId;
return res.json([req.session]);
});
}
module.exports = {
login: login
};
It seems the if statement is never true, and the userId is never set permanently (it shows up in just the second return statement after the insert statement).
Not sure what is wrong here. My app.js has the typical express-session setup.
//app.js
'use strict';
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const mongoDbUrl = 'mongodb://localhost:27017';
const dbName = 'my_db';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
var session = require('express-session')
const MongoStore = require('connect-mongo')(session);
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'some secret',
store: new MongoStore({url:mongoDbUrl}),
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))
module.exports = app; // for testing
global.app = app;
var config = {
appRoot: __dirname // required config
};
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
var port = process.env.PORT || 10010;
app.listen(port);
if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
}
});
MongoClient.connect(mongoDbUrl, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
app.db = db;
});
Looks like the problem was this line:
cookie: { secure: true }
secure should have been false because I wasn't using https on my local machine.

Sharing Session Socket.io Express

I am using the express-socket.io-session and express-mysql-session to share a session between socket.io and express. I do this as follows:
var express = require('express');
var mysql = require('mysql');
var app = express();
var serv = require('http').Server(app);
var io = require('socket.io')(serv, {});
var MySQLStore = require('express-mysql-session');
var options = {
host: "...",
user: "...",
password: "...",
database: "...",
};
var con = mysql.createConnection(options);
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
var sessionStore = new MySQLStore({},con);
var session = require("express-session")({
secret: "...",
resave: true,
saveUninitialized: true,
store : sessionStore
});
var sharedsession = require("express-socket.io-session");
// Use express-session middleware for express
app.use(session);
// Use shared session middleware for socket.io
// setting autoSave:true
io.use(sharedsession(session, {
autoSave:true
}));
Next, I have the following:
app.get('/', function(req, res, next){
console.log(req.session.sessionId);
console.log(req.session.username);
});
Finally:
socket.on('login', function(data) {
socket.handshake.session.sessionId = sessionId;
socket.handshake.session.username = result[0].username;
socket.handshake.session.save();
}
When I check my database, these values are saved correctly. However,
console.log(req.session.sessionId);
console.log(req.session.username);
always prints undefined, even after the login has occurred.

express-session session is not consistent

In my project i am using nodejs (express), react js and socket.io to develop a chatting application. But i am not able to get "correct sessionid" inside my socket function (io.use).
In server.js file there are routes and functions to handle socket connections.
In my project i had started my express-session inside login.js file.
Then after successfull login...i am redirecting to home.js, which intern returns home.html.
home.html contains js file, which is having react code and also have socket connections.
server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');
var DIST_DIR = path.join(__dirname, "bin");
var express = require('express');
//Getting session store
var session = require('express-session');
var cookieParser = require('cookie-parser');
var sessionStore = new session.MemoryStore();
var handshakeData ={};
var cookie = require('cookie');
//Importing routes
var login = require('./routes/login.js');
var registration = require('./routes/registration.js');
var home = require('./routes/home.js');
//Getting cookies from request header. so that from it we can get sessionid.
io.use(function(socket, next) {
handshakeData = socket.request;
var cookies = cookie.parse(handshakeData.headers.cookie);
//Bringing sessionid and storing in a global variable
console.log("***********************Server*********************");
console.log("");
console.log('All cookies parsed in io.use ( %s )', JSON.stringify(cookies));
handshakeData.sessionID = cookies['connect.sid'].split('.')[0].split(':'[1];
console.log('All cookies parsed at server ( %s )', JSON.stringify(cookies));
console.log('Session id at server cookie value in io.use( %s )',
JSON.stringify(handshakeData.sessionID));
next();
});
//Bringing session data by sending "sessionid" to sessionStore
(MemoryStore)place
io.on('connection', function(socket){
sessionStore.get(handshakeData.sessionID, function (err, session) {
handshakeData.session = session;
//Now we can retrieve all session data. But sessionID sent was
not correct
});
console.log('user connected');
socket.on('new message', function(msg){
console.log('Server recieved new message: '+msg);
io.emit('new message', msg);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
app.use('/', login);
app.use('/registration', registration);
app.use('/home', home);
http.listen(8080, function(){
console.log("listening on port 8080");
});
login.js
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var cookieParser = require('cookie-parser');
var session = require('express-session');
var sessionStore = new session.MemoryStore();
var login_success = 0;
router.use(cookieParser());
router.use(session({ cookie: {
maxAge : 24*60*60*1000
},
store: sessionStore,
saveUninitialized: true,
resave: true,
secret: '1234567890QWERT'
}));
router.get('/', function(req, res){
console.log("Actual session id before login: "+ req.sessionID);
//Clearing cookies at client side.
res.clearCookie("login_message");
res.clearCookie("connect.sid");
res.clearCookie("io");
res.clearCookie("user_name");
res.clearCookie("user_id");
if (login_success == 2)
{
res.cookie('login_message', 'incorrectCredentials');
login_success = 0;
}
res.sendFile(path.join(SRC_DIR,"login.html"));
// res.sendFile(path.join(__dirname, '../bin', 'login.html'));
});
router.post('/', urlencodedParser, function(req, res){
console.log("database called");
//Fetching form data
var username = req.body.loginusername;
var password = req.body.loginpassword;
//Connection string to datanbase
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/WebChat";
//Comparing username and password.
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var query = { email: username, password: password };
db.collection("Profile").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
if (result.length != 0)
{
console.log("login success");
login_success = 1;
//Setting session variables
req.session.userid = username;
req.session.username= result[0].firstname;
console.log("***********************Login*********************");
console.log("");
console.log("Actual session id at login: "+ req.sessionID);
console.log("Session userid at server set to :"+ req.session.userid);
console.log("Session name at server set to :"+ req.session.username);
//res.sendFile(path.join(SRC_DIR,"home.html"));
// res.status(200).send(req.session);
console.log("Session reload called");
res.redirect('/home');
}
else
{
//**It is for when user come to login page with entering wrong credentials
login_success = 2;
console.log("login failed");
res.redirect('http://localhost:8080');
}
});
});
});
//export this router to use in our server.js
module.exports = router;
home.js
var express = require('express');
var router = express.Router();
var path = require("path");
var SRC_DIR=path.join(__dirname, "../src/views");
var session = require('express-session');
cookie = require('cookie');
var cookieParser = require('cookie-parser');
var sessionStore = new session.MemoryStore();
var handshakeData ={};
router.use(cookieParser());
router.use(session({ cookie: {
maxAge : 24*60*60*1000
},
store: sessionStore,
saveUninitialized: true,
resave: true,
secret: '1234567890QWERT'
}));
router.get('/', function(req, res){
//setting cookie at client side
res.clearCookie("user_id");
res.clearCookie("user_name");
res.cookie('user_id', req.session.userid);
res.cookie('user_name', req.session.username);
// res.status(200).send(req.session);
console.log(" session reload called");
setTimeout(function(){
res.sendFile(path.join(SRC_DIR,"home.html"));
}, 5000);
console.log("***********************Home*********************");
console.log("");
console.log("Actual session id at home: "+ req.sessionID);
console.log("Cookie userid at client set to :"+ req.session.userid);
console.log("Cookie username at client set to :"+ req.session.username);
});
//export this router to use in our server.js
module.exports = router;
home.jsx (client side file)
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {messages: [],socket: io.connect('http://localhost:8080')};
this.send = this.send.bind(this)
}
}
export default Home
Ouput when exicuting "node server.js":
output
In the above output...
1. login page we got two different session ids (before login and after login).I don't know why this is happening
2. While accessing the session variable inside "server.js", in "io.use" function... we again getting old session id, which was set before login.But with this i can't get my session variable. Because i need to pass new session variable in order to access session variable inside sessionStore.get.
Please help. i have been trying this for 3 days.
Thanks in advance.

session in nodejs express

I' m using const SessionStore = require('express-session-sequelize')(expressSession.Store); for storing the sessions.
I would like to save in session currenty user, which log to site.
here is a configuration for store:
const expressSession = require('express-session');
const SessionStore = require('express-session-sequelize')(expressSession.Store);
const Sequelize = require('sequelize');
const myDatabase = new Sequelize('analytic', 'root', '', {
host: 'localhost',
dialect: 'mysql'
});
const sequelizeSessionStore = new SessionStore({
checkExpirationInterval: 15 * 60 * 1000, // The interval at which to cleanup expired sessions in milliseconds.
expiration: 24 * 60 * 60 * 1000, // The maximum age (in milliseconds) of a valid session.
db: myDatabase
});
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.use(expressSession({
secret: '412415415415415121212121',
store: sequelizeSessionStore,
name: 'session_id',
resave: false,
saveUninitialized: false
}));
So, now for login I have this:
var express = require('express');
var url = require('url');
var router = express.Router();
var User = require('../../model').User;
var jwt = require('jsonwebtoken');
var app = require("../../application");
router.post('/authenticate', function(req, res) {
User.doLogin(req).then((result)=> {
if (result) {
if (result.error) {
if (result.error.hasOwnProperty("email")) {
res.send(400, { success: false, message: "Incorrect user / password"});
} else if (result.error.hasOwnProperty("activated")) {
res.send(400, {success: false, message: "You are not activated yet"});
}
} else {
//app.createSession(req);
req.session.user = result;
res.send(200, result);
}
}
});
});
module.exports = router;
Now, after this req.session.user = result; I have in db session table with current user data.
Now,
How can I verify is this user authenticated?
and I notice that for every request I get diferrent sessionID (is this ok)
Thanks
Hi there for user manager you can use passportjs
it's a great user manager for express and provide a high quality for handle with your user manager logic .

Sails.js How to load session and create, check, destroy?

In config session.js i have enabled redis
before that i have installed these two things...
npm install connect-redis
npm install express
adapter: 'redis',
//
// on localhost is expected.
// Read more about options at: https://github.com/visionmedia/connect-redis
//
host: 'localhost',
port: 6379,
ttl: 3600,
db: 0,
pass: '',
prefix: 'sess:'
In controller 2
//assign the value in session and redirect to controller1
req.session.error = "category Not found";
//error
TypeError: Cannot set property 'error' of undefined
module.exports = {
load_word: function(req, res){
var async = require('async');
var express = require('express');
var RedisStore = require('connect-redis')(express);
async.waterfall([
function(callback){
Category.findOne().where({keyword:req.param('keyword')}).done(function(err,category){
if(category==undefined){
req.session.error = "category Not found";
res.redirect('home');
}else{
category_id = category.id;
}
/*Word.findOne().where({id:category_id}).done(function(err,word){
});*/
});
},
Controller 1
console.log(req.session.error);
module.exports = {
/**
* Action blueprints:
* `/home/index`
* `/home`
*/
index: function (req, res) {
var async = require('async');
var express = require('express');
var RedisStore = require('connect-redis')(express);
var data = new Object();
console.log(req.session.error);
How to solve this ?
To check if category is undefined or not use
if(typeof(category)!='undefined){}

Resources