summaryrefslogtreecommitdiff
path: root/lib/matrix_app_service_web/auth_plug.ex
blob: a06fd46f00120070e564f4eda7bb0ffc8ab69b07 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
defmodule MatrixAppServiceWeb.AuthPlug do
  @moduledoc """
  Implements the Application Service authorization as a Plug.

  https://matrix.org/docs/spec/application_service/r0.1.2#authorization
  """

  @behaviour Plug
  import Plug.Conn
  require Logger

  @doc false
  @impl Plug
  def init(opts) do
    opts
  end

  @doc false
  @impl Plug
  def call(%Plug.Conn{params: %{"access_token" => hs_token}} = conn, _opts) do
    config_hs_token = Application.fetch_env!(:matrix_app_service, :homeserver_token)

    with ^config_hs_token <- hs_token do
      conn
    else
      _ ->
        Logger.warn("Received invalid homeserver token")
        respond_error(conn, 403)
    end
  end

  def call(conn, _opts) do
    Logger.warn("No homeserver token provided")
    respond_error(conn, 401)
  end

  defp respond_error(conn, error_code) do
    conn
    |> put_status(error_code)
    |> Phoenix.Controller.put_view(MatrixAppServiceWeb.ErrorView)
    |> Phoenix.Controller.render("#{error_code}.json")
    |> halt
  end
end