Here's a simple pattern pulled from https://github.com/fly-apps/live_beats. It has the following steps:
- Add
current_user
to socket assigns.
- Use the
on_mount
in the live views where you want it.
- Access
current_user
in the template.
Add current_user
to socket assigns in on_mount
(see lib/live_beats_web/controllers/user_auth.ex):
defmodule LiveBeatsWeb.UserAuth do
import Plug.Conn
import Phoenix.Controller
alias Phoenix.LiveView
alias LiveBeats.Accounts
alias LiveBeatsWeb.Router.Helpers, as: Routes
def on_mount(:current_user, _params, session, socket) do
case session do
# I think you have to manually add `user_id` to session. I used
`user_token` instead of `user_id` (because it's already in session due to the `fetch_current_user` plug in the browser pipeline) and `Accounts.get_user_by_session_token(user_token)` instead of `Accounts.get_user(user_id)`
%{"user_id" => user_id} ->
{:cont, LiveView.assign_new(socket, :current_user, fn -> Accounts.get_user(user_id) end)}
%{} ->
{:cont, LiveView.assign(socket, :current_user, nil)}
end
end
...
end
Use the on_mount
in the live views where you want it.
(see lib/live_beats_web/live/player_live.ex):
defmodule LiveBeatsWeb.PlayerLive do
use LiveBeatsWeb, {:live_view, container: {:div, []}}
alias LiveBeats.{Accounts, MediaLibrary}
alias LiveBeats.MediaLibrary.Song
# this uses the `on_mount` defined above. `:current_user` matches the first argument of `on_mount` above. It can say whatever you want, but it has to match in both places.
on_mount {LiveBeatsWeb.UserAuth, :current_user}
...
def mount(_parmas, _session, socket) do
%{current_user: current_user} = socket.assigns
if connected?(socket) do
Accounts.subscribe(current_user.id)
end
socket =
socket
|> assign(
song: nil,
playing: false,
profile: nil,
current_user_id: current_user.id,
own_profile?: false
)
|> switch_profile(current_user.active_profile_user_id || current_user.id)
{:ok, socket, layout: false, temporary_assigns: []}
end
Access current_user
in the template
(I didn't find an example of this in that repo, but here's how you get properties of current_user)
User id: <%= @current_user.id %>