From 1436c7ff06619cc6ded136ade0b45252be5b3ae8 Mon Sep 17 00:00:00 2001 From: "byte[]" Date: Mon, 12 Oct 2020 03:01:20 -0400 Subject: [PATCH] update connecting ip in session --- lib/philomena_web/endpoint.ex | 1 + lib/philomena_web/plugs/last_ip_plug.ex | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 lib/philomena_web/plugs/last_ip_plug.ex diff --git a/lib/philomena_web/endpoint.ex b/lib/philomena_web/endpoint.ex index 0a14d1d3..e3a0f707 100644 --- a/lib/philomena_web/endpoint.ex +++ b/lib/philomena_web/endpoint.ex @@ -47,5 +47,6 @@ defmodule PhilomenaWeb.Endpoint do plug PhilomenaWeb.RenderTimePlug plug PhilomenaWeb.ReferrerPlug + plug PhilomenaWeb.LastIpPlug plug PhilomenaWeb.Router end diff --git a/lib/philomena_web/plugs/last_ip_plug.ex b/lib/philomena_web/plugs/last_ip_plug.ex new file mode 100644 index 00000000..9a4ea040 --- /dev/null +++ b/lib/philomena_web/plugs/last_ip_plug.ex @@ -0,0 +1,24 @@ +defmodule PhilomenaWeb.LastIpPlug do + @moduledoc """ + This plug stores the connecting IP address in the session. + ## Example + + plug PhilomenaWeb.LastIpPlug + """ + + alias Plug.Conn + + @doc false + @spec init(any()) :: any() + def init(opts), do: opts + + @doc false + @spec call(Conn.t(), any()) :: Conn.t() + def call(conn, _opts) do + {:ok, ip} = EctoNetwork.INET.cast(conn.remote_ip) + + conn + |> Conn.fetch_session() + |> Conn.put_session(:remote_ip, to_string(ip)) + end +end