-
-
Notifications
You must be signed in to change notification settings - Fork 250
/
AuthExampleApp.scala
62 lines (52 loc) · 2.16 KB
/
AuthExampleApp.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package example.akkahttp
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import caliban._
import caliban.interop.tapir.HttpInterpreter
import caliban.interop.tapir.TapirAdapter.TapirResponse
import caliban.schema.GenericSchema
import sttp.model.StatusCode
import sttp.tapir.model.ServerRequest
import zio.{ Runtime, URIO, Unsafe, ZIO, ZLayer }
import scala.concurrent.ExecutionContextExecutor
import scala.io.StdIn
object AuthExampleApp extends App {
case class AuthToken(value: String)
val auth =
ZLayer {
for {
request <- ZIO.service[ServerRequest]
authToken <- request.headers.collectFirst {
case header if header.is("token") => header.value
} match {
case Some(token) => ZIO.succeed(AuthToken(token))
case _ => ZIO.fail(TapirResponse(StatusCode.Forbidden))
}
} yield authToken
}
val schema: GenericSchema[AuthToken] = new GenericSchema[AuthToken] {}
import schema.auto._
case class Query(token: URIO[AuthToken, String])
private val resolver = RootResolver(Query(ZIO.serviceWith[AuthToken](_.value)))
private val api = graphQL(resolver)
implicit val system: ActorSystem = ActorSystem()
implicit val executionContext: ExecutionContextExecutor = system.dispatcher
implicit val runtime: Runtime[Any] = Runtime.default
val interpreter = Unsafe.unsafe(implicit u => runtime.unsafe.run(api.interpreter).getOrThrow())
val adapter = AkkaHttpAdapter.default
val route =
path("api" / "graphql") {
adapter.makeHttpService(
HttpInterpreter(interpreter).configure(Configurator.setEnableIntrospection(false)).intercept(auth)
)
} ~ path("graphiql") {
adapter.makeGraphiqlService("/api/graphql")
}
val bindingFuture = Http().newServerAt("localhost", 8088).bind(route)
println(s"Server online at http://localhost:8088/\nPress RETURN to stop...")
StdIn.readLine()
bindingFuture
.flatMap(_.unbind())
.onComplete(_ => system.terminate())
}