-
Notifications
You must be signed in to change notification settings - Fork 4
/
push_controller.ex
67 lines (54 loc) · 1.74 KB
/
push_controller.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
defmodule PushExWeb.PushController do
@moduledoc false
use PushExWeb, :controller
def create(conn, params) do
PushEx.Instrumentation.Push.api_requested()
with_auth(conn, params, fn conn, params ->
with_params_validation(conn, params, fn conn, %{"channel" => channel, "data" => data, "event" => event} ->
wrapped_channel =
channel
|> List.wrap()
|> Enum.uniq()
wrapped_channel
|> Enum.each(fn channel ->
%PushEx.Push{channel: channel, data: data, event: event, unix_ms: PushEx.unix_ms_now()}
|> PushEx.push()
end)
PushEx.Instrumentation.Push.api_processed()
conn
|> maybe_close_connection()
|> json(%{channel: wrapped_channel, data: data, event: event})
end)
end)
end
defp maybe_close_connection(conn) do
if PushExWeb.Config.close_connections?() do
put_resp_header(conn, "connection", "close")
else
conn
end
end
defp with_params_validation(conn, params = %{"channel" => channel, "data" => _, "event" => event}, func)
when (is_bitstring(channel) or is_list(channel)) and is_bitstring(event) do
func.(conn, params)
end
defp with_params_validation(conn, _, _) do
conn
|> put_status(422)
|> json(%{error: "Invalid push arguments: channel, data, event are required."})
end
defp with_auth(conn, params, func) do
case PushEx.Config.controller_impl().auth(conn, params) do
:ok ->
func.(conn, params)
{:ok, conn = %Plug.Conn{}, params = %{}} ->
func.(conn, params)
{:error, conn = %Plug.Conn{}} ->
conn
:error ->
conn
|> put_status(403)
|> json(%{error: "Access forbidden"})
end
end
end