Creating seed data with Pow

Hi all,

I have a beginners’ question and I was wondering if anyone here might be able to help me.

I’ve followed this tutorial to set up Pow for my API and everything worked well, but then I wanted to create some test users via seeds.exs and then I realised that it’s not going to be straightforward. My create_user logic sits inside my registration controller, but even if I pull out Pow.Plug.create_user(user_params) into a user context it would still need a connection parameter. I think phx.gen.auth creates an account context with simple logic like this:

def register_user(attrs) do
   %User{}
   |> User.registration_changeset(attrs)
   |> Repo.insert()
end

Whereas if I look at MyApp.Users.User I can only see the schema definition with pow_user_fields(). I feel that going around the Pow.Plug.create_user with my own changesets and repo inserts isn’t a good idea because Pow is meant to hash the password and do a few other important operations. With this in mind, how would you go about creating seed data with Pow? Many thanks! :frowning:

Ok, I solved it by creating the following method inside my user module:

  def create(attrs) do
    %__MODULE__{}
    |> pow_changeset(attrs)
    |> case do
      changeset = %{valid?: true} ->
        Repo.insert(changeset)
      %{valid?: false, errors: e} ->
        {:error, e}
       end
  end
2 Likes

This is the exact problem I am facing as a beginner. Could you share you context defmodule?

Sure! You can find my create function here. Here is how it’s used in the seeds file.

2 Likes

Thank you!