Browse Source

fix issue #3

prevent cors errors in clients contacting the relay
endpoing handles preflight OPTIONS requests
test/local-setup
Silberengel 3 weeks ago
parent
commit
3bdc58dc14
  1. 1
      lib/gc_index_relay_web/endpoint.ex
  2. 29
      lib/gc_index_relay_web/plugs/cors.ex

1
lib/gc_index_relay_web/endpoint.ex

@ -51,5 +51,6 @@ defmodule GcIndexRelayWeb.Endpoint do
plug Plug.MethodOverride plug Plug.MethodOverride
plug Plug.Head plug Plug.Head
plug Plug.Session, @session_options plug Plug.Session, @session_options
plug GcIndexRelayWeb.Plugs.CORS
plug GcIndexRelayWeb.Router plug GcIndexRelayWeb.Router
end end

29
lib/gc_index_relay_web/plugs/cors.ex

@ -0,0 +1,29 @@
defmodule GcIndexRelayWeb.Plugs.CORS do
@moduledoc """
CORS plug for the Nostr relay REST API.
Nostr clients can be hosted on any origin, so this plug allows all origins
on all API routes. Preflight OPTIONS requests are halted here and returned
a 200 before they reach the router.
"""
import Plug.Conn
def init(opts), do: opts
def call(conn, _opts) do
conn
|> put_resp_header("access-control-allow-origin", "*")
|> put_resp_header("access-control-allow-methods", "GET, POST, DELETE, OPTIONS")
|> put_resp_header("access-control-allow-headers", "content-type, authorization")
|> handle_preflight()
end
defp handle_preflight(%Plug.Conn{method: "OPTIONS"} = conn) do
conn
|> send_resp(200, "")
|> halt()
end
defp handle_preflight(conn), do: conn
end
Loading…
Cancel
Save