redis-jwt
Management of sessions by Redis and JWT for horizontal scalability, with the possibility of having one session at a time or multiple for the same user
Requirements
- Nodejs >= 6.x.x (Recommended 8.x.x)
- Redis >= 3.x.x (Recommended 4.x.x)
Installation
Npm
npm install redis-jwt --save
Yarn
yarn add redis-jwt
Usage
import RedisJWT from 'redis-jwt';
const r = new RedisJWT({
host: '127.0.0.1',
port: 6379,
maxretries: 10,
db: 0,
secret: 'secret_key',
multiple: false,
kea: true
});
r.sign('507f191e810c19729de860ea').then(token => {
r.verify(token).then(result => {
}).catch(err => {
});
});
Example Redis-jwt with Express
import RedisJWT from 'redis-jwt';
import express from 'express';
const r = new RedisJWT();
const app = express();
app.get('/login', (req, res) => {
r.sign('507f191e810c19729de860ea', {
ttl: '15m',
data: { hello: 'world' },
request: req
}).then(token => {
res.json({token});
});
});
app.get('/me', mw(), (req, res) => {
res.json(req.user);
});
function mw() {
return (req, res, next) => {
const token = req.headers['authorization'];
r.verify(token).then(rjwt =>
req.user = rjwt;
next();
}).catch(err => {
res.status(401).json({err})
})
}
}
app.listen(3000, () => console.log('Server listening on port 3000!'));
Events
r.on('ready', () => {
console.log('redis-jwt-> ready!');
});
r.on('connected', () => {
console.log('redis-jwt-> connected!');
});
r.on('disconnected', () => {
console.log('redis-jwt-> disconnected!');
});
r.on('error', (err) => {
console.log('redis-jwt-> error!', err);
});
Options
Sign
r.sign('507f191e810c19729de860ea').then(token => {
});
r.sign('507f191e810c19729de860ea', {
ttl: '15m'
}).then(token => {
});
r.sign('507f191e810c19729de860ea', {
data: { hello: 'world' }
}).then(token => {
});
r.sign('507f191e810c19729de860ea', {
request: req
}).then(token => {
});
r.sign('507f191e810c19729de860ea', {
ttl: '15m',
data: { hello: 'world' },
request: req
}).then(token => {
});
Verify
r.verify(token).then(result => {
}).catch(err => {
})
r.verify(token, true).then(result => {
}).catch(err => {
})
Exec
var exec = r.exec();
exec.rawCall(['keys', `507f191e810c19729de860ea:*`], (err, result) => {
});
Call
var call = r.call();
call.ping().then..
call.create(key, value, ttl).then..
call.exists(key).then..
call.ttl(key).then..
call.getValueByKey(key).then..
call.getValuesByPattern(pattern).then..
call.getCountByPattern(pattern).then..
call.getInfo(section).then..
call.destroy(key).then..
call.destroyMultiple(key).then..
Development
Start
npm start
Serve
npm run serve
Build
npm run build
Test
npm test
License
MIT © Leonardo Rico