Skip to content

Commit

Permalink
use router for cors
Browse files Browse the repository at this point in the history
  • Loading branch information
yujonglee committed Oct 8, 2024
1 parent 2dbf224 commit f435b00
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
21 changes: 21 additions & 0 deletions core/lib/canary_web/cors_router.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
defmodule CanaryWeb.CORSRouter do
use Corsica.Router,
max_age: 300,
allow_credentials: false,
allow_headers: ["Authorization", "Content-Type"],
origins: {CanaryWeb.CORSRouter, :is_allowed_origin?, []}

def is_allowed_origin?(_conn, origin) do
%URI{host: host} = URI.parse(origin)
host in hosts()
end

defp hosts() do
Cachex.fetch!(:cache, :origin, fn _ ->
hosts = Canary.Accounts.Key.allowed_hosts!()
{:commit, hosts, expire: :timer.seconds(15)}
end)
end

resource "/api/v1/*"
end
1 change: 1 addition & 0 deletions core/lib/canary_web/endpoint.ex
Original file line number Diff line number Diff line change
Expand Up @@ -65,5 +65,6 @@ defmodule CanaryWeb.Endpoint do
plug Plug.Session, @session_options

plug CanaryWeb.Plug.Subdomain, CanaryWeb.SubdomainRouter
plug CanaryWeb.CORSRouter
plug CanaryWeb.Router
end
6 changes: 0 additions & 6 deletions core/lib/canary_web/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,6 @@ defmodule CanaryWeb.Router do

pipeline :api do
plug :accepts, ["json"]

plug Corsica,
max_age: 300,
allow_credentials: true,
allow_headers: ["Authorization"],
origins: {CanaryWeb.Router, :is_allowed_origin?, []}
end

def is_allowed_origin?(_conn, origin) do
Expand Down

0 comments on commit f435b00

Please sign in to comment.