philomena/lib/philomena_web/plugs/user_attribution_plug.ex
SomewhatDamaged 3e7ee76fe2
Api create image (#105)
* added new method (POST) to /api/v1/json/images

* Cleaned up debug

* added require_authorization plug, fixed up issues with image_controller

* make user do work

* Fixed inefficient function use

* added api fingerprinting

* more robust

* corrected holdover from merging files
2020-05-01 00:40:57 -04:00

50 lines
1 KiB
Elixir

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
{:ok, remote_ip} = EctoNetwork.INET.cast(conn.remote_ip)
conn = Conn.fetch_cookies(conn)
user = Pow.Plug.current_user(conn)
attributes = [
ip: remote_ip,
fingerprint: fingerprint(conn, conn.path_info),
referrer: conn.assigns.referrer,
user: user,
user_agent: user_agent(conn)
]
conn
|> Conn.assign(:attributes, attributes)
end
defp user_agent(conn) do
case Conn.get_req_header(conn, "user-agent") do
[ua] -> ua
_ -> nil
end
end
defp fingerprint(conn, ["api" | _]) do
"a#{:erlang.crc32(user_agent(conn))}"
end
defp fingerprint(conn, _) do
conn.cookies["_ses"]
end
end