trivialcase

trivialcase

Assign isn't assigning?

I have a piece of code that gets executed on successful user signin, and everything seems to work fine, except that one of my assigned variables isn’t getting assigned by the code, but it works fine when I do it while debugging with pry…

Here is my code:

case TokenAuthentication.verify_token_value(token) do
  {:ok, user} ->
    conn
    |> put_session(:user_id, user.id)
    |> configure_session(renew: true)
    |> put_flash(:info, "Congratulations, #{user.first_name}, you were signed in successfully.")
    |> assign(:current_user, user)
    IEx.pry
    |> redirect(to: page_path(conn, :index))

and when I pry I have

assigns: %{current_user: nil}

but then I do assign(conn, :current_user, user) at the prompt and I get

assigns: %{current_user: %Myapp.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">,
    auth_tokens: #Ecto.Association.NotLoaded<association :auth_tokens is not loaded>,
    email: "test@test.com", first_name: "Test", id: 20,
    inserted_at: ~N[2017-05-09 13:06:32.374191], last_name: "McTest",
    password: nil, password_confirmation: nil,
    password_hash: "$2b$12$v8zTVSz0TGJ6COKlGb0TY.pbg3lnpJMZprmjDz3OS6s5aZWIDgsaC",
    updated_at: ~N[2017-05-09 13:06:32.374206]}}

as expected. I know that Elixir shouldn’t have side effects, so how is my running it at the prompt different?

Marked As Solved

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Your code isn’t quite doing what you think it is. Here it is formatted better:

    conn
    |> put_session(:user_id, user.id)
    |> configure_session(renew: true)
    |> put_flash(:info, "Congratulations, #{user.first_name}, you were signed in successfully.")
    |> assign(:current_user, user)
    # everything prior to this line has now been thrown away, you didn't bind it to anything

    IEx.pry
    |> redirect(to: page_path(conn, :index))

If I had to guess IEx.pry will return whatever it is you’ve last written in it. So if you assign a conn, that assigned conn will get passed through to the redirect function.

Also Liked

Aetherus

Aetherus

Remember that all data structures in Elixir are immutable, so is a %Plug.Conn{}.

Plug.Conn.assign/3 always returns a new %Plug.Conn{}. So your code should be

conn = conn
       |> put_session(:user_id, user.id)
       |> configure_session(renew: true)
       |> put_flash(:info, "Congratulations, #{user.first_name}, you were signed in successfully.")
       |> assign(:current_user, user)

IEx.pry

redirect(conn, to: page_path(conn, :index))

Note that the local variable conn is reassigned.

Aetherus

Aetherus

I’m not familiar with Guardian so excuse me if I’m wrong.

Since you’re using token authentication, the token should be maintained by the client side code (e.g. javascript on the browser side). The client should carry the token on every request whenever the token is available.

However, redirect is a two-step action:

  1. the browser receives a response with status code 302 and a Location header, which contains a URL.
  2. the browser sends another GET request immediately to the URL in Location header.

Unfortunately, you can’t control the second step. You can’t add headers to it, you can’t specify the HTTP method, you can’t add cookie to it, and you can’t attach token to it. I think this is the reason why you lose the current_user after redirect.

If you are building a single-page application, try not to use redirect. Let Javascript handle page switching.

Last Post!

OvermindDL1

OvermindDL1

I came from the erlang world instead of the rails/node world, the concepts clicked, but wow it has a weird structure to me, it still does. ^.^

Where Next?

Popular in Questions Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

Other popular topics Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36689 110
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

We're in Beta

About us Mission Statement