Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Scala Secure Trait in PlayFramework?

I'm trying to build a web application in Scala using Play Framework. When using Play Framework in Java I can use the Secure module to do authentication for pages that require logins. This is a common problem in many web applications, and I would like to use a general solution for my web application.

I have tried to follow Mixing controllers using Traits with a Secure trait example, but my trait doesn't even compile, and I don't understand what's wrong.

I have created the trait from the example and saved it on mysite\app\Secure.scala:

package controllers

import play._
import play.mvc._

trait Secure {
    self:Controller =>

    @Before checkSecurity = {
        session("username") match {
            case Some(username) => renderArgs += "user" -> User(username)
                                   Continue
            case None => Action(Authentication.login)
        }
    }

    def connectedUser = renderArgs("user").get

}

Then I use the Secure trait in a simple mysite\app\MySecretController.scala:

package controllers

import play._
import play.mvc._

object MySecretController extends Controller with Secure {
    def index = <h1>Hello</h1>
}

But when visiting the page I get Compilation error:

The file /app/Secure.scala could not be compiled. Error raised is : expected 
start of definition

on this line:

@Before ↓checkSecurity = {

I also created a simple mysite/app/User class:

package controllers

class User (name: String){

}

Any suggestion on how I can solve this?


UPDATE

After adding def as suggested by Felipe. I get another error not found: value User on:

case Some(username) => renderArgs += "user" -> ↓User(username)
like image 306
Jonas Avatar asked Jun 02 '11 18:06

Jonas


1 Answers

You must use keyword def before defining an method.

@Before def checkSecurity = {

should fix this.

like image 103
Felipe Avatar answered Nov 11 '22 14:11

Felipe