A redis session for Koa that creates sets for specific values.
Use-case: you want to know all the sessions related to a user so that if the user resets his/her password, you destroy all the sessions.
Specifics:
- Stores sessions as hash sets
- Stores cross references as sets
- Functional API
const app = require('koa')()
const client = require('ioredis').createClient()
const Session = require('koa-redis-session-sets')(app, {
client,
references: {
user_id: {} // options object for future use, maytbe
}
})
app.use(Session)
app.use(function * (next) {
// get the session
let session = yield this.session.get()
// update the session
yield this.session.set({
user_id: 1
})
// update the session object with latest keys
session = yield this.session.get()
this.status = 204
})
Here's an example of deleting all the sessions associated with user_id: 1
.
You have to do it yourself because handling it would be too opinionated.
Specifically, if this set is possibly large, you'd want to use SSCAN
.
const key = Session.getReferenceKey('user_id', 1)
client.smembers(key).then(session_ids => {
return Promise.all(session_ids.map(session_id => {
// deletes the session and removes the session from all the referenced sets
return Session.store.delete(session_id)
}))
}).catch(err => {
console.error(err.stack)
process.exit(1)
})
Creates a new session middleware instance.
Options:
client
-ioredis
clientreferences
- fields to referencemaxAge
- max age of sessions, defaulting to28 days
prefix
- optional key prefixbyteLength
- optional byte length for CSRF tokens
Use the session middleware in your app. Note that this is a very simple function and middleware is not required. Look at the source code to understand how simple it is.
A Koa v2 version of the middleware.
Create your own session object from a context.
Get the key
for a redis set
that contains all the session ids related to a field:value
pair.
Use client.smembers(key)
to get all the session ids.
Session is ctx.session
.
Get the key for the redis hash
for use with client.hgetall(key)
.
Get the session, optionally with select fields.
Set specific fields in the session. Does not return the new session.
Remove specific fields in the session. Does not return the new session.
Update the session, updating the cookies and the session expire time.
Deletes the session.
Does not create a new one.
Execute const session = await ctx.session.get()
to create a new one
Create a CSRF token.
Returns a boolean of whether a CSRF token is valid.
The Store
is the underlying redis logic of the session.