Skip to content

Instantly share code, notes, and snippets.

@tarzan
Created July 3, 2018 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tarzan/9d2aad9bb0191587ae4a31e1ded0beb7 to your computer and use it in GitHub Desktop.
Save tarzan/9d2aad9bb0191587ae4a31e1ded0beb7 to your computer and use it in GitHub Desktop.
An alternative to https://github.com/ueberauth/guardian_backdoor, that doesn't create tokens twice in acceptance tests.
if Mix.env() == :test do
defmodule Detroit.Guardian.Plug.Backdoor do
@moduledoc """
This plug allows you to bypass authentication in acceptance tests by passing
the token needed to load the current resource directly to your Guardian module
via a query string parameter.
This is an abstraction from https://github.com/ueberauth/guardian_backdoor
but then without needing to create the actual token twice.
"""
import Plug.Conn
alias Detroit.Accounts
alias Guardian.Plug.Keys, as: GPlugKeys
@doc false
def init(opts) do
Enum.into(opts, %{})
end
@doc false
def call(conn, %{module: module}) do
with {:ok, user_id} <- fetch_user_id(conn),
false <- authenticated?(conn, module),
resource <- Accounts.get_user!(user_id) do
sign_in(conn, module, resource)
else
_ -> conn
end
end
defp fetch_user_id(conn) do
conn = fetch_query_params(conn)
Map.fetch(conn.params, "user_id")
end
defp sign_in(conn, module, resource) do
app_plug = Module.concat(module, :Plug)
app_plug.sign_in(conn, resource)
end
defp authenticated?(conn, _module) do
conn
|> get_session(GPlugKeys.token_key()) != nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment