Permalink
Browse files

Added session expiration.

  • Loading branch information...
gjritter committed Dec 12, 2009
1 parent fec1fee commit 110f65952e01c74c70000d73143266f5e90bb5b4
Showing with 32 additions and 10 deletions.
  1. +1 −1 TODO.md
  2. +4 −2 app.js
  3. +27 −7 nerve.js
View
@@ -1,3 +1,3 @@
# To Do List
-Session Expiration
+Replace hardcoded 30 minute session expiration with something configurable.
View
6 app.js
@@ -1,5 +1,4 @@
var nerve = require("./nerve");
-var sys = require("sys");
// define an application using request matcher/handler pairs
var app = [
@@ -20,9 +19,12 @@ var app = [
// this handler will respond to any request method
[/^\/goodbye$/, function(req, res) {
+ var name = req.session["name"];
+ var message = "Goodbye, " + (name || "I hardly knew thee") + "!";
+
// respond takes an object specifying content and headers,
// and uses sensible defaults if not supplied
- res.respond({content: "Goodbye, " + req.session["name"] + "!", headers: {"Content-Type": "text/plain"}});
+ res.respond({content: message, headers: {"Content-Type": "text/plain"}});
}]
View
@@ -56,16 +56,36 @@ del = function(regexp) {
// what is a better way of differentiating a regexp from a regular function?
return typeof matcher.test === "function";
}
+
+ function get_or_create_session(req, res) {
+ var session_id = req.get_cookie("session_id");
+ if(!session_id) {
+ session_id = idgen.generate_id(22);
+ res.set_cookie("session_id", session_id);
+ }
+ sessions[session_id] = (sessions[session_id] || {
+ session: {},
+ touch: function() {
+ // TODO: replace 30 minute expiration with something configurable
+ this.expiration = (+ new Date) + 10*1000;
+ return this;
+ }
+ }).touch();
+ return sessions[session_id].session;
+ }
+
+ function cleanup_sessions() {
+ for(session_id in sessions) {
+ if((+ new Date) > sessions[session_id].expiration) {
+ delete sessions[session_id];
+ }
+ }
+ }
function create(app) {
+ setInterval(cleanup_sessions, 1000);
function request_handler(req, res) {
- var session_id = req.get_cookie("session_id");
- if(!session_id) {
- session_id = idgen.generate_id(22);
- res.set_cookie("session_id", session_id);
- }
- sessions[session_id] = sessions[session_id] || {};
- req.session = sessions[session_id];
+ req.session = get_or_create_session(req, res);
for(var i = 0; i < app.length; i++) {
var matcher = app[i][0], handler = app[i][1],
match = req.uri.path.match(is_regexp(matcher) ? matcher : matcher.apply(req));

0 comments on commit 110f659

Please sign in to comment.