Created
July 3, 2018 19:12
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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