Frage

I am working on play 2.1 with secure social integration. As of now, I was able to integrate securesocial with mongod db using SALAT. Now I am able to login/logout. But now what i want is if the user has logged in , then I need to show user info like avatar etc in the header of my web application and I am not sure how to get the user information in scala.html without passing as params from Controller. I can't do this everytime.

Do we have something similar to spring security which grabs user from session and use EL or spring taglib to display user info ???

War es hilfreich?

Lösung

Sad that this community is so inactive or dont want to answer this question. I still find spring and java communities answering the most basic questions even after several years. So here it is what I did.Any improvements or suggestions are highly welcome.

Wrote a method in my controller that would return user as a implicit method.

  implicit def user(implicit request: RequestHeader):Option[Identity] = {
    SecureSocial.currentUser
  }

Pass this user to my template and make it implicit. Wondering why it can't directly use it from controller. I have to explicitly pass it which is very weird.

  @(implicit user:Option[securesocial.core.Identity])

Since the user info has to be in all pages it has to be included in main template or main template call another template that renders user info.In my main template=>

@(title: String, nav: String = "")(content: Html)(implicit user:Option[securesocial.core.Identity]=None)

Then some view related code

@if(user.isDefined){
      <li>          
         <a href="@securesocial.controllers.routes.LoginPage.logout()"/>Logout</li>
         }else{
      <li>
        <a href="@securesocial.core.providers.utils.RoutesHelper.login()">Login</a></li>
 }

Andere Tipps

You can call a controller's method in a template to get something without passing it as a parameter:

@defining(Auth.getCurrentUserName()) {user =>
    <div>Hello, @user</div>
}

Auth is a controller, getCurrentUserName() just gets some data from the session.

public static String getCurrentUserName() {
    return session().get("username");
}

To make it simpler without providing implicit user, just call SecureSocial.currentUser() directly in your scala template.

You need to import it and then you can check if user is defined:

@import securesocial.core.SecureSocial

@if(SecureSocial.currentUser.isDefined) {
    ...
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top