Security.Authenticated
just checks if session contains "username" key. If it does, user supposed to be authenticated.
You should authenticate your users yourself, by doing database lookup, or any other way. Then, store user id(or email, or just name) in the session:
val user = // fetch user info
Redirect("/").withSession("userId" → user.id.toString)
Then wrap actions in Security.Authenticated
call:
def someAction = Security.Authenticated(
req => req.session.get("userId"),
_ => Redirect(views.html.login())) { userId =>
Action {
Ok(html.index())
}
}
The first argument to Authenticated
is a function that retrieves user id from the session. It returns an Option[String]
, i.e. Some[String]
if there is id in the session or None
if there isn't.
req => req.session.get("userId")
The second argument is a function that returns Result
to use, if session isn't contains user id. You will typically want a redirect to a login page.
_ => Redirect(views.html.login())
The final argument is a function returning Action
. It is used if user is authenticated.
userId => Action {
Ok(html.index())
}
You are not forced to use play implementation, feel free to wrap it in handy helper, or write it from scratch to fit your needs:
def myAuth(f: String => Result) = Security.Authenticated(
req => req.session.get("userId"),
_ => Redirect(views.html.login())) { userId =>
Action {
f(userId)
}
}
def someAction = myAuth { userId =>
Ok(html.index())
}