Skip to content

Instantly share code, notes, and snippets.

@danielholmstrom
Created July 27, 2012 11:49
Show Gist options
  • Save danielholmstrom/3187562 to your computer and use it in GitHub Desktop.
Save danielholmstrom/3187562 to your computer and use it in GitHub Desktop.
package controllers
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.data._
import play.api.data.Forms._
import play.api.Play.current
import views._
case class Account(id: Int, username: String)
case class Login(username: String, password: String) {
// Defines a login
// A login is NOT an account
def isValid = {
username == "admin" && password == "pass"
}
def account = { Account(1, username) }
}
trait AuthForms {
implicit val loginForm = Form(
tuple(
"username" -> nonEmptyText,
"password" -> nonEmptyText
) verifying ("Invalid email or password", result => result match {
case (username, password) => Login(username, password).isValid
})
)
}
object Auth extends Controller with AuthForms {
def login = Action { implicit request =>
request.session.get(Security.username).map { user =>
Unauthorized("You are already logged in")
}.getOrElse {
loginForm.bindFromRequest.fold(
formWithErrors => Redirect(routes.Application.index()).flashing("error" -> "Login failed"),
login => Redirect(routes.Application.index()).flashing("info" -> "You were now logged in").withSession(Security.username -> login._1)
)
}
}
def logout = Action { request =>
Redirect(routes.Application.index()).flashing("info" -> "You were logged out").withNewSession
}
}
object Application extends Controller with AuthForms {
def index = Action { implicit request =>
Ok(views.html.index())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment