shahryarjb

shahryarjb

How to add Map in phoenix conn's params in Plug

hello, I need to add some Map in phoenix conn’s params in Plug

for example :

def init(_params) do

	end

	def call(%Plug.Conn{params: %{"ptoken" => ptoken}} = conn, params) do
    outputs = case Guardian.decode_and_verify(ptoken) do
           {:ok, _climes} ->
             # I need to add it in blow conn , map like : %{"last_ip" => "127.1.2.3"}
             assign(conn, :user_ip_checked, params)
           {:error, _ms} ->
             conn
         	  |> put_status(403)
         		|> json(%{error_code: "403", error_msg: "You don't have an access."})
         	  |> halt()
     end
     outputs
	end

how can I do this ?

Marked As Solved

peerreynders

peerreynders

The idea is not to subvert the intent behind Plug.Conn.params - it’s not a general data “dumping ground” - that is Plug.Conn.assigns job. So the strategy would be to put the information in Plug.Conn.assigns first and then combine it in the last possible moment. So start with

          {:ok, climes} ->
             conn =
               conn
               |> assign(:all_req,  %{"last_ip", "#{climes["ip"]}"})
               |> assign(:user_ip_checked, params)

And then have a helper function that assembles everything

def make_all_req(conn, params) do
  conn.assigns
  |> Map.get(:all_req, %{})
  |> Map.merge(conn.params)
  |> Map.merge(params)
end

which you can use at the last possible moment, like:

def get_posts_category(conn, %{"seo_alias_link" => _seo_alias_link, "page_number" => _page_number, "page_size" => _page_size, "token" => _token, "ptoken" => _ptoken} = params) do
   all_req = make_all_req(conn, params)
   ...
end

You really shouldn’t be sending the entire contents of the Plug.Conn structure.

  • The actual content may change in the next version of Plug.Conn
  • The organization of the Plug.Conn structure could change in the next version
  • By using Plug.Conn verbatim you are unnecessarily coupling other parts of your system to it (and the version that you started using).

In the interest of decoupling:

  • Decide what minimal information is actually useful.
  • Structure that information in a way the makes sense to your system. Your information structure has different reasons to change than those that will force a change on Plug.Conn.

Also Liked

peerreynders

peerreynders

Yes but action functions receive 2 parameters:

  def index(conn, params) do
     ...
  end

Plug.Conn Connection fields:

  • assigns - shared user data as a map

So rather than polluting Plug.Conn.params with non-standard data, you should use Plug.Conn.assigns which is intended for “user data”, e.g.:

          {:ok, climes} ->
             conn
             |> assign(:last_ip,  "#{climes["ip"]}")
             |> assign(:user_ip_checked, params)

and then inside the action function retrieve it:


  def index(conn, params) do
     ...
     last_ip = conn.assigns[:last_ip]
     ...
  end
kokolegorille

kokolegorille

Given that conn is a struct, I would update it like this…

conn = %{conn | assigns: Map.merge(conn.assigns, %{"last_ip" => "127.1.2.3"})}

BTW It really depends what You want to do with assigns, You could use Map.update, or Map.merge or anything You need depending on situation.

With Map.update…

args = %{"last_ip" => "127.1.2.3"}
conn = Map.update(conn, :assigns, args, &Map.merge(&1, args))
shahryarjb

shahryarjb

Thanks , I edited your code and now it works for me

code :

conn = %{conn | params: Map.merge(conn.params, %{"last_ip" => "#{climes["ip"]}"})}

Where Next?

Popular in Questions Top

nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
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
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
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
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
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
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
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
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
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
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
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43757 214
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement