When user login, i am storing data in session like this :
req.session.user = userData;
And it is working fine but when i restart in nodejs, the session is null. Then user need to login again.
I want to create a file based storage for session.But after a lot of search, i got the way to store data in database but i dont want to store session data in database. I want to store data in file.
Is there a nodejs module to store the session data in file?
You can use session-file-store. can refer below working example.
var express = require('express');
var app = express();
var session = require('express-session');
var FileStore = require('session-file-store')(session);
app.use(session({ secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
store: new FileStore,
cookie: { maxAge: 3600000,secure: false, httpOnly: true }
})
);
app.get('/', function (req, res) {
if (req.session.views) {
req.session.views++;
res.setHeader('Content-Type', 'text/html');
res.write('<p>views: ' + req.session.views + '</p>');
res.end();
} else {
req.session.views = 1;
res.end('Welcome to the file session demo. Refresh page!');
}
});
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);
});
You can try connect-fs2.
var FSStore = require('connect-fs2')(express);
var options = { dir='./mySessionFolder' }; // specify your directory to store your session files
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
store: new FSStore(options), // use it as your store
secret: 'your secret',
cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 } // 1 week
}));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
Butt isn't it something like whenever we logedin session data is store in file and we at the moment we logout session data which are store in file they may get delete...
its not a good idea to write session data in file , because you need to stores as key , value pair and have to parse it. if the user logout you need to delete particular session from file (otherwise the file may goes out of memory)
you say , you have stored session data in db , you need to add additional status information as key value pair in db. that status should only become false when the user terminates the seesion or session timeouts , otherwise it remains true even if server restart.with reference with this status you can hold the users.
Related
Using express-session and storing session in files. However every request it is creating new session id and new file is getting created.
Here is the code which i am using to create the session.
app.use(session({ secret: 'keyboard cat',
resave: false,store: new FSStore(options),
saveUninitialized: false ,
cookie: { maxAge: 1000,secure: false,httpOnly: true }
}))
However i want it should create a single session id for each user or until session expires.
My issue was with MaxAge which I set it 1000 milliseconds i.e 1 sec. Therefore it was creating a new session id everytime. I have set it to 1 hour, it works fine.
Here is the complete code
var express = require('express');
var app = express();
var session = require('express-session');
var FileStore = require('session-file-store')(session);
app.use(session({ secret: 'keyboard cat',
resave: false,
store: new FileStore,
saveUninitialized: false ,
cookie: { maxAge: 3600000,secure: false, httpOnly: true }
})
);
app.get('/', function (req, res) {
if (req.session.views) {
req.session.views++;
res.setHeader('Content-Type', 'text/html');
res.write('<p>views: ' + req.session.views + '</p>');
res.end();
} else {
req.session.views = 1;
res.end('Welcome to the file session demo. Refresh page!');
}
});
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);
});
I used Redis to store session in my nodejs server. This is my code:
var express = require('express');
var http = require('http');
var connect = require("connect");
var path = require('path');
var RedisStore = require("connect-redis")(express);
var redis = require("redis").createClient();
var app = express();
app.set('port', 8888);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.session({secret: 'blues',
cookie: { secure: true },
store: new RedisStore({
host: 'localhost',
port: 6379,
client: redis })
}));
app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', require('ejs').renderFile);
app.get('/login', function(req,res){
res.render('login.html', {title: 'Login'});
});
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
When I run the server, and access the url http://localhost:8888/login, then come back to check the Redis server, I found 3 sessions saved there, like this
127.0.0.1:6379> keys *
1) "sess:DGtMAO3pRPExzPjFS_B07bXP"
2) "sess:bzPTRrlXXe1DhzNze0JdZswt"
3) "sess:-RM8kkNtJ0jj3nhuYmiuw0f6"
What does it mean? Why 3 sessions (I had double-check with FLUSHDB command)?
EDIT: Ok I have some test and it turns out the other two sessions is from a css and a js file in login.html. But there are something I don't understand that when I press F5, 3 new session is stored in Redis. Why is that? Didn't session stay the same until it expire?
Another problem is, with above code how can I retrieve the session saved in Redis? I used this:
redis.get('"sess:' + req.session.id + '"', function(err, result){
console.log("Get session: " + util.inspect(result,{ showHidden: true, depth: null }));
});
it return null, although I can retrieve it with the same req.session.id in Redis server.
Please help me. Thank you!
I'm trying get access to session data in express so I thought I would try declaring a connect-redis session store when configuring express. However, I cannot see why this doesn't work:
var express = require('express');
var http = require('http');
var RedisStore = require('connect-redis')(express);
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));
//app.use(express.session({ secret: "keyboard cat" }));
app.use(app.router);
app.get('/', function(req, res){
console.log('/');
req.session.items = [ 'apple', 'orange' ];
res.end('items configured');
});
app.get('/items', function(req, res){
console.log('/items: ', req.session.items);
var s = JSON.stringify(req.session.items);
res.end('items: ' + s);
});
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The '/' route simply configures items with the session.
The '/items' route displays the list of items in the session.
It works using the standard expressjs session store.
It doesn't work using connect-redis (req.session is undefined)
I'm assuming the redis store will be instantiated and destroyed as the app loads/unloads (or do I need it running outside of node/express app?)
Any ideas?
req.session will be undefined if RedisStore can't connect to your Redis server. So it's either not running, or it's not running on the default location that RedisStore is looking for it (127.0.0.1:6379).
In case of the latter, you can configure the location using the options argument to the RedisStore constructor.
Give this a try.
var express = require('express');
var redis = require("redis");
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var bodyParser = require('body-parser');
var client = redis.createClient();
var app = express();
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.use(session({
secret: 'ssshhhhh',
// create new redis store.
store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl : 260}),
saveUninitialized: false,
resave: false
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/',function(req,res){
// create new session object.
if(req.session.key) {
// if email key is sent redirect.
res.redirect('/admin');
} else {
// else go to home page.
res.render('index.html');
}
});
app.post('/login',function(req,res){
// when user login set the key to redis.
req.session.key=req.body.email;
res.end('done');
});
app.get('/logout',function(req,res){
req.session.destroy(function(err){
if(err){
console.log(err);
} else {
res.redirect('/');
}
});
});
app.listen(3000,function(){
console.log("App Started on PORT 3000");
});
link : https://codeforgeek.com/2015/07/using-redis-to-handle-session-in-node-js/
You should invoke RedisStore constructor (with ())
app.use(express.session({ secret: "keyboard cat", store: new RedisStore()}));
I have written a simple cms in nodejs using expressjs framework. I used passportjs for authentication using twitter. below is my app.configure:
app.configure(function(){
//views
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
//parse request bodies
app.use(express.bodyParser());
app.use(express.methodOverride());
// session support
app.use(express.cookieParser(cfg.cookie_secret));
app.use(express.session({
key : 'whynode',
store : sessionStore,
cookie: {
expires: new Date(Date.now() + 60 * 10000),
maxAge: 60*10000
}
}));
app.use(passport.initialize());
app.use(passport.session());
//pass user data
app.use(function(req, res, next) {
res.locals.req_path = req.path;
res.locals.user = req.user || false;
next();
});
//get routers
app.use(app.router);
//serve asset files
app.use('/assets', express.static(__dirname + '/public'));
});
I used redis for session store. full app.js code can be viewed here full app.js
What I am now experiencing is when I leave app unused for some minutes, session expires and I need to login again. How do we make so that session doesnot timeout for atleast 2-3 hours of inactivity?
Adjust this code:
cookie: {
expires: new Date(Date.now() + 60 * 10000),
maxAge: 60*10000
}
That sets the expiry for your session to 10 minutes. You don't need to use both maxAge or expires, one will suffice (the difference is that expires uses a Date instance and maxAge just means expire X milliseconds from now).
For RedisStore you can set disableTTL to true. Keys will stay in redis until evicted by other means.
var sessionStore = new RedisStore({client: rClinet, disableTTL: true})
I'm working on a Google Chrome extension with a popup, in which I load a page from a node.js + express.js server. The page I load changes depending on the status of the req.session.user in this way:
app.get('/', function(req, res){
if(req.session.user){
res.render(__dirname + '/pages/base.jade', {});
}
else{
res.render(__dirname + '/pages/login_register.jade', {});
}
});
If req.session.user is null I send a page in which the user can do the login or register. If he/she does a login, this is what happens in the server:
app.post('/login', function(req, res){
var user = {};
user.username = req.body.username;
user.password = req.body.password;
checkLogin(user, function(foundUser){
//login correct
console.log("login!");
req.session.user = foundUser;
res.render(__dirname + '/pages/base.jade', {
});
});
});
So if the user logs in correctly req.session.user should be set with the credentials of the current user. The problem is that once I log in and then close the popup of the Chrome extension, whenever I reopen it I still receive the login page.
My question is: does the popup supports session storage in the express.js server? If yes, then there is something wrong with my code, can anyone point out what am I doing wrong? Thanks.
EDIT:
This is how I setup the server:
var app = express.createServer(
express.logger(),
express.cookieParser(),
express.session({ secret: 'keyboard cat' })
);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
I might be doing something redundant here, since I still don't have a deep understanding of how that works.
The problem is how you have set up your server - you're using the cookieParser and session middlewares twice:
var app = express.createServer(
express.logger(),
express.cookieParser(),
express.session({ secret: 'keyboard cat' })
);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
You should only use either middlewares as parameters to createServer, or use, so:
var app = express.createServer();
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
Popup page probably reloads every time you open it. You should create a backgroundpage for your extension where you could store/manage sessions. Then you can communicate from popup to backgroundpage passing messages docs. Using messaging you can send login data to backgroundpage and also ask whether user has already logged in.