Burnett
Burnett

Reputation: 47

Scala Play session value not saving

So I am working on a webapp in Scala with Play 2.3 using IntelliJ 14.1.1.

The problem is with storing values in the session. I currently have this:

def authCredentials = Action { implicit request =>
  loginForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.login(formWithErrors.withError("badlogin","Username or password is incorrect."))),
        goodForm => Redirect(routes.AccountController.display).withSession(request.session + ("username" -> goodForm._1))
    )
}

and then in my AccountController:

  def display = Action { implicit request =>
    request.session.get("username").map { username =>
      Ok(views.html.account(User.getUser(username))).withSession(request.session + ("username" -> username))
    }.getOrElse(Redirect(routes.LoginController.login)).withNewSession
  }

Now in the the above function it is finding the username and rendering the account page only once. The problem is after that when I want to navigate to a page from the account page such as to the change password page or even a refresh of the account page it will redirect back to login with new session.

What am I doing wrong and is there a better way to check if the session is authenticated for access to the page instead of repeat code on each display function.

Upvotes: 3

Views: 584

Answers (1)

aveuiller
aveuiller

Reputation: 1551

It seems to be a simple parentheses problem, try :

def display = Action { implicit request =>
  request.session.get("username").map { username =>
  Ok(views.html.account(User.getUser(username))).withSession(request.session + ("username" -> username))
  }.getOrElse(Redirect(routes.LoginController.login).withNewSession)
}

You were in fact resetting the session in any case in your controller, now the withNewSession call is inside getOrElse, which send a new session only in case of no username found in the current one.

Upvotes: 1

Related Questions