Created
February 23, 2015 17:44
-
-
Save amolbrid/df7f490028f4b5fea0f3 to your computer and use it in GitHub Desktop.
Authentication with DI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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