Packages
shopifex
2.1.11
2.4.0
2.3.0
2.2.2
2.2.1
2.2.0
2.1.20
2.1.19
2.1.18
2.1.17
2.1.16
2.1.15
2.1.14
2.1.13
2.1.12
2.1.11
2.1.10
2.1.9
2.1.8
2.1.7
2.1.6
2.1.5
2.1.4
2.1.3
2.1.2
2.1.1
2.1.0
2.0.1
2.0.0
1.1.1
1.1.0
1.0.1
1.0.0
0.6.2
0.6.1
0.6.0
0.5.7
0.5.6
0.5.5
0.5.4
0.5.3
0.5.2
0.5.1
0.5.0
0.4.1
0.4.0
0.3.6
0.3.5
0.3.4
0.3.3
0.3.2
0.3.1
0.3.0
0.2.1
0.2.0
0.1.5
0.1.4
0.1.3
0.1.2
0.1.1
0.1.0
Phoenix boilerplate for Shopify Embedded App SDK
Current section
Files
Jump to
Current section
Files
lib/shopifex/plug/shopify_session.ex
defmodule Shopifex.Plug.ShopifySession do
import Plug.Conn
import Phoenix.Controller
require Logger
def init(options) do
# initialize options
options
end
def call(conn, _) do
token = get_token_from_conn(conn) || Guardian.Plug.current_token(conn)
case Shopifex.Guardian.resource_from_token(token) do
{:ok, shop, claims} ->
locale = get_locale(conn, claims)
host = get_host(conn, claims)
Shopifex.Plug.build_session(conn, shop, host, locale)
_ ->
initiate_new_session(conn)
end
end
defp get_token_from_conn(%Plug.Conn{params: %{"token" => token}}), do: token
defp get_token_from_conn(_), do: nil
defp initiate_new_session(conn) do
expected_hmac = Shopifex.Plug.build_hmac(conn)
received_hmac = Shopifex.Plug.get_hmac(conn)
if expected_hmac == received_hmac do
conn
|> do_new_session()
else
Logger.info("Invalid HMAC, expected #{expected_hmac}")
respond_invalid(conn)
end
end
defp do_new_session(conn = %{params: %{"shop" => shop_url}}) do
case Shopifex.Shops.get_shop_by_url(shop_url) do
nil ->
redirect_to_install(conn, shop_url)
shop ->
locale = get_locale(conn)
host = get_host(conn)
Shopifex.Plug.build_session(conn, shop, host, locale)
end
end
defp redirect_to_install(conn, shop_url) do
Logger.info("Initiating shop installation for #{shop_url}")
install_url =
"https://#{shop_url}/admin/oauth/authorize?client_id=#{Application.fetch_env!(:shopifex, :api_key)}&scope=#{Application.fetch_env!(:shopifex, :scopes)}&redirect_uri=#{Application.fetch_env!(:shopifex, :redirect_uri)}"
conn
|> redirect(external: install_url)
|> halt()
end
defp respond_invalid(conn) do
conn
|> put_view(ShopifexWeb.AuthView)
|> put_layout({ShopifexWeb.LayoutView, "app.html"})
|> render("select-store.html")
|> halt()
end
defp get_locale(conn, token_claims \\ %{})
defp get_locale(%Plug.Conn{params: %{"locale" => locale}}, _token_claims), do: locale
defp get_locale(_conn, token_claims),
do: Map.get(token_claims, "loc", Application.get_env(:shopifex, :default_locale, "en"))
defp get_host(conn, token_claims \\ %{})
defp get_host(%Plug.Conn{params: %{"host" => host}}, _token_claims), do: host
defp get_host(_conn, token_claims),
do: Map.get(token_claims, "host")
end