diff -r 22f027da67ec -r 9c968d0de9a0 progs/scala/Application4.scala --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/progs/scala/Application4.scala Sat Oct 04 12:46:04 2014 +0100 @@ -0,0 +1,52 @@ +package controllers + +import play.api.mvc._ +import java.security.MessageDigest + +/* + * Application sets a cookie in plain ASCII on the + * clients browser recording the visits of a page. + * + * The cookie data is hashed and salted with a + * secret key. + */ + + +object Application extends Controller { + + //secret key for salting + val salt = "my secret key" + + //SHA-1 + salt + def mk_hash(s: String) : String = { + val hash_fun = MessageDigest.getInstance("SHA-1") + hash_fun.digest((s + salt).getBytes).map{ "%02x".format(_) }.mkString + } + + def gt_cookie(c: Cookie) : Int = c.value.split("/") match { + case Array(s, h) if (s.forall(_.isDigit) && mk_hash(s) == h) => s.toInt + case _ => 0 + } + + def mk_cookie(i: Int) : Cookie = { + val hash = mk_hash(i.toString) + Cookie("visits", s"$i/$hash") + } + + def index = Action { request => + + val visits_cookie = request.cookies.get("visits") + val visits = visits_cookie.map(gt_cookie).getOrElse(0) + + val msg = + if (visits >= 10) + s"You are a valued customer who has visited this site $visits times." + else s"You have visited this site $visits times." + + Ok(msg).withCookies(mk_cookie(visits + 1)) + } +} + + + +