AutoAdminUser

Bootstrap an admin account on app startup from an environment variable.

Every Phoenix app needs an initial admin user in production. This is always the same pattern: read an env var, check if the user exists, create one if not. AutoAdminUser handles this as a oneshot Task in your supervision tree with sensible defaults for apps using mix phx.gen.auth.

Installation

Add auto_admin_user to your list of dependencies in mix.exs:

def deps do
  [
    {:auto_admin_user, "~> 0.1.0"}
  ]
end

Quick start

If you generated your auth with mix phx.gen.auth Accounts User users, add one line to your supervision tree:

# application.ex
children = [
  MyApp.Repo,
  {AutoAdminUser, context: MyApp.Accounts},
  MyAppWeb.Endpoint
]

Set the ADMIN_EMAIL environment variable and you're done. On startup, AutoAdminUser will:

  1. Read ADMIN_EMAIL
  2. Call MyApp.Accounts.get_user_by_email/1 to check if the user exists
  3. If not, call MyApp.Accounts.register_user/1 with a random 32-character password
  4. Log the result

If ADMIN_EMAIL is unset or empty, it does nothing.

Options

Option Type Default Description
:context module required* Your accounts context module
:env_var string "ADMIN_EMAIL" Environment variable to read
:find atom or fn/1 :get_user_by_email Look up an existing user by email
:create atom or fn/1 :register_user Create the user (receives %{email:, password:})
:after_create fn/1 or nil nil Called with the newly created user
:password_length integer 32 Length of the random password

* Not required if both :find and :create are provided as functions.

When :find or :create is an atom, it's called as a function on the :context module.

Examples

Custom create function

If your app uses a different function name to create admin users:

{AutoAdminUser, context: MyApp.Accounts, create: :create_admin}

After-create hook

Send a password reset email after bootstrapping:

{AutoAdminUser,
  context: MyApp.Accounts,
  after_create: fn user ->
    MyApp.Accounts.deliver_user_reset_password_instructions(
      user, &"/users/reset_password/#{&1}")
  end}

Custom env var

{AutoAdminUser, context: MyApp.Accounts, env_var: "SUPERADMIN_EMAIL"}

Fully custom (no context module)

{AutoAdminUser,
  env_var: "ADMIN_EMAIL",
  find: fn email -> MyApp.Repo.get_by(MyApp.User, email: email) end,
  create: fn params -> MyApp.Repo.insert(MyApp.User.changeset(%MyApp.User{}, params)) end}

Documentation

Full documentation is available at hexdocs.pm/auto_admin_user.

License

MIT - see LICENSE for details.