programs/Application4.scala
changeset 13 2bd3530c30af
equal deleted inserted replaced
12:621301c1cb63 13:2bd3530c30af
       
     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 and salted with a
       
    14  * secret key.
       
    15  */
       
    16 
       
    17 
       
    18 object Application extends Controller {
       
    19 
       
    20   //secret key for salting - this key should not be
       
    21   //sent to the client; the key should normally be
       
    22   //a unguessable random number generated once
       
    23   val salt = "my secret key"
       
    24 
       
    25   //SHA-1 + salt
       
    26   def mk_hash(s: String) : String = {
       
    27     val hash_fun = MessageDigest.getInstance("SHA-1")
       
    28     hash_fun.digest((s + salt).getBytes).map{ "%02x".format(_) }.mkString
       
    29   }
       
    30 
       
    31   def gt_cookie(c: Option[Cookie]) : Int = 
       
    32     c.map(_.value.split("/")) match {
       
    33       case Some(Array(s, h)) 
       
    34         if (s.forall(_.isDigit) && mk_hash(s) == h) => s.toInt 
       
    35       case _ => 0
       
    36     }
       
    37 
       
    38   def mk_cookie(i: Int) : Cookie = {
       
    39     val s = i.toString
       
    40     Cookie("visits", s + "/" + mk_hash(s))
       
    41   }
       
    42    
       
    43   def index = Action { request =>
       
    44 
       
    45     val visits_cookie = request.cookies.get("visits")
       
    46     val visits = gt_cookie(visits_cookie)
       
    47 
       
    48     val msg1 = "You are a valued customer who has visited this site %d times."
       
    49     val msg2 = "You have visited this site %d times."
       
    50     val msg = 
       
    51       if (visits >= 10) msg1.format(visits) else msg2.format(visits)
       
    52     
       
    53     Ok(msg).as(HTML).withCookies(mk_cookie(visits + 1))
       
    54   }     
       
    55 }
       
    56 
       
    57 
       
    58 
       
    59