Skip to content

Instantly share code, notes, and snippets.

@vkostyukov
Created February 17, 2016 20:11
Show Gist options
  • Save vkostyukov/f8d5fe040bc80b1b22f7 to your computer and use it in GitHub Desktop.
Save vkostyukov/f8d5fe040bc80b1b22f7 to your computer and use it in GitHub Desktop.
Simple Auth with Finch
scala> case class Auth(u: String)
defined class Auth
scala> val auth = headerOption("Auth").withDefault("anon").as[Auth].mapOutput { a =>
| if (a.u == "foo") Ok(a) else Unauthorized(new Exception("wrong credentials"))
| }
scala> val e = get("foo" :: auth).map(_.u)
e: io.finch.Endpoint[String] = GET /foo/header(Auth)
scala> val s = e.toService
s: com.twitter.finagle.Service[com.twitter.finagle.http.Request,com.twitter.finagle.http.Response] = <function1>
scala> s(Request("/foo")).get
res1: com.twitter.finagle.http.Response = Response("HTTP/1.1 Status(401)")
scala> val req = Request("/foo")
req: com.twitter.finagle.http.Request = Request("GET /foo", from 0.0.0.0/0.0.0.0:0)
scala> req.headerMap.set("Auth", "foo")
res2: com.twitter.finagle.http.HeaderMap = Map(Auth -> foo)
scala> s(req).get
res3: com.twitter.finagle.http.Response = Response("HTTP/1.1 Status(200)")
scala> s(req).get.contentString
res4: String = "foo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment