将参数从自定义插件转发到第二个插件

时间:2018-12-02 18:01:09

标签: elixir phoenix-framework plug guardian

我有一个自定义插件,如下所示:

defmodule Db.Auth.GuardianPipeline do
  use Guardian.Plug.Pipeline,
    otp_app: :db,
    module: Db.Auth.Guardian

  plug Guardian.Plug.VerifySession, claims: %{"typ" => "access"}
  plug Guardian.Plug.VerifyHeader, claims: %{"typ" => "access"}
  plug Guardian.Plug.LoadResource, allow_blank: true

  plug Guardian.Plug.VerifySession, claims: %{"typ" => "access"}, key: :impersonated_user
  plug Guardian.Plug.VerifyHeader, claims: %{"typ" => "access"}, key: :impersonated_user
  plug Guardian.Plug.LoadResource, allow_blank: true, key: :impersonated_user

end

但是,我需要能够传递错误处理程序。我目前是这样的:

pipeline :authenticate do
    plug(Guardian.Plug.Pipeline, error_handler: Web.Auth.ErrorHandler)
    plug(Db.Auth.GuardianPipeline)
  end

我宁愿做这样的事情:

pipeline :authenticate do
    plug(Db.Auth.GuardianPipeline, error_handler: Web.Auth.ErrorHandler)
  end

将其传递到我的插件中,如下所示:

defmodule Db.Auth.GuardianPipeline do
  use Guardian.Plug.Pipeline,
    otp_app: :db,
    module: Db.Auth.Guardian,
    error_handler: args["error_handler"],

  plug Guardian.Plug.VerifySession, claims: %{"typ" => "access"}
  plug Guardian.Plug.VerifyHeader, claims: %{"typ" => "access"}
  plug Guardian.Plug.LoadResource, allow_blank: true

  plug Guardian.Plug.VerifySession, claims: %{"typ" => "access"}, key: :impersonated_user
  plug Guardian.Plug.VerifyHeader, claims: %{"typ" => "access"}, key: :impersonated_user
  plug Guardian.Plug.LoadResource, allow_blank: true, key: :impersonated_user

end

如何将args从自定义插件传递到其内部调用的插件?

1 个答案:

答案 0 :(得分:0)

以下内容将满足我的需求。使用builder_opts()将使选项从一个插入到另一个。这是使用Plug.Builder,当然也可以在Guardian之外将其用于其他插头。

defmodule Db.Auth.AuthPipeline do
  use Guardian.Plug.Pipeline, otp_app: :db, module: Db.Auth.Guardian

  plug Guardian.Plug.Pipeline, builder_opts()
  plug Guardian.Plug.VerifySession, claims: %{"typ" => "access"}
  plug Guardian.Plug.VerifyHeader, claims: %{"typ" => "access"}
  plug Guardian.Plug.LoadResource, allow_blank: true

end