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

Snippet: Pow registration, plug checking if the user has the address filled out in case it's a requirement to finish registration, and redirect them if it's missing. #13

Open
joepstender opened this issue Oct 22, 2019 · 0 comments

Comments

@joepstender
Copy link

Something like this could work:

defmodule MyAppWeb.EnsureHasAddress do
  @moduledoc false

  import Plug.Conn, only: [halt: 1]

  alias MyAppWeb.Router.Helpers, as: Routes
  alias Phoenix.Controller
  alias Plug.Conn
  alias Pow.Plug

  @doc false
  @spec init(any()) :: any()
  def init(opts), do: opts

  @doc false
  @spec call(Conn.t(), any()) :: Conn.t()
  def call(conn, _opts) do
    conn
    |> Plug.current_user()
    |> completed_registration?()
    |> maybe_halt(conn)
  end

  defp completed_registration?(%{address: nil}), do: false
  defp completed_registration?(_any), do: true

  defp maybe_halt(true, conn), do: conn
  defp maybe_halt(_any, conn) do
    conn
    |> Controller.redirect(to: Routes.registration_path(conn, :address_prompt))
    |> halt()
  end
end

Add it to the routes:

defmodule MyAppWeb.Router do
  use MyAppWeb, :router
  # ...

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
  end

  pipeline :require_address do
    plug MyAppWeb.EnsureHasAddress
  end

  scope "/", MyAppWeb do
    pipe_through [:browser, :require_address]

    # ...
  end

  # ...
end

Or to the endpoint:

defmodule MyAppWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :my_app

  # ...

  plug Plug.Session,
    store: :cookie,
    key: "_my_app_key",
    signing_salt: "secret"

  plug Pow.Plug.Session, otp_app: :my_app

  plug MyAppWeb.EnsureHasAddress

  # ...
end

Originally posted by @danschultzer in pow-auth/pow#296 (comment)

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