progs/Application3.scala
author Christian Urban <christian dot urban at kcl dot ac dot uk>
Thu, 25 Sep 2014 06:43:43 +0100
changeset 178 13c6bd6e3477
parent 103 bd6e45c7aa8d
permissions -rw-r--r--
updated

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 stored in the format:
 *
 * visits_counter/hashed_value 
 */

object Application extends Controller {

  //hash functions: SHA-1, SHA-256, etc
  def mk_hash(s: String) : String = {
    val hash_fun = MessageDigest.getInstance("SHA-1")
    hash_fun.digest(s.getBytes).map{ "%02x".format(_) }.mkString
  }

  //extracting from the string .../... the visits
  //value and hash
  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))
  }     
}