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