Skip to content

Repository files navigation

Super Session

The best autentication with token and session on back-end in same module. Made with love to NodeJS.

Installation

$ npm install --save super-session

Guide

Quick usage

Back-end

constexpress=require('express');const{ Router }=require('express');constsuperSession=require('super-session').superSession;constapp=express();constrouter=Router();// Set to use super sessionthis.app.use(superSession.decode());// Create the options objectconstsuperSessionOptions={// Connection is optional, without connection the session will be saved on cacheconnection: {dbUrl: 'your mongo connection',// NecessarydbName: 'your db name (test or production)'// Necessary},secret: 'your secret',// NecessarytokenHeaderName: 'authorization',duration: 15,mult: true,reqAttribute: 'session',collectionName: 'xsessions'};// Configure the super sessionsuperSession.configure(superSessionOptions).then(()=>{createRoutes();});functioncreateRoutes(){// The routes of your app// Get usersrouter.get('/users',function(req,res){// If user is logged, return users' dataif(req.session){// Now you can access all user datareturnres.json([{name: 'Thor',email: 'thor@asgard.com'}]);}res.status(401).json({});// User is not logged});// Loginrouter.get('/users/login',function(req,res){// The role to user make login, check password...// ...// If login it's ok, create the user session// Is necessary use a unique identifier to create the session (_id or email)// Any unique identifier// The session data, put anythingconstsessionData={_id: 'USER_ID',name: 'Thor',email: 'thor@asgard.com',permissions: ['list-users','all']};// Creating the session using the user._idsuperSession.createSession(sessionData._id,sessionData).then((token)=>{returnres.json({userToken: token,userData: sessionData,logged: true});});});// Logoutrouter.get('/users/logout',function(req,res){// If user is logged, make logoutif(req.user){req.session.logout().then(()=>{returnres.json({logged: false});});}else{res.status(401).json({});// User is not logged}});}

Front-end

We will need request to the back-end and get the response, like this. Just example using angular HTTP client

http.post(`${API}/users/login`,{user: 'thor@asgard.com',password: 'loki'}).subscribe((res)=>{storage.set('userToken',res.userToken);// Save the user token on storage});// And last we will get the token on storage and put on headers to each request// To do this, use the interceptor// The header name would be equal the option tokenHeaderName on back-end// Example// ...intercept(req,next){returnObservable.create((obs)=>{consttoken=storage.get('userToken');if(token){constcloneReq=req.clone({setHeaders: {'x-access-token': token}});returnobs.next(next.handle(cloneReq));}returnobs.next(next.handle(req));});}

Why use

It's fast because don't send the user data to front and save a session on cache. It's Safe because save the session on your database. And have few options to use and control multiples sessions or a unique session by user.

Configure

Configure the super session, will need configure in express file

// Set to use super sessionthis.app.use(superSession.decode());// Create the options objectconstsuperSessionOptions={connection: {dbUrl: 'your mongo connection',dbName: 'your db name (test or production)'},secret: 'your secret',// any wordtokenHeaderName: 'authorization',duration: 15,mult: true,reqAttribute: 'session',collectionName: 'xsessions'};// Configure the super sessionsuperSession.configure(superSessionOptions).then(()=>{// Continue your server configuration// ...});

Options

Avaliable bellow options to configure the super session

{
// Connection is optional, without connection the session will be saved on cache
"connection": {
"dbUrl": "your mongo connection", // Necessary
"dbName": "your db name (test, production or ETC.)" // Necessary
},
// Necessary
"secret": "your secret", // Optional, default is authorization
"tokenHeaderName": "authorization",
// Optional, default is 14 days
"duration": 15, // days
// Optional, default is false
// When true, the user can log in many devices and all sessions will be active
"mult": true, // Opitional, default is session. Can be change to any word.
// If change to user, the session data will be in req.user
"reqAttribute": "session",
// Optional, default is sessions. The collection name that store the sessions
"collectionName": "xsessions"
}

Decode

Set to use the super session decode on express app

// The server need this to decode the token of userthis.app.use(superSession.decode());

Create session

It's necessary use a unique identifier to create the session, _id, email ETC. as a unique identifier

// The session data, put anythingconstsessionData={_id: 'USER_ID',name: 'Thor',email: 'thor@asgard.com',permissions: ['list-users','all']};superSession.createSession(sessionData._id,sessionData).then((token)=>{console.log('userToken',token);});

Delete user sessions

We've used the 'user id' to delete all user sessions

superSession.deleteUserSessions('USER_ID').then(()=>{console.log('Delete all sessions of user USER_ID');});

Logout

To user logout, just check exist the session and call req.session.logout() (It's a promise)

router.get('/users/logout',function(req,res){// If user is logged, make logoutif(req.user){req.session.logout().then(()=>{returnres.json({logged: false});});}else{res.status(401).json({});// User is not logged}});

Tests

To run the test suite, first install the dependencies, then run npm run test:

$ npm install
$ npm run test

Related projects

express-session

License

MIT

About

The best autentication with token and session on back-end in same module. Made with love to NodeJS.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages