|
| 1 | +defmodule AlgoraWeb.Plugs.GithubWebhooks do |
| 2 | + @moduledoc false |
| 3 | + @behaviour Plug |
| 4 | + |
| 5 | + import Plug.Conn |
| 6 | + |
| 7 | + alias Algora.Github.Webhook |
| 8 | + alias AlgoraWeb.Webhooks.GithubController |
| 9 | + alias Plug.Conn |
| 10 | + |
| 11 | + require Logger |
| 12 | + |
| 13 | + @impl true |
| 14 | + def init(opts) do |
| 15 | + path_info = String.split(opts[:at], "/", trim: true) |
| 16 | + |
| 17 | + opts |
| 18 | + |> Map.new() |
| 19 | + |> Map.put_new(:path_info, path_info) |
| 20 | + end |
| 21 | + |
| 22 | + @impl true |
| 23 | + def call(%Conn{method: "POST", path_info: path_info} = conn, %{path_info: path_info} = _opts) do |
| 24 | + with {:ok, webhook, conn} <- Webhook.new(conn), |
| 25 | + :ok <- GithubController.process_delivery(webhook) do |
| 26 | + conn |> send_resp(200, "Webhook received.") |> halt() |
| 27 | + else |
| 28 | + {:error, :bot_event} -> |
| 29 | + conn |> send_resp(200, "Webhook received.") |> halt() |
| 30 | + |
| 31 | + {:error, :missing_header} -> |
| 32 | + Logger.error("Missing header") |
| 33 | + conn |> send_resp(400, "Bad request.") |> halt() |
| 34 | + |
| 35 | + {:error, :signature_mismatch} -> |
| 36 | + Logger.error("Signature mismatch") |
| 37 | + conn |> send_resp(400, "Bad request.") |> halt() |
| 38 | + |
| 39 | + error -> |
| 40 | + Logger.error("Bad request: #{inspect(error)}") |
| 41 | + conn |> send_resp(400, "Bad request.") |> halt() |
| 42 | + end |
| 43 | + rescue |
| 44 | + e -> |
| 45 | + Logger.error(Exception.format(:error, e, __STACKTRACE__)) |
| 46 | + conn |> send_resp(400, "Bad request.") |> halt() |
| 47 | + end |
| 48 | + |
| 49 | + @impl true |
| 50 | + def call(%Conn{path_info: path_info} = conn, %{path_info: path_info}) do |
| 51 | + conn |> send_resp(400, "Bad request.") |> halt() |
| 52 | + end |
| 53 | + |
| 54 | + @impl true |
| 55 | + def call(conn, _), do: conn |
| 56 | +end |
0 commit comments