progs/scala/app4.scala
author Christian Urban <christian dot urban at kcl dot ac dot uk>
Sat, 04 Oct 2014 12:46:04 +0100
changeset 197 9c968d0de9a0
parent 98 progs/app4.scala@3d585e603927
permissions -rw-r--r--
moved old scala files into a subdirectory

object Application extends Controller {

  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 => ... }
}