Convert Scala to Long String

I am trying to convert a user id from a User class and store it in Play! session variable. However, when I try to print this session variable, it returns an empty string. This is a simple authentication.

For authentication:

session += "userid" -> user.id.toString 

Print Session Variable on Play! scala view:

 @ctx("userid") 

All authentication def:

  def authenticate(login:LoginAttempt) = { println("in authenticate") User.authenticate(login.username, login.password) match { case Some(user:User) => { session += "username" -> user.emailAddress session += "userid" -> user.id.toString session += "name" -> user.name session += "accounts" -> user.accounts.toString Redirect(session("path").getOrElse("/")) } case _ => { flash += "error" -> "Wrong username or password." Action(Authentication.login) } } } 

And user class:

 case class User( val id: Long, 

Decision? What is missing here or is something wrong that preventing user.id from being stored in the session? Thanks

+4
source share
1 answer

After you asked and read more, it was called a β€œfeature” of Play! 1.2.4. Fortunately, we can expect more with v2.

In our particular application, there is a 3rd often neglected step when it comes to session variables. You need renderArgs for each of them to be available. Therefore, the comment from @ChrisJamesC was basically right: a step was skipped in the initialization.

Here's what happens in our Secure.scala controller:

 (session("userid"), session("username"), session("name"), session("accounts")) match { case (Some(userid), Some(username), Some(name), Some(accounts)) => { renderArgs += "userid" -> userid renderArgs += "username" -> username renderArgs += "name" -> name renderArgs += "accounts" -> accounts Continue } case _ => { session += "path" -> Request.current().path Action(Authentication.login) } } 

In my own case, I did not understand what I needed for renderArgs for each variable that I want to save and access in the session. But there is a trick: you still need to store each var as a string.

Then in each Play! view I can access var like this: @ctx("userid")

I hope this helps future people who use Play!

+3
source

Source: https://habr.com/ru/post/1395722/


All Articles