Skip to content

Instantly share code, notes, and snippets.

Created February 2, 2015 18:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3ce6914e4aa9f992d25c to your computer and use it in GitHub Desktop.
Save anonymous/3ce6914e4aa9f992d25c to your computer and use it in GitHub Desktop.
if get_req_header(conn, "https") == "on" or
get_req_header(conn, "x-forwarded-ssl") == "on" or
get_req_header(conn, "x-forwarded-scheme") == "https" or
(get_req_header(conn, "x-forwarded-proto") |> to_string |> String.split(",") |> Enum.at(0)) == "https" or
conn.scheme == :https do
"Secure Request"
else
"Request"
end
@chrismccord
Copy link

defmodule SecureRequest do
  import Plug.Conn
  def init(opts), do: opts

  def call(conn, _) do
    if get_req_header(conn, "https") == "on" or
       get_req_header(conn, "x-forwarded-ssl") == "on" or 
       get_req_header(conn, "x-forwarded-scheme") == "https" or
       proto_header(conn) == "https" or
       conn.scheme == :https do

       put_private(conn, :secure_request_scheme, :https)
    else
       put_private(conn, :secure_request_scheme, :http)
    end
  end

  def scheme(conn), do: conn.private[:secure_request_scheme]

  defp proto_header(conn) do
    get_req_header(conn, "x-forwarded-proto") |> to_string |> String.split(",") |> Enum.at(0)
  end
end


# router
pipeline :browser do
  plug SecureRequest
end


# controller
def create(conn, params) do
  case SecureRequest.scheme(conn) do
    :https -> ...
    :http  -> ...
  end
end

@chrismccord
Copy link

Option 2, overwrite conn.scheme:

defmodule SecureRequest do
  import Plug.Conn
  def init(opts), do: opts

  def call(conn, _) do
    if get_req_header(conn, "https") == "on" or
       get_req_header(conn, "x-forwarded-ssl") == "on" or 
       get_req_header(conn, "x-forwarded-scheme") == "https" or
       proto_header(conn) == "https" or
       conn.scheme == :https do

       put_in(conn.scheme, :https)
    else
       put_in(conn.scheme, :http)
    end
  end

  defp proto_header(conn) do
    get_req_header(conn, "x-forwarded-proto") |> to_string |> String.split(",") |> Enum.at(0)
  end
end


# router
pipeline :browser do
  plug SecureRequest
end


# controller
def create(%Conn{scheme: :https}, params) do
end
def create(%Conn{scheme: :http}, params) do
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment