Creating custom controller callbacks with Pow

The callbacks is the wrong place to deal with this. You would want it to be inserted in a transaction so if the subscription insert fails, the user won’t be created. There’re multiple ways to deal with it, but if all users inserted needs to have a subscription created along it, then I would keep it simple and just deal with it in the user changeset:

defmodule MyApp.Users.User do
  use Ecto.Schema
  use Pow.Ecto.Schema

  schema "users" do
    has_one :subscription, MyApp.Users.Subscription

    pow_user_fields()

    timestamps()
  end

  def changeset(user_or_changeset, attrs) do
    user
    |> pow_changeset(attrs)
    |> maybe_add_subscription()
  end

  defp maybe_add_subscription(changeset) do
    case Ecto.get_meta(changeset.data, :state) do
      :built  -> add_subscription(changeset)
      :loaded -> changeset
    end
  end
  
  defp add_subscription(changeset) do
    Ecto.Changeset.cast_assoc(changeset, :subscription, with: &MyApp.Users.Subscription.changeset/2)
  end
end

If you need more control over the flow, then I would either set up a custom controller and/or custom context module.

(Also, as you guessed the controller callbacks module you’ve set up is only for custom extensions)

1 Like