如何使用 ExMachina 创建一个可以登录的帐户?

问题描述 投票:0回答:1

我可以使用我的 Factory 将新用户保存到数据库,但当我尝试登录时收到“无效的用户名或密码”。 如何在我的 Factory 中创建我也可以登录的用户? 如果我尝试在没有设置 hashed_password 的情况下插入用户,则该用户无效,但我想我不应该自己手动设置它?

使用 iex 运行 Phoenix,以确保将用户插入到与运行服务器相同的环境中:

$ iex -S mix phx.server

iex(4)> Factory.insert(:user)
[debug] QUERY OK db=3.6ms queue=1.9ms idle=472.0ms
INSERT INTO "users" ("confirmed_at","email","hashed_password","inserted_at","updated_at") VALUES ($1,$2,$3,$4,$5) RETURNING "id" [~N[2023-08-06 06:00:23], "[email protected]", "password", ~N[2023-08-06 06:00:23], ~N[2023-08-06 06:00:23]]
↳ anonymous fn/4 in :elixir.eval_external_handler/1, at: src/elixir.erl:309
#HealthTracker.Accounts.User<
  __meta__: #Ecto.Schema.Metadata<:loaded, "users">,
  id: 9,
  email: "[email protected]",
  confirmed_at: ~N[2023-08-06 06:00:23],
  inserted_at: ~N[2023-08-06 06:00:23],
  updated_at: ~N[2023-08-06 06:00:23],
  ...
>

HealthTracker.Factory

defmodule HealthTracker.Factory do
  use ExMachina.Ecto, repo: HealthTracker.Repo

  def user_factory do
    %HealthTracker.Accounts.User{
      email: sequence(:email, &"email-#{&1}@example.com"),
      password: "password",
      hashed_password: "password", # Can save, but invalid content so i can't log in.
      confirmed_at: DateTime.utc_now()
    }
  end

end

HealthTracker.Accounts.User

defmodule HealthTracker.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :email, :string
    field :password, :string, virtual: true, redact: true
    field :hashed_password, :string, redact: true
    field :confirmed_at, :naive_datetime

    timestamps()
  end

  def registration_changeset(user, attrs, opts \\ []) do
    user
    |> cast(attrs, [:email, :password])
    |> validate_email(opts)
    |> validate_password(opts)
  end


  defp validate_email(changeset, opts) do
    changeset
    |> validate_required([:email])
    |> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces")
    |> validate_length(:email, max: 160)
    |> maybe_validate_unique_email(opts)
  end

  defp validate_password(changeset, opts) do
    changeset
    |> validate_required([:password])
    |> validate_length(:password, min: 12, max: 72)
    # Examples of additional password validation:
    # |> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character")
    # |> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character")
    # |> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character")
    |> maybe_hash_password(opts)
  end

  defp maybe_hash_password(changeset, opts) do
    hash_password? = Keyword.get(opts, :hash_password, true)
    password = get_change(changeset, :password)

    if hash_password? && password && changeset.valid? do
      changeset
      # If using Bcrypt, then further validate it is at most 72 bytes long
      |> validate_length(:password, max: 72, count: :bytes)
      # Hashing could be done with `Ecto.Changeset.prepare_changes/2`, but that
      # would keep the database transaction open longer and hurt performance.
      |> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password))
      |> delete_change(:password)
    else
      changeset
    end
  end

  defp maybe_validate_unique_email(changeset, opts) do
    if Keyword.get(opts, :validate_email, true) do
      changeset
      |> unsafe_validate_unique(:email, HealthTracker.Repo)
      |> unique_constraint(:email)
    else
      changeset
    end
  end

  @doc """
  A user changeset for changing the email.

  It requires the email to change otherwise an error is added.
  """
  def email_changeset(user, attrs, opts \\ []) do
    user
    |> cast(attrs, [:email])
    |> validate_email(opts)
    |> case do
      %{changes: %{email: _}} = changeset -> changeset
      %{} = changeset -> add_error(changeset, :email, "did not change")
    end
  end

  @doc """
  A user changeset for changing the password.

  ## Options

    * `:hash_password` - Hashes the password so it can be stored securely
      in the database and ensures the password field is cleared to prevent
      leaks in the logs. If password hashing is not needed and clearing the
      password field is not desired (like when using this changeset for
      validations on a LiveView form), this option can be set to `false`.
      Defaults to `true`.
  """
  def password_changeset(user, attrs, opts \\ []) do
    user
    |> cast(attrs, [:password])
    |> validate_confirmation(:password, message: "does not match password")
    |> validate_password(opts)
  end

  @doc """
  Confirms the account by setting `confirmed_at`.
  """
  def confirm_changeset(user) do
    now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
    change(user, confirmed_at: now)
  end

  @doc """
  Verifies the password.

  If there is no user or the user doesn't have a password, we call
  `Bcrypt.no_user_verify/0` to avoid timing attacks.
  """
  def valid_password?(%HealthTracker.Accounts.User{hashed_password: hashed_password}, password)
      when is_binary(hashed_password) and byte_size(password) > 0 do
    Bcrypt.verify_pass(password, hashed_password)
  end

  def valid_password?(_, _) do
    Bcrypt.no_user_verify()
    false
  end

  @doc """
  Validates the current password otherwise adds an error to the changeset.
  """
  def validate_current_password(changeset, password) do
    if valid_password?(changeset.data, password) do
      changeset
    else
      add_error(changeset, :current_password, "is not valid")
    end
  end
end
authentication elixir integration-testing phoenix-framework
1个回答
0
投票

我能够通过正确散列保存到数据库的密码来修复它。

查看更新后的工厂:

defmodule HealthTracker.Factory do
  use ExMachina.Ecto, repo: HealthTracker.Repo
  alias Bcrypt

  def user_factory do
    %HealthTracker.Accounts.User{
      email: sequence(:email, &"email-#{&1}@example.com"),
      password: "password",
      hashed_password: Bcrypt.hash_pwd_salt("password"),
      confirmed_at: DateTime.utc_now()
    }
  end
© www.soinside.com 2019 - 2024. All rights reserved.