Skip to content

Instantly share code, notes, and snippets.

@amolbrid
Created February 23, 2015 17:44
Show Gist options
  • Save amolbrid/df7f490028f4b5fea0f3 to your computer and use it in GitHub Desktop.
Save amolbrid/df7f490028f4b5fea0f3 to your computer and use it in GitHub Desktop.
Authentication with DI
class AuthenticationManager {
// inject db: Database, repo: Users
def authenticateWithToken(token: String): Option[User] = {
db withTransaction { implicit session =>
repo.authenticateWithToken(token)
}
}
}
trait TokenAuthenticator {
val apiTokenAuth = new ApiTokenAuthenticator()
}
class ApiTokenAuthenticator(implicit val executionContext: ExecutionContext) extends HttpAuthenticator[User] {
// inject AuthenticationManager
override def getChallengeHeaders(httpRequest: HttpRequest): List[HttpHeader] =
`WWW-Authenticate`(HttpChallenge(scheme = "Token", realm = "Manta", params = Map.empty)) :: Nil
override def authenticate(credentials: Option[HttpCredentials], ctx: RequestContext): Future[Option[User]] =
Future.successful(
credentials.flatMap {
case GenericHttpCredentials(scheme, token, params) if scheme == "Token" => {
authenticationManager.authenticateWithToken(token)
}
case _ => None
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment