session-se

This is a simple way how to handle session through encrypted cookies.

Usage no npm install needed!

<script type="module">
  import sessionSe from 'https://cdn.skypack.dev/session-se';
</script>

README

Session SE

npm CircleCI Coverage Status

Introduction

This is a simple way how to handle session through encrypted cookies. In this implementation, entire session information is preserved through secure cookies and system does not have any reliance on memory or other data store. You can restart your application or scale out to any number of servers and all will be able to function properly.

How to use?

First you need to install this module.

npm install session-se

Then, you need to add middleware to your pipeline.

const session = require('session-se');
app.use(session({
  cookie: { name: 'myapp_sid' },
  secret: 'mdflkebfiasdfjfjed#$sd',
  duration: 20, // 20 minutes
  expiration: 8*60 // 8 hours
}));

How to check if user is authenticated?

There are two scenarios:

  • UI
  • API

For the first one, we need to send code 401 and redirect user to login.

const authorize = (req, res, next) => {
  if (req.user)
    next();
  else
    res.status(401).redirect('/login');
};

In the second one, we should not redirect but just send code 401 Unauthorized.

const authorizeApi = (req, res, next) => {
  if(!req.user)
    res.status(401).end('Unauthorized');
  else
    next();
};

So, when you need to authorize some middleware, just add your function this way:

// Adding something that does not need authorization
app.use('/', usersRouter);

// Adding some UI that needs authorization
app.use('/secured-something', authorize, securedReouter);

// Adding some API that needs authorization
app.use('/api', authorizeApi, apiRouter);

How to do Login and Logout?

This is an example, your case can differ. I created a router named login.js;

const express = require('express');
const router = express.Router();

router.get('/login', (req, res) => {
  res.render('login');
});

router.get('/api/logout', (req, res) => {
  req.registerUser(null);
  res.status(200).send('Done');
});

router.post('/api/login', async (req, res) => {
  if(req.body.username === 'myunsername'
     && req.body.password === 'MyPassword') {
    await req.registerUser({ name: 'Dr Jekyll' });
    res.status(201).send('Created');
  }
  else
    res.status(401).send('Authentication Failed');
});

module.exports = router;

P.S. Do not forget that login should be available without authorization or you will end up in a loop.

Options

Name Description Default
secret Encryption secret REQUIRED N/A
secretSalt Encryption secret salt safawo$lfnfrn34r-fac
duration Session duration in minutes 20
expiration Absolute session expiration in minutes 480 (8 hours)
cookie.name Cookie name sid
cookie.httpOnly Cookie httpOnly flag true
cookie.secure Cookie secure flag false
cookie.domain Cookie domain null (meaning it will set current domain)
cookie.path Cookie path /

Contact

Image