为什么我在Play 2中收到特定方法的错误?

时间:2012-12-05 23:37:03

标签: scala playframework-2.0

我有这个方法:

def withAuth(f: => User => Request[AnyContent] => Result) = {
    Authentication.isAuthenticated(AuthenticationToken(AuthenticationService.TokenKey)) match {
      case None => Results.Redirect(routes.AuthenticationService.notLoggedIn)
      case Some(user) => Action(request => f(user)(request))
    }
  }

我用它像:

  def list(locationId: Option[Int]) = withAuth { user =>
    implicit request =>
      val entities = Assets.filter(user, locationId)
      Logger.info("Succesfully returned %d assets to user %s".format(entities.length, user))
      Ok(Json.toJson(entities.map(s => Json.toJson(s))))
  }

正如您所注意到的,我希望将其用作一种方法,如果用户未登录,则Redirect将他登录页面,否则会从会话返回用户。问题在于Redirect,在运行时Play正在抱怨:

  

不能使用将Object作为处理程序返回的方法

有人有任何线索吗?

2 个答案:

答案 0 :(得分:1)

为了避免上述问题,我最终做到了:

   def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.AuthenticationService.notLoggedIn)

  /**
   * A very important wrapper method which checks if the user is logged-in: if it is, return the User, otherwise
   * redirect the user to a specific page.
   */
  def withAuthentication(f: => Option[User] => Request[AnyContent] => Result) = {
    Security.Authenticated(userId, onUnauthorized) { user =>
      Action(request => f(Users.findById(Integer.valueOf(user)))(request))
    }
  }

答案 1 :(得分:0)

我认为withAuth的返回类型不是你想象的那样。我认为您需要将Redirect包装在Action中。