Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing loggedin User info in the header of my web app every time

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 ???

like image 584
Giri Avatar asked Mar 22 '23 16:03

Giri


2 Answers

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>
 }
like image 80
Giri Avatar answered Apr 16 '23 03:04

Giri


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");
}
like image 21
kapex Avatar answered Apr 16 '23 02:04

kapex