-
-
Save enterpredator/464b828f34c1dcd86b3913071f5d8f0c to your computer and use it in GitHub Desktop.
Async play form
This file contains hidden or 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
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