Skip to content

Instantly share code, notes, and snippets.

@Centaur
Created December 22, 2013 07:19
Show Gist options
  • Save Centaur/8079402 to your computer and use it in GitHub Desktop.
Save Centaur/8079402 to your computer and use it in GitHub Desktop.
spray customized authentication demo
import spray.routing.{AuthenticationFailedRejection, HttpService}
import akka.actor.{Props, ActorSystem, Actor, ActorRefFactory}
import spray.routing.authentication._
import scala.concurrent.Promise
import spray.routing.AuthenticationFailedRejection.CredentialsMissing
import akka.io.IO
import spray.can.Http
class MinifiedService extends Actor with HttpService {
val identity_cookie_name = "session_id"
def actorRefFactory: ActorRefFactory = context
implicit def executionContext = actorRefFactory.dispatcher
def receive: Actor.Receive = runRoute(routes)
val login = path("login") {
post {
complete("login")
}
}
val logout = path("logout") {
post {
complete("logout")
}
}
val change_password = { session_id: String =>
path("change_password") {
put {
complete("change_password")
}
}
}
def bySession: ContextAuthenticator[String] = { ctx =>
val promise = Promise[Authentication[String]]()
ctx.request.cookies.find(_.name == identity_cookie_name).map { cookie =>
promise.success(Right(cookie.value))
}.getOrElse {
promise.success(Left(AuthenticationFailedRejection(CredentialsMissing, Nil)))
}
promise.future
}
val routes = pathPrefix("admin") {
login ~ logout ~ authenticate(bySession) { session_id =>
change_password(session_id)
}
}
}
object MinifiedApp extends App{
implicit val system = ActorSystem("MinifiedSystem")
val service = system.actorOf(Props[MinifiedService], "Minified-Service")
IO(Http) ! Http.Bind(service, "0.0.0.0", port = 8080)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment