From 25c13632b922f45dd742c5d77e13f1875fe20cae Mon Sep 17 00:00:00 2001 From: Gianni Chiappetta Date: Mon, 23 Jan 2023 23:42:12 -0500 Subject: [PATCH] feat: more robust host config Attempt to both: 1. Use the provided scheme from the conn if available 2. Include all ports except 80 --- lib/elixir_auth_google.ex | 18 ++++++++++---- test/elixir_auth_google_test.exs | 40 ++++++++++++++++++++++++++++---- 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/lib/elixir_auth_google.ex b/lib/elixir_auth_google.ex index d544342..0772171 100644 --- a/lib/elixir_auth_google.ex +++ b/lib/elixir_auth_google.ex @@ -25,12 +25,22 @@ defmodule ElixirAuthGoogle do `get_baseurl_from_conn/1` derives the base URL from the conn struct """ @spec get_baseurl_from_conn(conn) :: String.t() - def get_baseurl_from_conn(%{host: h, port: p}) when h == "localhost" do - "http://#{h}:#{p}" + def get_baseurl_from_conn(%{host: h, port: p, scheme: s}) when p != 80 do + "#{Atom.to_string(s)}://#{h}:#{p}" end - def get_baseurl_from_conn(%{host: h}) do - "https://#{h}" + def get_baseurl_from_conn(%{host: h, scheme: s}) do + "#{Atom.to_string(s)}://#{h}" + end + + def get_baseurl_from_conn(%{host: h} = conn) do + scheme = + case h do + "localhost" -> :http + _ -> :https + end + + get_baseurl_from_conn(Map.put(conn, :scheme, scheme)) end @doc """ diff --git a/test/elixir_auth_google_test.exs b/test/elixir_auth_google_test.exs index 6edd8e5..0db5802 100644 --- a/test/elixir_auth_google_test.exs +++ b/test/elixir_auth_google_test.exs @@ -5,24 +5,56 @@ defmodule ElixirAuthGoogleTest do import Mock - test "get_baseurl_from_conn(conn) detects the URL based on conn.host" do + test "get_baseurl_from_conn(conn) detects the URL based on conn.host HTTP" do conn = %{ host: "localhost", - port: 4000 + port: 4000, + scheme: :http } assert ElixirAuthGoogle.get_baseurl_from_conn(conn) == "http://localhost:4000" end - test "get_baseurl_from_conn(conn) detects the URL for production" do + test "get_baseurl_from_conn(conn) detects the URL based on conn.host HTTPS" do + conn = %{ + host: "localhost", + port: 4000, + scheme: :https + } + + assert ElixirAuthGoogle.get_baseurl_from_conn(conn) == "https://localhost:4000" + end + + test "get_baseurl_from_conn(conn) detects the URL for production HTTPS" do conn = %{ host: "dwyl.com", - port: 80 + port: 80, + scheme: :https } assert ElixirAuthGoogle.get_baseurl_from_conn(conn) == "https://dwyl.com" end + test "get_baseurl_from_conn(conn) detects the URL for production HTTP" do + conn = %{ + host: "dwyl.com", + port: 80, + scheme: :http + } + + assert ElixirAuthGoogle.get_baseurl_from_conn(conn) == "http://dwyl.com" + end + + test "get_baseurl_from_conn(conn) detects the URL for production HTTPS, non-standard port" do + conn = %{ + host: "dwyl.com", + port: 8080, + scheme: :https + } + + assert ElixirAuthGoogle.get_baseurl_from_conn(conn) == "https://dwyl.com:8080" + end + test "get Google login url" do conn = %{ host: "localhost",