Session is not defined in Express - node.js

I've included the cookie-parser before the session (not sure if needed with the current versions), imported express-session as visible. If I change session to express.session on line 8 I get a deprecation error (not warning).
var express = require('express'),
cookieParser = require('cookie-parser'),
expressSession = require('express-session'),
port = process.env.PORT || 3000;
app = express();
app.use(cookieParser());
app.use(session({
secret: "yadayada",
resave: true,
saveUninitialized: true
}));
app.get('/', function (req, res) {
console.log(req.session);
console.log(req.cookies);
});
app.listen(port);

session is not defined on line 9 because you have it declared as expressSession at the top i.e.
expressSession = require('express-session')
Either rename the declaration to session or update line 9 to call expressSession i.e.
app.use(expressSession({ ... }));

same question......
but https://github.com/expressjs/session?_ga=1.45435812.1066105876.1451139756
app.use(session({
genid: function(req) {
return genuuid() // use UUIDs for session IDs
},
secret: 'keyboard cat'
}))

Related

req.isAuthenticated() returning false all the time in passportjs

I have passport setup in express and req.isAuthenticated() always returning due to wrong order of code in index.js. I am not able to figure out the order in which I have to write code , I searched for other answers in stackoverflow and I couldnt figure out the right order since my code has different dependencies please help . This is my index.js file :
const winston = require("winston");
const express = require("express");
const config = require("config");
const app = express();
const passport = require('passport');
const flash = require('connect-flash');
var session = require('express-session');
const cookieParser = require('cookie-parser');
app.use(express.json());
app.use(cookieParser());
app.use(session({
secret: 'ilovescotchscotchyscotchscotch',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.initialize());
app.use(passport.session());
require('./services/passport')(passport);
require("./startup/db")();
app.use(flash());
require("./startup/logging")();
require("./startup/cors")(app);
require("./startup/routes")(app);
require("./startup/config")();
//require("./startup/validation")();
const port = process.env.PORT || config.get("port");
const server = app.listen(port, () =>
winston.info(`Listening on port ${port}...`)
);
module.exports = server;
Thanks.

Nodejs Flash messages only loads after the page is refreshed (connect-flash)

I'm getting stuck with connect-flash , all flash messages doesn't load on the page unless I refresh for a couple of times I'm not sure why.
I created a small project just to test connect-flash and it's the same result, please check the code below:
App.js code:
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const flash = require('connect-flash');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
//using flash
app.use(flash());
app.use(function(req, res, next){
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
});
//flash route
app.get('/flash', (req, res) =>{
req.flash("success", "CONNECT FLASH TEST");
res.render('flash');
});
const port = process.env.PORT || 5000;
app.listen(port, () =>{
console.log(`App has started on port ${port}`);
})
Here's the code for the flash.hbs page to render the flash message:
<h1>Flash page</h1>
{‌{#if success}}
<h2>{‌{success}}</h2>
{‌{/if}}
Thanks so much in advanced, any help would be highly appreciated guys.
Do they render after just one refresh? That's how they are supposed to work.
"Flash messages" are used to carry a message over to the next request, and most of the time the only reason is the post-request-get pattern. If you just want to show a message to the user on the same page, while not doing a redirect, you don't need a library for it. Just pass the message to the template as data.
I was halfway through rolling my own new version of req.flash, when I was looking through the docs of express-session and came across this gem:
Note Since version 1.5.0, the cookie-parser middleware no longer needs to be used for this module to work. This module now directly reads and writes cookies on req/res. Using cookie-parser may result in issues if the secret is not the same between this module and cookie-parser.
And lo, I had these lines:
app.use(require('cookie-parser')())
const session = require('express-session')
const MongoStore = require('connect-mongo')(session)
app.use(session({
secret: process.env.SESSION_STORE_SECRET,
store: new MongoStore({mongooseConnection: mongoose.connection}),
maxAge: 10*365*24*60*60*1000, // set to 10 years
resave: false,
saveUninitialized: false
}))
Once I changed the cookie-parser line to:
app.use(require('cookie-parser')(process.env.SESSION_STORE_SECRET))`
it worked exactly as expected!
(For some people, the answer will be to remove cookie-parser altogether.)

Nodejs/Express/Cookies: how do you set signed cookies with a secret

In my directory i have app.js And Index.htmml ; I am trying to set cookies from App.js; I have tried:-
var express = require('express'),
app = express(),
http = require('http'),
cookieparser = require ('cookie-parser'),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/data'));
app.get('/', function(req, res) {
let options = {
maxAge: 60000, // would expire after 1 minutes
httpOnly: true,
signed: true ,
secret: 'secret'
}
// Set cookie
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
res.cookie('cookieName', 'Success', options)
res.sendFile(__dirname + '/index.html');
});
app.listen(8080);
When i run app.js from Cmd It dissappoints me with this error
Thanks in advance for help
Error: cookieParser("secret") required for signed cookies
You need to specify a secret key which will be used while signing the cookie.
You can do this by adding the following line to your code.
app.use(cookieparser("secret"));
According to the snippet, you are using the express-session module like so:
app.use(require('express-session')({ secret: 'keyboard cat', ... }));
That is already saying that you want cookies to be signed. Therefore, in your cookie options you can remove the option signed: true since it will be redundant.
And on a last note, you need to improve that code.

Redis not working on express-session

The code below is quite a normally snippet, but it's not working, session from request is undefined. Anyone who can give me a hint will be appreciated.
var express = require('express');
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var app = express();
app.listen(3000);
app.use(session({
store: new redisStore({
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
app.get('/', function (req, res) {
if(req.session.isVisit) {
req.session.isVisit++;
res.send('<p>times to be here:' + req.session.isVisit + '</p>');
} else {
req.session.isVisit = 1;
res.send('1st time to be here');
}
});
A Redis client is required
var redis = require("redis"); // You can use any module to create redis client
app.use(session({
store: new redisStore({
client : redis.createClient(<your setting>)
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
Please refer this link:
https://www.npmjs.com/package/connect-redis
Pass the express-session store into connect-redis to create a RedisStore constructor.
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.use(session({
store: new RedisStore(options),
secret: 'keyboard cat'
}));

Share sessions with redis and passport on a subdomain?

I am using npm subdomain, inside my app I have routes that fake a subdomain
// looks like app.localhost:3000
router.get('/subdomain/app', app.dashboard);
So I have a login page on a subdomain and a login page on a non subdomain page. They don't share sessions, so I have to login twice. I want to setup redis, but I don't know how.
// here is my session middleware, I tried using .localhost
app.use(session({ secret: 'something', domain: '.localhost', }));
I have seen where people are using redis like
app.use(express.session({
store:new RedisStore({
host: config.redis.session.host,
port: config.redis.session.port,
db: config.redis.session.db
}),
secret: config.session_secret
}));
This seems like it could solve my issue but I have no clue how to setup a redisStore and where the config data comes from?
Can someone explain to me how to use redis so that when a user logs in on either app.example.io or example.io that he/she is logged in for good, no need to log in twice?
You need to require following modules.
connect-redis
express-session
cookie-parser
Then use the following sample code:
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var app = express();
app.use(cookieParser());
app.use(session({
secret: "thisismysecretkey",
store: new RedisStore({ host: 'localhost', port: 6379})
}));
app.get('/', function (req, res) {
res.send('Hello World!')
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
Source : How to save and retrieve session from Redis
Here is how I did it, this is the most important piece - domain: .yourdomain.io Make sure to have that preceeding dot before your domain.
var express = require('express'),
app = express(),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
expressSession = require('express-session'),
sessionMiddleware = null,
redis = require('redis'),
conn_redis = {
path: '/var/run/redis/redis.sock',
socket_keepalive: true
}
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
const connectRedis = require('connect-redis')(expressSession),
uid = require('uid-safe').sync
sessionMiddleware = expressSession({
store: new connectRedis(conn_redis),
secret: 'xxxxxxxxxxxxxxxxxxxxx',
name: 'session_name',
resave: false,
rolling: true,
saveUninitialized: false,
logErrors: true,
cookie: {
path: '/',
domain: '.yourdomain.io'
expires: new Date(Date.now() + 3600000),
maxAge: 3600000
}
})

Resources