@cloudedots/express-session-token
v2.0.0
Published
Express Session Middleware for using tokens as session identifier, without using cookies
Downloads
13
Readme
Token based Express Session
Express Session Middleware for using tokens as session identifier, without using cookies.
Installation
$ npm i --save @cloudedots/express-session-token
Dependencies
You must use a Database store like RedisTokenStore (@cloduedots/redis-token-store
), with this library.
Usage
var express = require('express');
var redis = require('redis');
var RedisTokenStore = require('@cloudedots/redis-token-store');
var session = require('@cloudedots/express-session-token');
// Default expiry time (in seconds)
var ttl = 24 * 60 * 60;
// Redis Client
var redisClient = redis.createClient();
// Redis Token Session Store
var sessionStore = new RedisTokenStore({
client: redisClient,
prefix: 'token-sess:',
ttl: ttl // (in seconds)
});
var app = express();
// Use Session Middleware
app.use('/api', session({
store: sessionStore,
maxAge: ttl * 1000 // (in milliseconds)
}));
// Set data in session
app.post('/api/login', (req, res) => {
// Do your thing
req.session.user = userData; // Set user in session
res.status(200).send('Logged in!');
});
// Update data in Session
app.put('/api/user/:id', (req, res) => {
// Do your thing
for (let token of user.tokens) {
sessionStore.get(token, (err, data) => {
if (err) {
console.error('Error: ', err);
return;
}
console.log('Session : ', data);
delete data.xyz;
data.updatedAt = new Date();
sessionStore.set(token, data);
});
}
res.status(200).send(user);
});
// Destroy Session by ID
app.delete('/api/user/:id', (req, res) => {
// Do your thing
for (let token of user.tokens) {
sessionStore.destroy(token, (err, data) => {
if (err) {
console.error('Error: ', err);
}
});
}
res.status(200).send();
});
// Destroy Session
app.post('/api/logout', (req, res) => {
req.session.destroy(); // Destroy session
res.status(200).send('Logged out!');
});