benonymus

benonymus

Protocol Enumerable not implemented for error with guardian login

Hey I a trying to make a login system for my phoenix app, but I am having an error on successful login attempt:
# protocol Enumerable not implemented for %Userteam1.Web.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">, id: 1, inserted_at: ~N[2018-08-19 09:10:38.661295], name: "bence", password: nil, password_hash: "$2b$12$EEH/mgGuM1GyKHkUSIJG..THKJ6W/0iN/tWH6FiikZ4dRjGqPwt3G", role: #Ecto.Association.NotLoaded<association :role is not loaded>, role_id: 1, team: #Ecto.Association.NotLoaded<association :team is not loaded>, team_id: nil, updated_at: ~N[2018-08-19 09:10:38.661303]}. This protocol is implemented for: DBConnection.PrepareStream, DBConnection.Stream, Date.Range, Ecto.Adapters.SQL.Stream, File.Stream, Function, GenEvent.Stream, HashDict, HashSet, IO.Stream, List, Map, MapSet, Postgrex.Stream, Range, Stream

my controller for login looks like this:

def create(conn, %{"session" => %{"name" => name, "password" => password}}) do
    case Userteam1.Web.name_password_auth(name, password) do
      {:ok, user} ->
        IO.inspect(user)

        conn
        |> put_flash(:info, "Successfully signed in")
        |> Guardian.encode_and_sign(user)
        |> redirect(to: user_path(conn, :index))

      {:error, _reason} ->
        conn
        |> put_flash(:error, "Invalid name or password")
        |> render("new.html")
    end
  end

and my schema that it is trying to load looks like this:

  schema "users" do
    field(:name, :string)
    field(:password_hash, :string)
    field(:password, :string, virtual: true)
    belongs_to(:role, Userteam1.Role)
    belongs_to(:team, Userteam1.Team)
    timestamps()
  end

How can this be fixed?

Marked As Solved

stephane

stephane

Did you config guardian ? (config.exs)

config :my_app, MyApp.Guardian,
       issuer: "my_app",
       secret_key: "Secret key. You can use `mix guardian.gen.secret` to get one"

Also Liked

idi527

idi527

Dog.UserManager.Guardian.Plug != Guardian.Plug

Seems like you’ve confused one with the other because of

alias Dog.{UserManager, UserManager.User, UserManager.Guardian}
7stud

7stud

First time trying Guardian–I did not know that!

Seems like you’ve confused one with the other because of

alias Dog.{UserManager, UserManager.User, UserManager.Guardian}

And, I checked that line to make sure that Guardian.Plug was indeed equivalent to Dog.UserManager.Guardian.Plug! All that code is from the official Guardian “Getting Started Tutorial”.

And, the route problem I was having was due to the tutorial alternately using “/protected” and “/secret” to refer to the Guardian protected route.

By the way, things work when I do:

 alias Dog.{UserManager, UserManager.User, UserManager.Guardian}
 ...
 new_conn = Guardian.Plug.sign_in(conn, user)

So, I guess I was looking at the wrong docs??? This is what my lib/dog/user_manager/guardian.ex file looks like:

defmodule Dog.UserManager.Guardian do
  use Guardian, otp_app: :dog
  alias Dog.UserManager

  def subject_for_token(user, _claims) do
    # You can use any value for the subject of your token but
    # it should be useful in retrieving the resource later, see
    # how it being used on `resource_from_claims/1` function.
    # A unique `id` is a good subject, a non-unique email address
    # is a poor subject.

    {:ok, to_string(user.id)}
  end

  def resource_from_claims(%{"sub" => id}) do
    # Here we'll look up our resource from the claims, the subject can be
    # found in the `"sub"` key. In `above subject_for_token/2` we returned
    # the resource id so here we'll rely on that to look it up.

    case UserManager.get_user(id) do
      nil -> {:error, :user_not_found}
      user -> {:ok, user}
    end
  end

end

I guess the line:

use Guardian, otp_app: :dog

injects a Plug module? I looked at the source code for the Guardian module:

 defmacro __using__(opts \\ []) do
    otp_app = Keyword.get(opts, :otp_app)

    # credo:disable-for-next-line Credo.Check.Refactor.LongQuoteBlocks
    quote do
      @behaviour Guardian

      if Code.ensure_loaded?(Plug) do
        __MODULE__
        |> Module.concat(:Plug)    
        |> Module.create(  ## CREATES THE Dog.UserManager.Guardian.Plug MODULE
          quote do
            use Guardian.Plug, unquote(__MODULE__)
          end,
          Macro.Env.location(__ENV__)
        )
      end

And Guardian.Plug’s __using__() function looks like this:

   defmacro __using__(impl) do
      quote do
        ...
        ...
        def sign_in(conn, resource, claims \\ %{}, opts \\ []),
          do: Guardian.Plug.sign_in(conn, implementation(), resource, claims, opts)

And, there’s the two argument sign_in() function that I lucked into; and, like you said, the way I was calling it originally:

Guardian.Plug.sign_in(conn, Guaridan, user)

matched the parameter variable claims to user.

lol. And the original solution to this question was:

ok found something, I changed it into this:
|> Guardian.Plug.sign_in(user)

Thanks idiot!

NobbZ

NobbZ

Guardian.encode_and_sign/4 does not return a Plug.Conn.t, nor anything that would implement the Enumerable protocol.

Please give the Getting Started of guardian another read and try to incorporate the things you learned there into your application.

idi527

idi527

Your app actually fails at this line: https://github.com/ueberauth/guardian/blob/9ed23acbef1ddfde5a79c139570fada9399b0877/lib/guardian.ex#L573

Looks like you are passing your user as claims.

idi527

idi527

How do you know that?

See the stacktrace:

* elixir /home/build/elixir/lib/elixir/lib/enum.ex:1Enumerable.impl_for!/1
* elixir /home/build/elixir/lib/elixir/lib/enum.ex:141Enumerable.reduce/3
* elixir lib/enum.ex:3015Enum.reverse/1
* elixir lib/enum.ex:2647Enum.to_list/1
* elixir lib/map.ex:181Map.new_from_enum/1
* guardian lib/guardian.ex:573Guardian.encode_and_sign/4 # <-- this is where user=claims 
* guardian lib/guardian/plug.ex:208Guardian.Plug.sign_in/5
* lib/dog_web/controllers/session_controller.ex:29DogWeb.SessionController.login_reply/2

Try passing all arguments to sign_in without relying on the defaults, something strange is going on:

conn
|> put_flash(:info, "Welcome back!")
|> Guardian.Plug.sign_in(Guardian, user, %{}, [])

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New

We're in Beta

About us Mission Statement