Play Framework Multi-Tenant Filter

走远了吗. 提交于 2019-12-03 20:12:30

Think of actions in Play as being function calls, the input is the request, the output is the result. If you want to change the result of a wrapped function call, then you must first invoke the function, and then apply your change. Adding a key to a session is changing the result, since the session is sent to the client in the session cookie. In the code above, you're trying to do the change before you have a result to change, ie, before you call super.onRouteRequest.

If you don't need to modify routing at all, then don't do this in onRouteRequest, do it in a filter, much easier there. But assuming you do need to modify routing, then you need to apply a filter to handler returned. This is what it might look like:

override def onRouteRequest(request: RequestHeader): Option[Handler] = {
  val maybeSite: Option[String] = request.session.get("site").orElse {
    // Let's just assume that getSiteUIDFromUrl returns Option[String], always use Option if you're returning values that might not exist.
    models.Site.getSiteUIDFromURL(request.host.toLowerCase())
  }

  maybeSite.flatMap { site =>
    super.onRouteRequest(request).map {
      case e: EssentialAction => EssentialAction { req =>
        e(req).map(_.withSession("site" -> site))
      }
      case other => other
    }
  }
}

Check the source code for the CSRFFilter to see examples of how to add things to the session in a filter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!