diff options
| author | Pierre de Lacroix <pierre@pdelacroix.com> | 2020-05-26 20:56:57 +0200 |
|---|---|---|
| committer | Pierre de Lacroix <pierre@pdelacroix.com> | 2020-05-26 20:56:57 +0200 |
| commit | 02cd8f9c94dc36c4018915a463028141da1bc859 (patch) | |
| tree | b581ff951e4cafd9acc0b4c2f85a65f29a11ae1f | |
| parent | handle giving a custom path (diff) | |
Add API auth Plug
| -rw-r--r-- | lib/matrix_app_service/auth_plug.ex | 26 | ||||
| -rw-r--r-- | lib/matrix_app_service/phoenix/router.ex | 1 |
2 files changed, 27 insertions, 0 deletions
diff --git a/lib/matrix_app_service/auth_plug.ex b/lib/matrix_app_service/auth_plug.ex new file mode 100644 index 0000000..0768caa --- /dev/null +++ b/lib/matrix_app_service/auth_plug.ex @@ -0,0 +1,26 @@ +defmodule MatrixAppService.AuthPlug do + @behaviour Plug + import Plug.Conn + require Logger + + @impl Plug + def init(_opts) do + Application.fetch_env!(:matrix_app_service, :homeserver_token) + end + + @impl Plug + def call(%Plug.Conn{params: %{"access_token" => hs_token}} = conn, config_hs_token) + when hs_token == config_hs_token do + conn + end + + def call(conn, _config_hs_token) do + Logger.warn("Received invalid homeserver token") + + conn + |> put_status(:unauthorized) + |> Phoenix.Controller.put_view(MatrixAppServiceWeb.ErrorView) + |> Phoenix.Controller.render("401.json") + |> halt + end +end diff --git a/lib/matrix_app_service/phoenix/router.ex b/lib/matrix_app_service/phoenix/router.ex index 4ab6bf2..a5458d2 100644 --- a/lib/matrix_app_service/phoenix/router.ex +++ b/lib/matrix_app_service/phoenix/router.ex @@ -3,6 +3,7 @@ defmodule MatrixAppService.Phoenix.Router do quote do pipeline :matrix_api do plug :accepts, ["json"] + plug MatrixAppService.AuthPlug end path = Application.compile_env(:matrix_app_service, :path, "/") |
