forked from treygriffith/connect-mongodb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
example.js
75 lines (63 loc) · 2.16 KB
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Module dependencies.
*/
var sys = require('sys'),
http = require('http'),
connect = require('connect'),
mongoStore = require('./index');
http.IncomingMessage.prototype.flash = function(type, msg){
var msgs = this.session.flash = this.session.flash || {};
if (type && msg) {
(msgs[type] = msgs[type] || []).push(msg);
} else if (type) {
var arr = msgs[type];
delete msgs[type];
return arr || [];
} else {
this.session.flash = {};
return msgs;
}
};
// Expire after two minutes
var mongoStore = mongoStore({ maxAge: 60000 * 2 });
connect.createServer(
// Always before session!
connect.bodyDecoder(),
// session requires cookieDecoder
connect.cookieDecoder(),
// Pass custom session store
connect.session({ store: mongoStore }),
// Ignore favicon
function(req, res, next){
if (req.url === '/favicon.ico') {
res.writeHead(404, {});
res.end();
} else {
next();
}
},
// Increment views
function(req, res){
req.session.count = req.session.count || 0
++req.session.count;
// Display online count
req.sessionStore.length(function(err, len){
if (req.session.count < 10) {
var msgs = req.flash('info').join('\n');
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(msgs);
res.write('<form method="post"><input type="hidden" name="foo" value="bar" /><input type="submit" value="POST request!" /></form>');
res.write('<p>online : ' + len + '</p>');
res.end('<p>views: ' + req.session.count + '</p>');
} else {
// regenerate session after 10 views
req.session.regenerate(function(){
req.flash('info', 'sess key is now <strong>' + req.sessionHash + '</strong>');
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('regenerated session');
});
}
});
}
).listen(3000);
sys.puts('Connect server started on port 3000');