Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Use new tako middle-less api

  • Loading branch information...
commit 090bbda9d7bd85c5fd5aa7c2b714aa4f8ccc2b62 1 parent 4095155
@isaacs authored
Showing with 28 additions and 17 deletions.
  1. +6 −3 README.md
  2. +22 −14 token.js
View
9 README.md
@@ -6,10 +6,13 @@ Just a session token middleware for Tako. Works great with
## Usage
```javascript
-// various tako stuff...
+var sessionToken = require("tako-session-token")
-var SessionToken = require("tako-session-token")
-app.middle(new SessionToken("my-happy-app"))
+// use the default token of "tako-session"...
+app.on("request", sessionToken)
+
+// or define one of your own
+app.on("request", sessionToken("myapp-session"))
// later...
app.route("/foo", function (req, res) {
View
36 token.js
@@ -1,24 +1,31 @@
var tako = require("tako")
, crypto = require("crypto")
-, EE = require("events").EventEmitter
// the default middleware, so it just works.
-module.exports = SessionToken
+module.exports = sessionToken
-// make the class act as one itself.
-SessionToken.call(SessionToken, "tako-session")
+var handlers = {}
+, defaultKey = "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)
- }
+// call once to set up the default
+sessionToken()
- var myEE = new EE()
- this.on = myEE.on.bind(myEE)
- this.emit = myEE.emit.bind(myEE)
+function sessionToken (req, res) {
+ var tok = defaultKey
+ if (typeof req === "object" && typeof res === "object") {
+ return handler(tok)(req, res)
+ } else {
+ if (typeof req === "string" || Buffer.isBuffer(req)) {
+ tok = String(req)
+ }
+ if (!tok) throw new Error("tako-session needs a token")
+ return handler(tok)
+ }
+}
- myEE.on("request", function (req, res) {
+function handler (tok) {
+ handlers[tok] = handlers[tok] || function handle (req, res) {
+ if (!tok) throw new Error("tako-session needs a token")
if (!req.cookies) {
throw new Error("session token requires cookies")
}
@@ -28,5 +35,6 @@ function SessionToken (tok) {
req.cookies.set(tok, key, {signed: true})
}
req.session = res.session = key
- })
+ }
+ return handlers[tok]
}
Please sign in to comment.
Something went wrong with that request. Please try again.