Skip to content

Instantly share code, notes, and snippets.

@freekh
Created March 4, 2014 12:04
Show Gist options
  • Save freekh/9345293 to your computer and use it in GitHub Desktop.
Save freekh/9345293 to your computer and use it in GitHub Desktop.
package controllers
import play.api._
import play.api.mvc._
import play.api.libs.json.JsValue
import play.api.data.Form
import play.api.data.Forms._
import play.api.data.format.Formats._
import play.api.data.validation.Constraints._
import models.Credential
import forms.CredentialForm._
import play.api.libs.ws.WS
import scala.concurrent.Future
object Application extends Controller {
val SessionKey = "username"
def index = Action { request =>
request.session.get(SessionKey) match {
case Some(username) =>
Ok(views.html.index(username))
case None =>
Redirect(routes.Application.login)
}
}
def login = Action { implicit request =>
Ok(views.html.login(credentialForm))
}
def logout = Action {
Redirect(routes.Application.login).withNewSession
}
def submit = Action.async { implicit request =>
val filledForm: Form[Credential] = credentialForm.bindFromRequest()
import play.api.libs.concurrent.Execution.Implicits._
def onFailure(badForm: Form[Credential]) = Future(BadRequest(views.html.login(badForm)))
def onSuccess(credential: Credential): Future[SimpleResult] = {
credentialCheck(credential).map { authenticated =>
if (authenticated) {
Redirect(routes.Application.index).withSession(SessionKey -> credential.username)
} else {
BadRequest(views.html.login(filledForm.withGlobalError("Not authenticated :(")))
}
}
}
filledForm.fold(onFailure _, onSuccess _)
}
}
package forms
import models.Credential
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.ws.WS
import scala.concurrent.Await
import play.api.libs.ws.Response
import scala.concurrent.Future
object CredentialForm {
val UsernameFormField = "username"
val PasswordFormField = "password"
def credentialFormApply(username: String, password: String) = {
Credential(username, password)
}
def credentialFormUnapply(credential: Credential) = {
Some((credential.username, credential.password))
}
def credentialCheck(credential: Credential): Future[Boolean] = {
import scala.concurrent.duration._
import play.api.libs.concurrent.Execution.Implicits._
val futureResponse: Future[Response] = WS.url(models.github.baseUrl + "/user")
.withAuth(credential.username, credential.password, com.ning.http.client.Realm.AuthScheme.BASIC)
.get
futureResponse.map(_.status == 200)
}
val credentialMapping = mapping(
UsernameFormField -> nonEmptyText(minLength = 4),
PasswordFormField -> nonEmptyText)(credentialFormApply)(credentialFormUnapply)
val credentialForm: Form[Credential] = Form(credentialMapping)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment