Skip to content

Commit 21d5884

Browse files
committed
Content type check
1 parent 5ce1d4c commit 21d5884

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

lib/srh/http/base_router.ex

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ defmodule Srh.Http.BaseRouter do
55
alias Srh.Http.ResultEncoder
66

77
plug(:match)
8+
plug(Srh.Http.ContentTypeCheckPlug)
89
plug(Plug.Parsers, parsers: [:json], pass: ["application/json"], json_decoder: Jason)
910
plug(:dispatch)
1011

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

0 commit comments

Comments
 (0)