简体   繁体   中英

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)

You must use keyword def before defining an method.

@Before def checkSecurity = {

should fix this.

You're probably getting the 'not found: value User' error because its definition is not found. You need to make sure you import the package. Just do:

import models._

after

import play.mvc._

To import all models.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM