-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathcors_plug.ex
190 lines (158 loc) · 4.78 KB
/
cors_plug.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
defmodule CORSPlug do
import Plug.Conn
def defaults do
[
origin: "*",
credentials: true,
max_age: 1_728_000,
headers: [
"Authorization",
"Content-Type",
"Accept",
"Origin",
"User-Agent",
"DNT",
"Cache-Control",
"X-Mx-ReqToken",
"Keep-Alive",
"X-Requested-With",
"If-Modified-Since",
"X-CSRF-Token"
],
expose: [],
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
send_preflight_response?: true
]
end
@doc false
def call(conn, options) do
case {options[:send_preflight_response?], conn.method, get_req_header(conn, "access-control-request-method")} do
# Not a CORS preflight request
{_, "OPTIONS", []} ->
conn
{true, "OPTIONS", _} ->
conn
|> merge_resp_headers(add_cors_headers(conn, options))
|> send_resp(204, "")
|> halt()
{false, "OPTIONS", _} ->
merge_resp_headers(conn, add_cors_headers(conn, options))
{_, _, _} ->
merge_resp_headers(conn, add_cors_headers(conn, options))
end
end
@doc false
def init(options) do
options
|> prepare_cfg(Application.get_all_env(:cors_plug))
|> Keyword.update!(:expose, &Enum.join(&1, ","))
|> Keyword.update!(:methods, &Enum.join(&1, ","))
end
defp prepare_cfg(options, env) do
defaults()
|> Keyword.merge(env)
|> Keyword.merge(options)
end
# headers specific to OPTIONS request
defp add_cors_headers(conn = %Plug.Conn{method: "OPTIONS"}, options) do
add_cors_headers(%{conn | method: nil}, options) ++
[
{"access-control-max-age", "#{options[:max_age]}"},
{"access-control-allow-headers", allowed_headers(options[:headers], conn)},
{"access-control-allow-methods", options[:methods]}
]
end
# universal headers
defp add_cors_headers(conn, options) do
allowed_origin = origin(options[:origin], conn)
vary_header = vary_header(allowed_origin, get_resp_header(conn, "vary"))
vary_header ++ cors_headers(allowed_origin, options)
end
# When the origin doesn't match, dont send CORS headers
defp cors_headers(nil, _options) do
[]
end
defp cors_headers(allowed_origin, options) do
headers = [
{"access-control-allow-origin", allowed_origin},
{"access-control-expose-headers", options[:expose]}
]
if options[:credentials] do
[{"access-control-allow-credentials", "true"} | headers]
else
headers
end
end
# Allow all requested headers
defp allowed_headers(["*"], conn) do
case get_req_header(conn, "access-control-request-headers") do
[first | _tail] -> first
_ -> ""
end
end
defp allowed_headers(key, _conn) do
Enum.join(key, ",")
end
# return origin if it matches regex, otherwise nil
defp origin(%Regex{} = regex, conn) do
req_origin = conn |> request_origin() |> to_string()
if origins_match?(req_origin, regex), do: req_origin, else: nil
end
# get value if origin is a function
defp origin(fun, conn) when is_function(fun) do
case Function.info(fun, :arity) do
{:arity, 0} ->
origin(fun.(), conn)
{:arity, 1} ->
origin(fun.(conn), conn)
{:arity, arity} ->
raise """
Passing a function with arity #{arity} is not supported. Please use
one with arity 0 or 1 (in which case it will be passed the `conn`).
"""
end
end
# normalize non-list to list
defp origin(key, conn) when not is_list(key) do
key
|> List.wrap()
|> origin(conn)
end
# whitelist internal requests
defp origin([:self], conn) do
request_origin(conn) || "*"
end
# return "*" if origin list is ["*"]
defp origin(["*"], _conn) do
"*"
end
defp origin(origins, conn) when is_list(origins) do
req_origin = conn |> request_origin() |> to_string()
cond do
origin_in_list?(req_origin, origins) -> req_origin
"*" in origins -> "*"
true -> nil
end
end
def origin_in_list?(req_origin, origins) do
Enum.any?(origins, &origins_match?(req_origin, &1))
end
def origins_match?(req_origin, origin) when is_binary(origin) do
req_origin == origin
end
def origins_match?(req_origin, %Regex{} = origin) do
req_origin =~ origin
end
defp request_origin(%Plug.Conn{req_headers: headers}) do
Enum.find_value(headers, fn {k, v} -> k =~ ~r/^origin$/i && v end)
end
# Set the Vary response header
# see: https://www.w3.org/TR/cors/#resource-implementation
defp vary_header("*", _headers), do: []
defp vary_header(nil, _headers), do: []
defp vary_header(_allowed_origin, []), do: [{"vary", "Origin"}]
defp vary_header(_allowed_origin, headers) do
vary = Enum.join(["Origin" | headers], ", ")
[{"vary", vary}]
end
end