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 stored in the format: |
|
11 * |
|
12 * visits_counter/hashed_value |
|
13 */ |
|
14 |
|
15 object Application extends Controller { |
|
16 |
|
17 //hash functions: SHA-1, SHA-256, etc |
|
18 def mk_hash(s: String) : String = { |
|
19 val hash_fun = MessageDigest.getInstance("SHA-1") |
|
20 hash_fun.digest(s.getBytes).map{ "%02x".format(_) }.mkString |
|
21 } |
|
22 |
|
23 //extracting from the string .../... the visits |
|
24 //value and hash |
|
25 def gt_cookie(c: Cookie) : Int = c.value.split("/") match { |
|
26 case Array(s, h) if (s.forall(_.isDigit) && mk_hash(s) == h) => s.toInt |
|
27 case _ => 0 |
|
28 } |
|
29 |
|
30 def mk_cookie(i: Int) : Cookie = { |
|
31 val hash = mk_hash(i.toString) |
|
32 Cookie("visits", s"$i/$hash") |
|
33 } |
|
34 |
|
35 def index = Action { request => |
|
36 val visits_cookie = request.cookies.get("visits") |
|
37 val visits = visits_cookie.map(gt_cookie).getOrElse(0) |
|
38 |
|
39 val msg = |
|
40 if (visits >= 10) |
|
41 s"You are a valued customer who has visited this site $visits times." |
|
42 else s"You have visited this site $visits times." |
|
43 |
|
44 Ok(msg).withCookies(mk_cookie(visits + 1)) |
|
45 } |
|
46 } |
|
47 |
|
48 |
|
49 |
|
50 |