2019-11-17 19:29:07 +01:00
|
|
|
defmodule PhilomenaWeb.UserAttributionPlug do
|
|
|
|
@moduledoc """
|
|
|
|
This plug stores information about the current session for use in
|
|
|
|
model attribution.
|
|
|
|
|
|
|
|
## Example
|
|
|
|
|
|
|
|
plug PhilomenaWeb.UserAttributionPlug
|
|
|
|
"""
|
|
|
|
|
|
|
|
alias Plug.Conn
|
|
|
|
|
|
|
|
@doc false
|
|
|
|
@spec init(any()) :: any()
|
|
|
|
def init(opts), do: opts
|
|
|
|
|
|
|
|
@doc false
|
|
|
|
@spec call(Plug.Conn.t(), any()) :: Plug.Conn.t()
|
|
|
|
def call(conn, _opts) do
|
2019-11-17 19:52:59 +01:00
|
|
|
{:ok, remote_ip} = EctoNetwork.INET.cast(conn.remote_ip)
|
2019-11-17 19:29:07 +01:00
|
|
|
conn = Conn.fetch_cookies(conn)
|
2020-07-28 22:56:26 +02:00
|
|
|
user = conn.assigns.current_user
|
2019-11-19 01:33:27 +01:00
|
|
|
|
2020-01-11 05:20:19 +01:00
|
|
|
attributes = [
|
|
|
|
ip: remote_ip,
|
2020-05-01 06:40:57 +02:00
|
|
|
fingerprint: fingerprint(conn, conn.path_info),
|
2020-01-11 05:20:19 +01:00
|
|
|
referrer: conn.assigns.referrer,
|
|
|
|
user: user,
|
|
|
|
user_agent: user_agent(conn)
|
|
|
|
]
|
2019-11-17 19:29:07 +01:00
|
|
|
|
|
|
|
conn
|
|
|
|
|> Conn.assign(:attributes, attributes)
|
|
|
|
end
|
|
|
|
|
|
|
|
defp user_agent(conn) do
|
|
|
|
case Conn.get_req_header(conn, "user-agent") do
|
|
|
|
[ua] -> ua
|
2020-01-11 05:20:19 +01:00
|
|
|
_ -> nil
|
2019-11-17 19:29:07 +01:00
|
|
|
end
|
|
|
|
end
|
2020-05-01 06:40:57 +02:00
|
|
|
|
|
|
|
defp fingerprint(conn, ["api" | _]) do
|
|
|
|
"a#{:erlang.crc32(user_agent(conn))}"
|
|
|
|
end
|
|
|
|
|
|
|
|
defp fingerprint(conn, _) do
|
|
|
|
conn.cookies["_ses"]
|
|
|
|
end
|
2020-01-11 05:20:19 +01:00
|
|
|
end
|