var express = require('express');
var cookie = require('cookie-parser')
var crypto = require('crypto');
var app = express();
app.use(cookie());
var salt = 'secret key'
function mk_hash(s) {
return crypto.createHash('sha1').update(s).digest('hex')
}
function mk_cookie(c) {
return c.toString() + '-' + mk_hash(c.toString() + salt)
}
function gt_cookie(s) {
var splits = s.split("-", 2);
var counter = parseInt(splits[0])
var hash = splits[1]
if (mk_hash(counter.toString() + salt) == hash) {
return counter
} else {
return 0
}
}
app.get('/', function(req, res){
var counter = gt_cookie(req.cookies.counter) || 0;
res.cookie('counter', mk_cookie(counter + 1));
if (counter >= 5) {
res.write('You are a valued customer ' +
'visting the site ' + counter + ' times.');
} else {
res.write('This is visit number '+ counter +'!');
}
res.end();
});
// starting the server
app.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");