How to send a var to router - node.js

Maybe in express, there are some thing changed. But I don't know how to send the session:
var session = require('express-session');
app.use('/', routes);
to another .js file router.
var express = require('express');
var router = express.Router();
module.exports = router;

generally seesion we configure in configure section like this
var express = require('express')
var parseurl = require('parseurl')
var session = require('express-session')
var app = express()
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))
in controller level we can access the session like
req.session
we can access seesion
to regenerate the session
req.session.regenerate(function(err) {
// will have a new session here
})
destroy seesion
req.session.destroy(function(err) {
// cannot access session here
})
store the value in session
req.session.key = value;
retrieving value from session
req.session.key
refer the given link
https://github.com/expressjs/session
we can pass api object to route configuration like this ;
var api = require('express');
require('../api/routes/authorization.routes.js')(api);
in route configuration
module.exports = function (api) {
api.route('/api/authorization/token')
.post( authorization.token);
};

Related

firebase express-session dosn't store nothing in the cookies

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
...

express.js sharing the session from websocket to http

I can't find a way how to read in the .get() block the specific session value, that was assigned in the .ws() block recently:
const express = require('express');
const app = express();
const ws = require('express-ws')(app);
const session = require('express-session');
app.use(session({secret: 'secret', resave: true, saveUninitialized: true}));
app.get('/', function(req, res) {
console.log(req.session.val) //undefined (would like to have "my value")
res.end("<script>var ws = new WebSocket(window.location.href.replace('http', 'ws')); ws.send(true);</script>");
})
.ws('/', function(ws, req) {
//trying to assign session
req.session.val = 'my value';
});
app.listen(80);
Please, help.

Implement cookie based authentication in Node JS with Passport

Below is my server.js (app.js). I am using express with passport, for user authentication. But whenever I restart my node server user logsout.
I am very new to nodejs, I was wondering how I could implement a cookie based authentication. So that user does not log out even if the server starts. I'm sure theres some config change which I have not able to find.
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 80;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'yassers' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
Its logout when you restart your start because its stored in MemoryStore(RAM). Use mongoStore to store your session mongodb. Try below code:
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var mongoStore = new MongoStore({
url: 'your mongo db url'
});
app.use(session({
secret: 'your secret',
saveUninitialized: true, // don't create session until something stored
resave: false, //don't save session if unmodified
store: mongoStore,
cookie: {
domain: 'domain name',
maxAge: 1000 * 24 * 60
}
}));

Redis with express and passport

I am trying to using Redis with my exsiting application
Here is my app.js code
var express = require('express'),
request = require('request'),
http = require('http'),
path = require('path');
var app = express();
var routes = require('./routes');
var passport = require('passport');
var flash = require('connect-flash');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var busboy = require('connect-busboy');
var policies = require('./policies/admin');
var config = require('./config');
require('./libs/passport')(passport);
app.configure(function () {
app.use(express.session({ secret: 'secertkey', cookie: { maxAge : 2592000000 } })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
});
Which is working fine.
I want to use Rediss along with passport,
Is this possible and how can i do
Thanks
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'
}));
for reference
https://www.npmjs.com/package/connect-redis

how to create different session on url based in nodejs?

Our site have two section :
1. admin (content management)
2. site
Admin section will have url '/admin' and site section have url '/'.
Example : My site name is www.example.com, then admin section url is "www.example.com/admin" and site url is "www.example.com".
I want to create url based session means request from admin section will have different session than request from site section.
How can i do it?
Assuming you're using express, you can separate your routers for your routes and apply the session middleware to each router.
routes/index.js
var express = require('express'),
router = express.Router(),
session = require('express-session');
router.use(session({
secret: 'index route secret',
resave: false,
saveUninitialized: true
}));
module.exports = router;
routes/admin.js
var express = require('express'),
router = express.Router(),
session = require('express-session');
router.use(session({
secret: 'admin route secret',
resave: false,
saveUninitialized: true
}));
module.exports = router;
app.js
var express = require('express'),
app = express();
app.use('/', require('./routes/index'));
app.use('/admin', require('./routes/admin'));
app.listen(3000);
documentation

Resources