Skip to content

Instantly share code, notes, and snippets.

@freekh
Last active May 15, 2017 10:48
Show Gist options
  • Save freekh/9132313 to your computer and use it in GitHub Desktop.
Save freekh/9132313 to your computer and use it in GitHub Desktop.
Async play form
package controllers
import play.api._
import play.api.mvc._
import play.api.data.Form
import play.api.data.Forms._
import play.api.data.format.Formats._
import models.Credential
import views.html.defaultpages.unauthorized
import scala.concurrent.Await
import play.api.libs.ws.WS
import scala.concurrent.Future
import play.api.libs.ws.Response
object Application extends Controller {
val UsernameSessionKey = "username"
def index = Action { request =>
request.session.get(UsernameSessionKey) match {
case Some(username) => Ok(views.html.index(username))
case None => Redirect(routes.Application.login)
}
}
def login = Action {
Ok(views.html.login(Form(loginFormMapping)))
}
def logout = Action {
Redirect(routes.Application.login).withNewSession
}
val loginFormMapping = mapping(
"username" -> nonEmptyText(4),
"password" -> nonEmptyText(4)) {
(username, password) => Credential(username, password)
} {
credential => Some(credential.username -> credential.password)
}
import play.api.libs.concurrent.Execution.Implicits._
def checkLogin(c: Credential): Future[Boolean] = {
val requestHolder = WS.url(models.github.baseUrl + "/user")
.withAuth(c.username, c.password, com.ning.http.client.Realm.AuthScheme.BASIC)
val futureResponse: Future[Response] = requestHolder.head()
futureResponse.map(_.status == 200)
}
def submit = Action.async(BodyParsers.parse.urlFormEncoded) { implicit request =>
Form(loginFormMapping).bindFromRequest().fold(
badForm => Future(BadRequest(views.html.login(badForm))),
credential => {
checkLogin(credential).map { loginSuccessful =>
{
if (loginSuccessful) {
Redirect(routes.Application.index).withSession(UsernameSessionKey -> credential.username)
} else BadRequest(views.html.login(Form(loginFormMapping).withGlobalError("Username password combo wrong")))
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment