3
votes

I'm trying to test if a user id is equal to the resource id using guardian auth. If there is no current token and I try to go to a url that is checking for a token I get this error function nil.id/0 is undefined or private. I come from a ruby background and I don't know why it's saying .id is a function? and why this is throwing an error. Here is my code:

def index(conn, %{"user_id" => user_id}) do
    user = Repo.get(User, user_id)
           |> Repo.preload(:projects)
    cond do
      user.id == Guardian.Plug.current_resource(conn).id ->
        conn
        |> render("index.html", projects: user.projects, user: user)
      :error ->
        conn
        |> put_flash(:info, "No access")
        |> redirect(to: session_path(conn, :new))
    end
  end

If there is no current_resource then it prints this error. But if there is no current_resource I just want it to continue to the :error path and render the session path.

1

1 Answers

1
votes

This is because you're calling Guardian.Plug.current_resource(conn).id and Guardian.Plug.current_resource(conn) is nil. Since nil is an Atom in Elixir and so are modules, .id on it tries to call the function id on the module named nil (which doesn't exist). To fix this, you can add another check to see if Guardian.Plug.current_resource(conn) is not nil:

cond do
  (resource = Guardian.Plug.current_resource(conn)) && user.id == resource.id ->
    conn
    |> render("index.html", projects: user.projects, user: user)
  :error ->
    conn
    |> put_flash(:info, "No access")
    |> redirect(to: session_path(conn, :new))
end