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.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New

Other popular topics Top

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
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
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
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

We're in Beta

About us Mission Statement