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
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
Something like this could work:
Add it to the routes:
Or to the endpoint:
Originally posted by @danschultzer in https://github.com/danschultzer/pow/pull/296#issuecomment-541796456