Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Login Form

Step 1: Create the Login Form Model

Define a simple case class to represent the login form data. You can place this in a Scala file in the models package, for instance, LoginForm.scala:

package models

case class LoginForm(username: String, password: String)

Step 2: Create the Login Controller

Create a controller that will render the login form and handle form submission. If the username and password match the hardcoded credentials, it will redirect the user to a secure page; otherwise, it will reload the login page with an error.

In the controllers directory, create a file named LoginController.scala:

package controllers

import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import models.LoginForm
import javax.inject._

@Singleton
class LoginController @Inject()(cc: MessagesControllerComponents) extends MessagesAbstractController(cc) {

  val loginForm: Form[LoginForm] = Form(
    mapping(
      "username" -> text,
      "password" -> text
    )(LoginForm.apply)(LoginForm.unapply)
  )

  def login = Action { implicit request: MessagesRequest[AnyContent] =>
    Ok(views.html.login(loginForm))
  }

  def authenticate = Action { implicit request: MessagesRequest[AnyContent] =>
    loginForm.bindFromRequest.fold(
      formWithErrors => BadRequest(views.html.login(formWithErrors)),
      formData => {
        if (formData.username == "user" && formData.password == "password") {
          Redirect(routes.HomeController.index()).flashing("success" -> "You are logged in.")
        } else {
          Redirect(routes.LoginController.login()).flashing("error" -> "Invalid username or password.")
        }
      }
    )
  }
}

Step 3: Define Routes

In the conf/routes file, add routes for your login form and authentication process:

GET     /login                   controllers.LoginController.login
POST    /authenticate            controllers.LoginController.authenticate
GET     /                        controllers.HomeController.index

Ensure you have a route and controller action for /, which will serve as the landing page after a successful login.

Step 4: Create the Login Form View

Create a new Scala HTML file named login.scala.html in the app/views directory. This view will render the login form:

@import helper._
@(form: Form[LoginForm])(implicit request: MessagesRequestHeader)

@main("Login") {
    @form(routes.LoginController.authenticate()) {
        @CSRF.formField

        @inputText(form("username"), '_label -> "Username")
        @inputPassword(form("password"), '_label -> "Password")

        <button type="submit">Login</button>
    }

    @request.flash.get("error").map { error =>
        <div class="error">@error</div>
    }
}

Make sure you have a main template file (main.scala.html) that this login template references to structure the page.

Step 5: Running Your Application

Execute your application:

sbt run

Navigate to http://localhost:9000/login in your browser to see the login form. Try logging in with the username user and the password password.