How to do it...

Let's follow the steps below to create a user session cookie in Express:

  1. First, let's create a new route configuration called routes/session.js. This will contain all the logic needed to read and write our user session using cookies:
var express = require('express');
var router = express.Router();

router.all('*', function(req, res, next) {
var hasSession = req.cookies.session;

if (hasSession) {
req.session = hasSession;
} else {
var newSession = Math.floor(Math.random() *
1000000000);
res.cookie('session', newSession);
req.session = newSession;
}

console.log('Current Session: ', req.session);
next();
});

module.exports = router;
  1. Next, let's add our new session route to our /app.js Express configuration. We will want the session to be handled for every route in our application, so let's put it before the Angular and API configurations. We will also add a cookie secret key so that we can sign and read secure cookies from Express:
...
var cookieParser = require('cookie-parser');

var api = require('./routes/api');
var angular = require('./routes/angular');
var session = require('./routes/session');

...
app.use(cookieParser('my-cookie-secret'));
app.use(session);
app.use('/', angular);
app.use('/api', api);
...
  1. To ensure that our cookies are genuine, we will update our /routes/session.js middleware to only use signed cookies, as follows:
...
router.all('*', function(req, res, next) {
var hasSession = req.signedCookies.session;

if (hasSession) {
req.session = hasSession;
} else {
var newSession = Math.floor(Math.random() * 1000000000);
res.cookie('session', newSession, { signed:
true })
;
req.session = newSession;
}

next();
});
...
  1. Finally, we can add a secret route to our session middleware that will set our user session up as a secret admin role. After setting the admin role, we will redirect it to the Angular application:
...
router.get('/admin', function(req, res, next) {
var adminId = 'super_secret_session';
res.cookie('session', adminId, {signed: true});
req.session = adminId;
res.redirect('/');
});

module.exports = router;
  1. Now, when we visit any route of our application, we will be assigned a session cookie. When we visit localhost:3000/ admin, our session is set to our special admin role, and we are redirected to the Angular application.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.116.50