如何将request.identity传递给视图

时间:2018-02-15 14:36:11

标签: scala playframework silhouette

def edit(id:String)= SecuredAction(WithService(“master”))。async {implicit request =>

    val futureEmp = collection.flatMap(_.find(Json.obj("_id" -> Json.obj("$oid" -> id))).cursor[Employee]().collect[List]())

futureEmp.map { emps: List[Employee] =>
  implicit val message = messagesApi.preferred(request)

  Ok(html.editForm(id, employeeForm.fill(emps.head)))
}.recover {
  case t: TimeoutException =>
    Logger.error("Problem found in employee edit process")
    InternalServerError(t.getMessage)
}

}

1 个答案:

答案 0 :(得分:1)

在播放模块中连接Silhouette后,将用户模型注入环境特征:

trait YourCustomEnv extends Env {
  type I = User // <- Whatever user model your app uses
  type A = JWTAuthenticator
}

...您将能够通过访问身份成员来访问安全端点上的身份:

def index() = silhouette.SecuredAction.async { implicit request =>
    // The model of the authenticated user available here
    val user: User = request.identity
    Future.successful(Ok)
}

假设您使用Twirl作为模板引擎,您可以将此对象作为参数添加到模板中,从而将此对象传递给视图:

@(user: models.User)

...并从您的控制器调用模板:

def index() = silhouette.SecuredAction.async { implicit request =>
    val user: User = request.identity
    Future.successful(Ok(views.html.home(user))))
}