Skip to content

Instantly share code, notes, and snippets.

@teamon
Created August 17, 2011 20:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teamon/1152512 to your computer and use it in GitHub Desktop.
Save teamon/1152512 to your computer and use it in GitHub Desktop.
import unfiltered.jetty._
import unfiltered.request._
import unfiltered.response._
import unfiltered.filter._
import unfiltered.Cookie
trait AuthService[T]{
def auth(username: String, password: String): Option[T]
}
trait SessionStore[T, S]{
def get(sid: S): Option[T]
def put(data: T): S
}
case class UserSession(username: String)
object SimpleAuthService extends AuthService[UserSession]{
def auth(username: String, password: String) =
if(password == "pass") Some(UserSession(username))
else None
}
object SimpleSessionStore extends SessionStore[UserSession, String] {
private val storage = scala.collection.mutable.Map[String, UserSession]()
def get(sid: String) = storage get sid
def put(data: UserSession) = {
val sid = generateSid
SimpleSessionStore.synchronized {
storage += (sid -> data)
}
sid
}
def dump = storage.toMap
protected def generateSid = scala.util.Random.alphanumeric.take(256).mkString
}
object AuthPlan extends Plan {
val SESSION_KEY = "x2gmx3m0t723mgx40t7823mtgxo"
def intent = {
case Path("/dump") & Cookies(cookies) =>
ResponseString(
"session: " + SimpleSessionStore.dump.toString + "\n" +
"cookies: " + cookies.toString
)
case Path("/secure") & Cookies(cookies) =>
(for {
sid <- cookies(SESSION_KEY)
data <- SimpleSessionStore.get(sid.value)
} yield {
ResponseString("Hello " + data.username)
}) getOrElse {
ResponseString("Go away!")
}
case Path("/login") & Params(par) & Cookies(cookies) =>
(for {
user <- par("user").headOption
pass <- par("pass").headOption
data <- SimpleAuthService.auth(user, pass)
} yield {
ResponseCookies(Cookie(SESSION_KEY, SimpleSessionStore.put(data))) ~> Redirect("/secure")
}) getOrElse {
ResponseString("dupa")
}
}
}
object Server {
def assets = new java.net.URL(getClass.getResource("/public/robots.txt"), ".")
def main(args: Array[String]): Unit = {
Http(8080).context("/assets"){
_ resources assets
}.filter(AuthPlan).run
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment