Reputation: 13300
I'm trying to convert a user ID from a User class and store it in a Play! session variable. However when I try to print out that session variable, it returns a blank string. This is a simple authentication.
During authentication:
session += "userid" -> user.id.toString
Printing session variable in Play! scala view:
@ctx("userid")
The whole 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 the User class:
case class User(
val id: Long,
A solution? What's missing or going wrong here that's preventing user.id
from being stored in the session? Thanks
Upvotes: 4
Views: 1015
Reputation: 13300
After asking around and doing some more reading, this was indeed caused by a "feature" of the Play! 1.2.4 framework. Luckily we can expect more with v2.
For our particular app, there's a 3rd often overlooked step when it comes to session variables. You need to renderArgs
for each one for them to be accessible. So a comment by @ChrisJamesC was mostly right: there was a step missing in initialization.
Here's what's going on 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 didn't realize that I needed to renderArgs for every variable I want to store and access in a session. But there's a catch: you still need to store each var as a String.
Then in each Play! view I can access the var like so: @ctx("userid")
I hope this helps future people who are using Play!
Upvotes: 3