Skip to content

Instantly share code, notes, and snippets.

@noelworden
Created July 21, 2020 15:01
Show Gist options
  • Select an option

  • Save noelworden/5cbf62679d6ccb8a54da06a371fc01ed to your computer and use it in GitHub Desktop.

Select an option

Save noelworden/5cbf62679d6ccb8a54da06a371fc01ed to your computer and use it in GitHub Desktop.
#helpers
defmodule Finance.Schemas.User do
  @moduledoc """
  The location of this schema has changed from the default placement upon
  installation (`mix pow.install`). If using the Pow library docs to make any
  changes, a reference to `Finance.Users.User` should be replaced with
  `Finance.Schemas.User`
  """

  use Finance.Schema
  use Pow.Ecto.Schema

  @generate_password_length 20

  schema "users" do
    pow_user_fields()

    timestamps()
  end

  def create_changeset(user \\ %__MODULE__{}, attrs) do
    user
    |> pow_user_id_field_changeset(attrs)
    |> generate_password_changeset()
  end

  def generate_password_changeset(user \\ %__MODULE__{}) do
    # source of password generator: https://stackoverflow.com/a/41735582/154703
    password =
      :crypto.strong_rand_bytes(@generate_password_length)
      |> Base.encode64()
      |> binary_part(0, @generate_password_length)

    user
    |> pow_password_changeset(%{
      password: password,
      password_confirmation: password
    })
  end
end

The IEx scripts

  • Create:
    %{email: "[email protected]"} |> Finance.Schemas.User.create_changeset() |> Finance.Repo.insert!()
    
  • Update:
    Finance.Schemas.User |> Finance.Repo.get_by!(email: "[email protected]") |> Finance.Schemas.User.generate_password_changeset() |> Finance.Repo.update()
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment