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)
You must use keyword def before defining an method.
@Before def checkSecurity = {
should fix this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With