package backchat
package web
package auth
import org.scalatra.auth.ScentryStrategy
import org.scalatra.ScalatraKernel
import model.User
class BackchatHeaderAuth(protected val app: ScalatraKernel, name: String) extends ScentryStrategy[User] {
override def isValid = true
def authenticateKey(key: String): Option[User] = User.authenticateWithApiKey(key).toOption
/**
* Authenticates a user by validating the key read from the authorization header.
*/
def authenticate() = {
BackchatHeaderAuth(app, name) flatMap (authenticateKey _)
}
/**
* Called when authentication failed. Sets a challenge header on the response.
*/
override def unauthenticated() {
val challenge = """%s realm="%s API""" format (name, name)
app.response.setHeader("WWW-Authenticate", challenge)
app.halt(401, "Unauthorized")
}
}
object BackchatHeaderAuth {
class OptionableString(s: String) {
def toOption = if(s == null || s.trim.isEmpty) None else Some(s)
}
private implicit def string2optionable(s: String) = new OptionableString(s)
def apply(app: ScalatraKernel, name: String) =
(app.request.getHeader("Authorization").toOption
map (_.trim)
filter (_.toUpperCase(ENGLISH).startsWith(name.toUpperCase(ENGLISH) + " "))
map (_.substring(name.length + 1)))
}