What's the best/common way to use an express-session in other files? I have trouble integrating the session into my code. I was using auth tokens, but I would like to use sessions instead.
I defined session in my server.js:
const express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser('secret'));
app.use(session({
key: 'user_sid',
secret: 'secret',
resave: false,
saveUninitialized: false,
cookie: {
expires: 600000
}
}));
// stuff
module.exports = {app, session};
And it works fine! But When I try to use it in my userController.js:
var express = require('express');
var {session} = require('./../server');
module.exports.login = (req, res) => {
var body = _.pick(req.body, ['email', 'password']);
User.findByEmailAndPassword(body.email, body.password).then((user) => {
// console.log(req.session); // is undefined
res.render('dashboard.hbs');
}).catch((e) => {
res.status(400).send();
});
}
then req.session is undefined.
I know what I'm doing isn't right, obviously, but what's the right way to do it?
Thanks!
I think you don't have to export session at all, as you are telling your app to use it in server.js.
So the working fiddle should be looking like the following:
const express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser('secret'));
app.use(session({
key: 'user_sid',
secret: 'secret',
resave: false,
saveUninitialized: false,
cookie: {
expires: 600000
}
}));
// stuff
module.exports = app;
and your controller:
module.exports.login = (req, res) => {
var body = _.pick(req.body, ['email', 'password']);
User.findByEmailAndPassword(body.email, body.password).then((user) => {
// console.log(req.session); // is undefined
res.render('dashboard.hbs');
}).catch((e) => {
res.status(400).send();
});
}
I am considering that you are going to use this exported login function for a route, like
app.use('/login', require('yourCtrl.js').login);
Related
I have a mern web app, and I'm using express session. The problem is, the cookie data is not getting saved when I try retrieving it on a different route. It gets set and outputs correctly on the same route, but when I go to another route, and try to retrieve the session data, it returns undefined.
What's weird, is that the session does get stored in mongodb, but I can't retrieve it.
What am I doing wrong and how can I fix it?
Here's the relevant code:
Session.js
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const mongoose = require('mongoose');
module.exports = function(app) {
var sess = {
secret: 'mySecret',
cookie: { token: null },
saveUninitialized: false,
resave: true,
store: new MongoStore({ mongooseConnection: mongoose.connection })
};
if (app.get('env') === 'production') {
app.set('trust proxy', 1);
sess.cookie.secure = true;
}
app.use(session(sess));
};
Route.js
module.exports = function(app) {
app.use(cors());
app.use(helmet());
require('../middleware/session')(app);
// Other routes...
};
File1
router.post('/', async (req, res) => {
req.session.token = 'hello';
console.log(req.session.token); // Outputs 'hello'
res.send(req.session.token);
});
File2 This gets called After the page reloads
router.get('/me', async (req, res) => {
console.log(req.session.token); // Outputs undefined
console.log(req.session);
// Outputs: "Session {
// cookie: { path: '/',
// _expires:null,
// originalMaxAge: null,
// httpOnly: true }
// }
res.send(req.session.token);
});
You should add the code below in your app.js file
var cookieParser = require('cookie-parser');
var session = require('express-session');
app.use(cookieParser());
app.use(session({secret: "Funny secret"}));
That's the simple way to do it. Then you may be able to assign and access values to the req.session object.
im trying to set up a session in NodeJS and use it in my /auth route after that but i'm getting undefined troubles with the session.
In the app.js :
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('./config/DB');
const app = express();
const session = require('express-session')
const MongoStore = require('connect-mongo')(session);
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
() => { console.log('Database is connected') },
err => { console.log('Can not connect to the database' + err) },
options
);
const db = mongoose.connection
const adUnitRoutes = require('./routes/adunit.route');
const userProfileRoutes = require('./routes/userprofile.route');
app.use('/adunits', adUnitRoutes);
app.use('/userprofile', userProfileRoutes);
app.use(session({
secret: 'my-secret',
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: db })
}));
In the route :
userProfileRoutes.route('/authentification').post((req, res) => {
console.log('req session : ' + req.session.userId);
//here I got cant read property of userId because session is undefined
});
This happens because you are setting your routes before adding the middleware. Your handlers are essentially middleware so if they are added before session, your session has not been processed and added to the request yet.
Adding the routes after setting your middleware will make it work as expected.
See this minimized example:
const express = require('express');
const app = express();
const session = require('express-session');
app.get('/broken', (req, res) => {
console.log('req session : ' + req.session.userId);
res.write(String(req.session.userId));
req.session.userId = 1;
res.end();
});
app.use(
session({
secret: 'my-secret',
resave: false,
saveUninitialized: true
})
);
app.get('/ok', (req, res) => {
console.log('req session : ' + req.session.userId);
res.write(String(req.session.userId));
req.session.userId = 1;
res.end();
});
app.listen(8089);
This is my code:
const functions = require('firebase-functions');
const express = require('express');
const session = require('express-session');
const FirebaseStore = require('connect-session-firebase')(session);
const firebase = require('firebase-admin');
const cookieParser = require('cookie-parser');
const ref = firebase.initializeApp(
functions.config().firebase
);
const app = express();
app.use(cookieParser());
app.set('trust proxy', 1);
app.use(session({
store: new FirebaseStore({
database: ref.database()
}),
secret: 'abigsigrettotheseeiosnofthmbiith765huig',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));
app.get('/', function(req, res, next) {
console.log(req.session);
req.session.username='xyz';
res.send('Filling the session with data');
});
app.get('/bar', function(req, res, next) {
console.log(req.session);
var sessionData = req.session.username;
res.send(`This will print the attribute I set earlier: ${sessionData}`);
});
exports.app = functions.https.onRequest(app);
When I run this, it creates new session in the DB.
And every time I refresh the page, there is a new session.
I want of course, that only one session would be created,
and that on refresh, this session would only be updated, or to get the data from there. not to create a new one every time.
Checking the cookies - showed me that no cookie is saved / created.
I've been working on this for hours...
this was frustrating when I was using firebase functions and hosting, but can be solved by simply setting name:"__session" in the session.
app.use(session({
store: new FirebaseStore({
database: ref.database()
}),
name:"__session
...
I developing login page.
If user successfully logs in , then I want to store user_Id into session variable,which I will be using to authenticate other pages.
App.js
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var cookieParser = require('cookie-parser');
var session = require('express-session');
app.use(bodyParser.json());
app.use('/user', userRoutes);
app.use('/', index);
app.use(cookieParser());
app.use(session({
secret: "helloKey",
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection}),
cookie: { maxAge: 180 * 60 * 1000 }
}));
User router
var express = require('express');
var router = express.Router();
User = require('../models/user');
//Login User
router.post('/login', function (req, res) {
var user = new User(req.body);
User.login(user, function (err, user) {
if (err) {
res.sendStatus(500);
throw err;
}
if (!user) {
res.sendStatus(404);
return;
}
req.session.name = user.id;
res.json(user.id);
});
});
Problem is if I execute this code I am getting Cannot set property 'name' of undefined
What I am doing wrong?
Please Help.
Problem is that your routes are already setup before session so you have to reorder the code.
Move these lines
app.use('/user', userRoutes);
app.use('/', index);
Below the app.use(session) declaration.
app.use(session({
secret: "helloKey",
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection}),
cookie: { maxAge: 180 * 60 * 1000 }
}))
I am implementing a MongoStore for use in session storage within my Node.js/Express application, however it looks as if none of the sessions are actually being stored in the database. (The MongoDB does not even have the db.session).
Socket.io 'authorization' takes the incoming data, and crosschecks the sent sessionID, however it keeps returning empty.
Hope someone could shed some light on any issues?
var express = require('express');
var bodyParser=require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var utils = require("express/node_modules/connect/lib/utils");
var parseSignedCookie = utils.parseSignedCookie;
var cookie = require('cookie');
var app = express();
app.use(bodyParser());
app.use(cookieParser());
var sessionStore = new MongoStore({
db: 'express',
host: 'localhost',
port: 27018,
collection: 'session',
auto_reconnect:true
});
app.use(session({
cookie: { maxAge: 5000 } ,
secret: "session secret",
store: sessionStore
}));
function checkSession(req,res,next){
if(req.session.user){
next();
}
else {
req.session.error = "Get Outta here!";
res.redirect('/');
}
}
app.get('/', function(req, res){
res.sendfile('./index.html');
});
app.post('/',function(req,res){
if(req.body.name){
req.session.user=req.body.name;
res.redirect('/info');
}
else {
req.session.error = "Auth Failure";
res.redirect('back');
}
});
app.get('/info', checkSession, function(req,res){
if(req.headers.cookie){
var session_id = utils.parseSignedCookie(req.headers.cookie, 'session secret');
console.log(session_id);
console.log("true");
res.sendfile('./info.html');
}
else {
console.log("false");
res.redirect('/');
}
});
var http = require('http').Server(app);
http.listen(80, function(){
console.log('listening on *:80');
});
var io = require('socket.io').listen(http);
You're not using your sessionStore anywhere. Try this:
app.use(session({
store: sessionStore,
cookie: { maxAge: 5000 } ,
secret: "session secret"
}));