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他带到登录页面,否则从会话中返回用户。问题在于重定向,在运行时 Play 抱怨:

不能使用返回对象作为处理程序的方法

有人有任何线索吗?

4

2 回答 2

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))
    }
  }
于 2012-12-06T09:22:19.130 回答
0

我认为 withAuth 的返回类型不是你想象的那样。我认为您需要将重定向包装在一个动作中。

于 2012-12-06T01:54:12.163 回答