This repository has been archived by the owner on Feb 27, 2022. It is now read-only.
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
var tako = require("tako") | ||
, crypto = require("crypto") | ||
, EE = require("events").EventEmitter | ||
|
||
// the default middleware, so it just works. | ||
module.exports = SessionToken | ||
|
||
// make the class act as one itself. | ||
SessionToken.call(SessionToken, "tako-session") | ||
|
||
function SessionToken (tok) { | ||
if (!tok) throw new Error("tako-session needs a token") | ||
if (!(this instanceof SessionToken) && this !== SessionToken) { | ||
return new SessionToken(tok) | ||
} | ||
|
||
var myEE = new EE() | ||
this.on = myEE.on.bind(myEE) | ||
this.emit = myEE.emit.bind(myEE) | ||
|
||
myEE.on("request", function (req, res) { | ||
if (!req.cookies) { | ||
throw new Error("session token requires cookies") | ||
} | ||
var key = req.cookies.get(tok, {signed: true}) | ||
if (!key) { | ||
key = crypto.randomBytes(30).toString("base64") | ||
req.cookies.set(tok, key, {signed: true}) | ||
} | ||
req.session = res.session = key | ||
}) | ||
} |