Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phoenix framework & passing conn

I am using phoenix framework, so:

I have the follow code at /web/static/js/socket.js

chatInput.on("keypress", event => {
  if (event.keyCode === 13) {
    channel.push("new_msg", {body: chatInput.val()}); //im want to pass @conn here
    chatInput.val("")
  }
});

and at /web/channels/room_channel:

use Phoenix.Channel
defmodule fooBar do
  def handle_in("new_msg", %{"body" => body}, socket) do #and get conn here
    broadcast! socket, "new_msg", %{body: body}
    {:noreply, socket}
  end
end

I need to get conn at room_channel. How can I pass it at socket.js?

like image 784
bartezr Avatar asked Jun 07 '16 19:06

bartezr


People also ask

What is Phoenix framework used for?

Phoenix is a framework created specifically to build web applications. Phoenix was built using Elixir, which was built on the Erlang VM, and is used to build low-latency, fault-tolerant, distributed systems.

Is Phoenix frontend or backend?

Phoenix LiveView — frontend framework friendly for backend developers. I would like to share with you how Phoenix LiveView lets me create reactive web content without writing code in JavaScript.

Is Phoenix a backend framework?

Phoenix is a back-end framework written in Elixir (a functional programming language that runs on Erlang virtual machine). It is used to create modern web applications that are scalable and maintainable at the same time.

Is Phoenix framework open source?

It's an Elixir application built on the Phoenix web framework, PostgreSQL, and many other great open source efforts.


1 Answers

Here is the solution for you. In your router.ex.You put an user token like:

defp put_user_token(conn, _) do
  current_user = get_session(:current_user)
  user_id_token = Phoenix.Token.sign(conn, "user_id", current_user.id)
  conn |> assign(:user_id, user_id_token)
end

and then you can plug in your pipeline:

pipeline :browser do
 ...
 plug :put_user_token
end

and make sure you put your user token in your app.html.eex:

<script>window.userToken = "<%= assigns[:user_id] %>"</script>

Now you can check your socket in socket.js:

let socket = new Socket("/socket", {params: {token: window.userToken}})

and in your user_socket.ex.You can assign your token with socket:

def connect(%{"token" => user_id_token}, socket) do
    case Phoenix.Token.verify(socket, "user_id", user_id_token, max_age: 1209600) do
      {:ok, id} ->
        {:ok, assign(socket, :user_id, id)}
      {:error, reason} ->
        reason
    end
  end

Finally in your channel:

def handle_info(:after_join, socket) do 
    push socket, "user_joined", %{message: "User #{socket.assigns.user_id} has joined"
    {:noreply, socket}
end
like image 123
TheAnh Avatar answered Oct 30 '22 03:10

TheAnh