summaryrefslogtreecommitdiff
path: root/crashbox-http/src/main/scala/io/crashbox/ci/Main.scala
blob: 6a61e516ef38515e079d2925e33266e45ba3acc2 (plain) (blame)
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
package io.crashbox.ci

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.directives.Credentials
import akka.stream.ActorMaterializer
import java.text.SimpleDateFormat
import java.util.Date
import scala.util.{Failure, Success}

object Main {

  implicit val system = ActorSystem("crashbox")
  implicit val materializer = ActorMaterializer()
  implicit val executionContext = system.dispatcher

  def main(args: Array[String]): Unit = {
    val host = system.settings.config.getString("crashbox.host")
    val port = system.settings.config.getInt("crashbox.port")

    Http(system).bindAndHandle(Route.route, host, port) onComplete {
      case Success(_) =>
        system.log.info(s"Listening on $host:$port")
      case Failure(ex) =>
        system.log.error(ex, s"Failed to bind to $host:$port")
        system.terminate()
    }
  }

}

object Route {
  import akka.http.scaladsl.server._
  import Directives._

  private val formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

  def route: Route = {
    pathEndOrSingleSlash {
      complete(s"Served at ${formatter.format(new Date)}")
    } ~ path("secure") {
      authenticateBasic(realm = "secure site", myUserPassAuthenticator) {
        userName =>
          complete(s"The user is '$userName'")
      }
    }
  }

  def myUserPassAuthenticator(credentials: Credentials): Option[String] = {
    credentials match {
      case p @ Credentials.Provided(id) if p.verify("guest") => Some(id)
      case _ => None
    }
  }
}