Skip to content

Commit

Permalink
feat(api-key): check for api key on public routes
Browse files Browse the repository at this point in the history
  • Loading branch information
akinsey committed Jan 17, 2025
1 parent 66f67c0 commit a1b95a6
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 1 deletion.
1 change: 1 addition & 0 deletions config/runtime.exs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ EpochtalkServer.RateLimiter.init()

## Frontend configurations
config :epochtalk_server, :frontend_config, %{
api_key: System.get_env("API_KEY", "ABC123"),
frontend_url: System.get_env("FRONTEND_URL", "http://localhost:8000"),
backend_url: System.get_env("BACKEND_URL", "http://localhost:4000"),
newbie_enabled: get_env_cast_bool_with_default.("NEWBIE_ENABLED", "FALSE"),
Expand Down
2 changes: 1 addition & 1 deletion lib/epochtalk_server_web/endpoint.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ defmodule EpochtalkServerWeb.Endpoint do
# origins: "*",
origins: ~r{^https?://(.*\.)?epochtalk\.com$},
allow_headers: :all,
expose_headers: ["epoch-viewer"]
expose_headers: ["epoch-viewer", "api-key"]

socket "/socket", EpochtalkServerWeb.UserSocket,
websocket: true,
Expand Down
35 changes: 35 additions & 0 deletions lib/epochtalk_server_web/plugs/check_api_key.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
defmodule EpochtalkServerWeb.Plugs.CheckAPIKey do
@moduledoc """
Plug that tracks user IP address for PUT POST or PATCH operations
"""
use Plug.Builder
import Plug.Conn

@env Mix.env()
@methods ~w(GET POST PUT PATCH)

plug(:check_api_key)

@doc """
Validates and checks API key sent from frontend against one stored on backend
"""
def check_api_key(conn, _opts) do
%{method: method} = conn

if method in @methods and @env != :test do
try_verify(conn)
else
conn
end
end

defp try_verify(conn) do
config = Application.get_env(:epochtalk_server, :frontend_config)
api_key = config[:api_key]
[req_api_key] = get_req_header(conn, "api-key")

if api_key == req_api_key,
do: conn,
else: raise(Plug.BadRequestError)
end
end
1 change: 1 addition & 0 deletions lib/epochtalk_server_web/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ defmodule EpochtalkServerWeb.Router do
plug EpochtalkServerWeb.Plugs.TrackIp
# Track user last active
plug EpochtalkServerWeb.Plugs.UserLastActive
plug EpochtalkServerWeb.Plugs.CheckAPIKey
end

pipeline :enforce_auth do
Expand Down

0 comments on commit a1b95a6

Please sign in to comment.