Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 247
Burnett Avatar asked Mar 24 '26 17:03

Burnett


1 Answers

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.

like image 59
aveuiller Avatar answered Mar 26 '26 13:03

aveuiller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!