equal
deleted
inserted
replaced
|
1 package controllers |
|
2 |
|
3 import play.api.mvc._ |
|
4 import java.security.MessageDigest |
|
5 |
|
6 /* |
|
7 * Application sets a cookie in plain ASCII on the |
|
8 * clients browser recording the visits of a page. |
|
9 * |
|
10 * The cookie data is hashed and salted with a |
|
11 * secret key. |
|
12 */ |
|
13 |
|
14 |
|
15 object Application extends Controller { |
|
16 |
|
17 //secret key for salting |
|
18 val salt = "my secret key" |
|
19 |
|
20 //SHA-1 + salt |
|
21 def mk_hash(s: String) : String = { |
|
22 val hash_fun = MessageDigest.getInstance("SHA-1") |
|
23 hash_fun.digest((s + salt).getBytes).map{ "%02x".format(_) }.mkString |
|
24 } |
|
25 |
|
26 def gt_cookie(c: Cookie) : Int = c.value.split("/") match { |
|
27 case Array(s, h) if (s.forall(_.isDigit) && mk_hash(s) == h) => s.toInt |
|
28 case _ => 0 |
|
29 } |
|
30 |
|
31 def mk_cookie(i: Int) : Cookie = { |
|
32 val hash = mk_hash(i.toString) |
|
33 Cookie("visits", s"$i/$hash") |
|
34 } |
|
35 |
|
36 def index = Action { request => |
|
37 |
|
38 val visits_cookie = request.cookies.get("visits") |
|
39 val visits = visits_cookie.map(gt_cookie).getOrElse(0) |
|
40 |
|
41 val msg = |
|
42 if (visits >= 10) |
|
43 s"You are a valued customer who has visited this site $visits times." |
|
44 else s"You have visited this site $visits times." |
|
45 |
|
46 Ok(msg).withCookies(mk_cookie(visits + 1)) |
|
47 } |
|
48 } |
|
49 |
|
50 |
|
51 |
|
52 |