Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package x
import unfiltered.request._
import unfiltered.response._
import unfiltered.Cookie
import unfiltered.filter._
import javax.servlet.{Filter, FilterConfig, FilterChain, ServletRequest, ServletResponse}
import javax.servlet.http.{HttpServletRequest, HttpServletResponse, HttpServletRequestWrapper}
import java.security.Principal
case class HtmlBody(nodes: scala.xml.NodeSeq) extends
ComposeResponse(HtmlContent ~> ResponseString((<html><body>{nodes}</body></html>).toString)) {
def this(text: String) = this(<p>{text}</p>)
}
object HtmlBody { def apply(text: String) = new HtmlBody(text) }
case class RequestSwap(req: RequestBinding) extends ResponseFunction[Any] { def apply[T](res: HttpResponse[T]) = res; }
trait PlanWithRequestSwap extends Plan {
override def doFilter(request: ServletRequest,
response: ServletResponse,
chain: FilterChain) {
(request, response) match {
case (hreq: HttpServletRequest, hres: HttpServletResponse) =>
val request = new RequestBinding(hreq)
val response = new ResponseBinding(hres)
intent.lift(request) match {
case Some(rf:RequestSwap) => chain.doFilter(rf.req.underlying, response.underlying)
case Some(Pass) | None => chain.doFilter(request.underlying, response.underlying)
case Some(rf) => rf(response).outputStream.close()
}
}
}
}
object AuthServerExample {
val authCookieName = "auth_token"
def main(args: Array[String]) {
case class MyPrincipal(user: String) extends Principal { def getName = user; }
def getUser(cookie: String): Option[String] = Some("dummyUser")
val userAuthPlan = new PlanWithRequestSwap {
def intent = {
case req @ Cookies(cookies) => cookies(authCookieName) match {
case Some(Cookie(_,authToken,_,_,_,_,_,_)) => getUser(authToken) match {
case Some(user) =>
println("got user: "+ user)
RequestSwap(new RequestBinding(new HttpServletRequestWrapper(req.underlying) {
override def getUserPrincipal = new MyPrincipal(user)
}))
case _ => Unauthorized
}
case _ => Unauthorized
}
}
}
val userProtectedPlan = Planify {
case req => req.underlying.getUserPrincipal match {
case MyPrincipal(user) => req match {
case Path("/userProtected") => HtmlBody(s"get protected as $user")
}
case x => Unauthorized ~> HtmlBody(s"Unrecognized principal: $x")
}
}
val publicPlan = Planify {
case Path(Seg("setc"::name::value::Nil)) => SetCookies(Cookie(name, value, path=Some("/"))) ~> HtmlBody(s"set $name=$value")
}
unfiltered.jetty.Server.local(9080).plan(publicPlan).plan(userAuthPlan).plan(userProtectedPlan).run()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment