0
votes

Here's the error that I'm getting:

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

It's pointing to this line in my web/controllers/auth.ex file:

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

which is a line in this function:

  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

This function is called from the SessionController module's create action:

  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 

How can I solve this error? I'm not sure why the password and hash are not strings and/or how I can fix this.

1
Please provide the function (probably the controller) that calls this function as well as the parameters provided. It is very likely one of these parameters is nil. - Gazler
I've edited question to include the function call and the function itself. - Andrew Hendrie
Is it possible that user.password_hash is nil? - Gazler
Yes. Turns out that it was - everything is working now. Thank you! Post as an answer and I'll accept it. - Andrew Hendrie

1 Answers

2
votes

This can happen when you provide a non string value as either the pass or hash (as indicated by the error message.)

Given what you have provided:

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

We know pass definitely exists. The line:

user && checkpw(given_pass, user.password_hash)

Would cause an error is password_hash is nil for the user. You can fix this by doing:

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