简体   繁体   中英

elixir phoenix liveview - passing user id through socket

In liveview , how can I pass the user data from leex to the context ? I have phx.gen.live a profiles context, and I want to add user_id to the profile every time user create the new profile. I change the create_profile code to:

**profiles.ex (context)**
  def create_profile(attrs \\ %{}, userid) do
    attrs = Map.put(attrs, "user_id", userid)
    %Profile{}
    |> Profile.changeset(attrs)
    |> Repo.insert()
  end

I am using pow , so in normal phoenix case, I would just do this:

user = Pow.Plug.current_user(conn) #<-- this is conn
Profiles.create_profile(profile_params, user.id)

but in liveview , instead of conn , it use socket . So I am not sure how to go about it.

There are lots of different ways to do this but I will describe a straightforward approach.

  1. In the function where you "log in" a user, I assume you have access to the conn . I also assume you have a user_token , if you are using Pow. If so, do this:
conn
|> put_session(:user_token, user_token)
  1. Now go to your live_helpers.ex file (or create it if you don't have one) and make a function like this:
  def assign_defaults(session, socket) do
    socket =
      socket
      |> assign_new(:current_user, fn ->
        find_current_user(session)
      end)

    socket
  end
  1. Also, in live_helpers , write this function:
  defp find_current_user(session) do
    with user_token when not is_nil(user_token) <- session["user_token"],
         %User{} = user <- Accounts.get_user_by_session_token(user_token),
         do: user
  end
  1. Now in any LiveView modules where you need to access the current_user, just put this in your mount function:
  def mount(_params, session, socket) do
    socket =
      assign_defaults(session, socket)

    {:ok, socket}
  end

And then you will have access to the session.assigns.current_user .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM