Spaces:
Sleeping
Sleeping
Scott Hiett
commited on
Commit
·
21d5884
1
Parent(s):
5ce1d4c
Content type check
Browse files
lib/srh/http/base_router.ex
CHANGED
@@ -5,6 +5,7 @@ defmodule Srh.Http.BaseRouter do
|
|
5 |
alias Srh.Http.ResultEncoder
|
6 |
|
7 |
plug(:match)
|
|
|
8 |
plug(Plug.Parsers, parsers: [:json], pass: ["application/json"], json_decoder: Jason)
|
9 |
plug(:dispatch)
|
10 |
|
|
|
5 |
alias Srh.Http.ResultEncoder
|
6 |
|
7 |
plug(:match)
|
8 |
+
plug(Srh.Http.ContentTypeCheckPlug)
|
9 |
plug(Plug.Parsers, parsers: [:json], pass: ["application/json"], json_decoder: Jason)
|
10 |
plug(:dispatch)
|
11 |
|
lib/srh/http/content_type_check_plug.ex
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
defmodule Srh.Http.ContentTypeCheckPlug do
|
2 |
+
import Plug.Conn
|
3 |
+
|
4 |
+
def init(opts), do: opts
|
5 |
+
|
6 |
+
def call(conn, _opts) do
|
7 |
+
# Only parse for POST, PUT, PATCH, and DELETE requests, which is what Plug.Parsers does
|
8 |
+
case conn.method do
|
9 |
+
"POST" ->
|
10 |
+
check_content_type(conn)
|
11 |
+
|
12 |
+
"PUT" ->
|
13 |
+
check_content_type(conn)
|
14 |
+
|
15 |
+
"PATCH" ->
|
16 |
+
check_content_type(conn)
|
17 |
+
|
18 |
+
"DELETE" ->
|
19 |
+
check_content_type(conn)
|
20 |
+
|
21 |
+
# All other methods can proceed
|
22 |
+
_ ->
|
23 |
+
conn
|
24 |
+
end
|
25 |
+
end
|
26 |
+
|
27 |
+
defp check_content_type(conn) do
|
28 |
+
case get_req_header(conn, "content-type") do
|
29 |
+
["application/json"] ->
|
30 |
+
# Proceed, this is the valid content type for SRH
|
31 |
+
conn
|
32 |
+
|
33 |
+
# Either missing, or a type that we don't support
|
34 |
+
other ->
|
35 |
+
# Return a custom error, ensuring the same format as the other errors
|
36 |
+
conn
|
37 |
+
|> put_resp_content_type("application/json")
|
38 |
+
|> send_resp(400, Jason.encode!(%{error: "Invalid content type. Expected application/json."}))
|
39 |
+
|> halt()
|
40 |
+
end
|
41 |
+
end
|
42 |
+
end
|