equal
deleted
inserted
replaced
|
1 var express = require('express'); |
|
2 var cookie = require('cookie-parser') |
|
3 var crypto = require('crypto'); |
|
4 |
|
5 var app = express(); |
|
6 app.use(cookie()); |
|
7 |
|
8 var salt = 'secret key' |
|
9 |
|
10 function mk_hash(s) { |
|
11 return crypto.createHash('sha1').update(s).digest('hex') |
|
12 } |
|
13 |
|
14 function mk_cookie(c) { |
|
15 return c.toString() + '-' + mk_hash(c.toString() + salt) |
|
16 } |
|
17 |
|
18 function gt_cookie(s) { |
|
19 var splits = s.split("-", 2); |
|
20 var counter = parseInt(splits[0]) |
|
21 var hash = splits[1] |
|
22 if (mk_hash(counter.toString() + salt) == hash) { |
|
23 return counter |
|
24 } else { |
|
25 return 0 |
|
26 } |
|
27 } |
|
28 |
|
29 |
|
30 app.get('/', function(req, res){ |
|
31 var counter = gt_cookie(req.cookies.counter) || 0; |
|
32 res.cookie('counter', mk_cookie(counter + 1)); |
|
33 if (counter >= 5) { |
|
34 res.write('You are a valued customer ' + |
|
35 'visting the site ' + counter + ' times.'); |
|
36 } else { |
|
37 res.write('This is visit number '+ counter +'!'); |
|
38 } |
|
39 res.end(); |
|
40 }); |
|
41 |
|
42 // starting the server |
|
43 app.listen(8000); |
|
44 console.log("Server running at http://127.0.0.1:8000/"); |