philomena/lib/philomena_web/plugs/referrer_plug.ex

39 lines
787 B
Elixir
Raw Normal View History

2019-11-17 19:18:21 +01:00
defmodule PhilomenaWeb.ReferrerPlug do
2019-11-16 01:40:32 +01:00
@moduledoc """
This plug assigns the HTTP Referer, if it exists. Note the misspelling
in the standard.
## Example
2019-11-17 19:18:21 +01:00
plug PhilomenaWeb.ReferrerPlug
2019-11-16 01:40:32 +01:00
"""
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
2020-09-28 05:47:32 +02:00
conn
|> Conn.assign(:referrer, referer(conn))
|> Conn.assign(:ajax?, ajax?(conn))
end
defp referer(conn) do
2019-11-16 01:40:32 +01:00
case Conn.get_req_header(conn, "referer") do
2020-09-28 05:47:32 +02:00
[] -> "/"
[referrer] -> referrer
end
end
2019-11-16 01:40:32 +01:00
2020-09-28 05:47:32 +02:00
defp ajax?(conn) do
case Conn.get_req_header(conn, "x-requested-with") do
[value] -> String.downcase(value) == "xmlhttprequest"
_ -> false
2019-11-16 01:40:32 +01:00
end
end
2020-01-11 05:20:19 +01:00
end