Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Best way to add authentication check #624

Open
justinbkay opened this issue May 26, 2021 · 0 comments
Open

Best way to add authentication check #624

justinbkay opened this issue May 26, 2021 · 0 comments

Comments

@justinbkay
Copy link

What would be the best way to add additional checks for authentication? Adding a plug at the end of the protected pipeline is what I would assume would be the best way, but I'm not sure how to implement it. Here's what I have, which I think needs to remove the current user from the conn, but right now still redirects to infinity.

defmodule RefleqWeb.RequireActiveOrg do
  @moduledoc """
  Plug that checks for active org
  """

  @behaviour Plug

  alias Plug.Conn
  import Phoenix.Controller, only: [put_flash: 3]
  alias Pow.{Config, Plug}

  def init(config) do
    Config.get(config, :error_handler) || raise_no_error_handler!()
  end

  def call(conn, handler) do
    user = Plug.current_user(conn)
    |> Refleq.Repo.preload(:organization)

    user
    |> maybe_halt(conn, handler)
  end

  defp maybe_halt(user, conn, handler) do
    if (user.organization && user.organization.active == false) do
      conn
      |> do_delete
      |> put_flash(:error, "Your organization is not currently subscribed to ReflEQ. If you would like to access your data, please contact [email protected].")
      |> handler.call(:not_authenticated)
      |> Conn.halt()
    end

    conn
  end
  defp maybe_halt(_user, conn, _handler), do: conn

  defp raise_no_error_handler!,
    do: Config.raise_error("No :error_handler configuration option provided. It's required to set this when using #{inspect __MODULE__}.")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant