Skip to content

Commit

Permalink
Merge pull request #120 from epochtalk/cors-config
Browse files Browse the repository at this point in the history
Cors config
  • Loading branch information
crod951 authored Feb 21, 2025
2 parents 7f6c195 + 4eb4200 commit 4ca9fc9
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
22 changes: 22 additions & 0 deletions config/runtime.exs
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,28 @@ config :epochtalk_server,
EpochtalkServerWeb.Endpoint,
Keyword.merge(base_endpoint_config, endpoint_config)

## Configure corsica
corsica_config_origins =
case config_env() do
:prod ->
get_env_or_raise_with_message.(
"CORS_ORIGINS",
"""
For example:
~r{^https?://(.*\.)?epochtalk\.com$}
"""
)

_ ->
"*"
end

corsica_config = %{
origins: corsica_config_origins
}

config :epochtalk_server, :corsica, corsica_config

## Configure mailer in prod
# (Other envs are hardcoded into their respective config/ files)
if config_env() == :prod do
Expand Down
13 changes: 12 additions & 1 deletion lib/epochtalk_server_web/endpoint.ex
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,18 @@ defmodule EpochtalkServerWeb.Endpoint do
plug RemoteIp

# cors configuration
plug Corsica, origins: "*", allow_headers: :all, expose_headers: ["epoch-viewer"]
plug Corsica,
origins: {__MODULE__, :valid_origin?, []},
allow_headers: :all,
allow_credentials: false,
allow_private_network: true,
expose_headers: ["epoch-viewer", "api-key", "x-api-key"]

def valid_origin?(conn, _origin) do
origins = Application.get_env(:epochtalk_server, :corsica).origins
options = %Corsica.Options{origins: origins}
Corsica.allowed_origin?(conn, options)
end

socket "/socket", EpochtalkServerWeb.UserSocket,
websocket: true,
Expand Down

0 comments on commit 4ca9fc9

Please sign in to comment.