Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Framework 2 (Scala) templates: see if user is logged in

Moin,

I wrote an app with help of play framework. Now I have a main template which should be used for every request. In this template I have links routing to login form and logout method. Of course only users that are logged out should see the login form and so on. Does anybody know how to implement that without writing every action two times?

Thanks from northern Germany!

like image 537
leMale Avatar asked Dec 20 '22 18:12

leMale


1 Answers

I put a gist up on securing actions, which could be of use to you.

Controllers extending the SecureableController trait have:

implicit def user(implicit request : RequestHeader) : Option[User] = {  
  // substitute in your own user lookup mechanism here
  session.get("email").flatMap(User.findOne(_))
}

which allows you to get the user via implicit parameters in views you route to from that controller by specifying:

@ ... other parameters ... (implicit user: Option[User] = None)

on each of your views. (Haven't got a way around that particular boilerplate yet.)

I then have something like this in my menu:

   @user match {
      case Some(u) => {
        @defining(u.givenName + " " + u.familyName) { profileName =>
      <li class="dropdown"><a href="#user" class="dropdown-toggle" data-toggle="dropdown">@profileName<b class="caret"></b></a>
        }
        <ul class="dropdown-menu">
          @defining("/profile/"+u.email) { profileUrl =>
          <li><a href="@profileUrl">Profile</a></li>                
          <li><a href="@routes.Users.logout">Logout</a></li>                
          }
        </ul>      
      </li>      
      }
      case None => {
      <li>            
        <a href="@routes.Users.login">Login</a>
      </li>
      }
    }       

It gives a bootstrap dropdown linking to the Profile page and Logout for a logged in user, and a Login link in place if there is no logged in user.

like image 117
Brian Smith Avatar answered Mar 09 '23 05:03

Brian Smith