通过 Comeonin 进行用户身份验证的 Phoenix 框架错误

Phoenix Framework Error with User Authentication via Comeonin

这是我遇到的错误:

Wrong type. The password and hash need to be strings.

它指向我的 web/controllers/auth.ex 文件中的这一行:

user && checkpw(given_pass, user.password_hash) ->

这是这个函数中的一行:

  def login_by_email_and_pass(conn, email, given_pass, opts) do
    repo = Keyword.fetch!(opts, :repo)
    user = repo.get_by(Qlc.User, email: email)

    cond do
      user && checkpw(given_pass, user.password_hash) ->
        {:ok, login(conn, user)}
      user ->
        {:error, :unauthorized, conn}
      true ->
        dummy_checkpw()
        {:error, :not_found, conn}
    end
  end

此函数从 SessionController 模块的创建操作中调用:

  def create(conn, %{"session" => %{"email" => email, "password" => pass}}) do
    case Qlc.Auth.login_by_email_and_pass(conn, email, pass, repo: Repo) do
      {:ok, conn} ->
        conn
        |> put_flash(:info, "Welcome back!")
        |> redirect(to: page_path(conn, :index))
      {:error, _reason, conn} ->
        conn
        |> put_flash(:error, "Invalid email/password combination")
        |> render("new.html")
    end
  end 

如何解决这个错误?我不确定为什么密码和散列不是字符串 and/or 我该如何解决这个问题。

当您提供非字符串值作为 passhash(如错误消息所示)时,可能会发生这种情况。

鉴于您提供的内容:

def create(conn, %{"session" => %{"email" => email, "password" => pass}}) do

我们知道通行证肯定存在。该行:

user && checkpw(given_pass, user.password_hash)

会导致错误的是 password_hash 对用户来说是 nil。您可以通过以下方式解决此问题:

user && checkpw(given_pass, Map.get(user, :password_hash, ""))`