mitkins

mitkins

I’m in the process of switching from Guardian to Pow. Now I’m trying to figure out how to get the current user in my Live View. I’ve figured out what my :session_key is - so I’m passing that via the live view route:

live "/tasks", TaskLive.Index, session: [ :zoinks_auth ], as: :task_live

And here’s what I want to do in my mount:

  def mount( session, socket) do
    socket = assign_new( socket, :current_user, fn -> Pow.Plug.current_user(session.zoinks_auth) end )

    {:ok, socket}
  end

Though current_user expects a conn. Is there a way to retrieve the current user in Pow with just the :session_key (and no Connection)?

Showing Posts 1 to 10

danschultzer

danschultzer

Pow Core Team

I’m going to set up a website with LiveView very soon, and will look into this then.

One caveat with LiveView is that the session won’t be reloaded or renewed like with the REST endpoints. It may make sense to get the socket to keep the session alive, but not sure if session can be updated through LiveView.

Pow.Plug.current_user/1 pulls the :current_user assigns from the conn, after the conn has been through the Pow.Plug.Session plug. It’s required to pass a conn.

In the LiveView docs, the user id is passed in the session and then loading it in mount/2. So you could set up a plug in your pipeline that updates a session value with the current user id, and then load from the DB in mount/2.

You can also pull the credentials directly by using the :zoinks_auth value. You have to call Pow.Store.CredentialsCache.get([backend: Pow.Store.Backend.EtsCache], session_key), but be warned that you’ll be working with the internals of Pow. It’ll return a tuple with the user being the first element {user, _ inserted_at}, and a :not_found atom is returned if there is no user stored.

I’ll have to work with LiveView to see what can be the best approach to deal with short lived sessions, and retrieving session data.

If anybody has ideas for how this could work, please do reply as I’m just scratching the surface of LiveView :smile:

LostKobrakai

LostKobrakai

I’ve build a small helper module, which at an interval checks if the user is still authenticated. There are a few hardcoded assumptions in there, but might be helpful:

danschultzer

danschultzer

Pow Core Team

This is great, thanks @LostKobrakai! I’ve refactored the code here to make it work in most cases: Instructions for WebSocket usage (e.g. Phoenix Channels and LiveView) · Issue #271 · pow-auth/pow · GitHub

And some thoughts on keeping session alive at the end:

There’s still an issue with sessions expiring after 30 minutes. The above doesn’t keep sessions alive after that. The session id will also be rotated every 15 minutes. It’s triggered if the user is visiting other pages while the socket is open.

The session could have a fingerprint, and that fingerprint can be used to look up the session info no matter if it has been rotated or not. This would make it possible to keep the socket open even after the session has been rotated.

If the cookie somehow can be updated in the session, then we can also prevent expiration after 30 min (since we’ll then rotate within the socket).

kreiling.io

kreiling.io

FYI: Phoenix LiveView 0.9.0 allows you to pass a function for the session option of live/4 and live_render/3.

Relevant docs: Phoenix.LiveView.Router — Phoenix LiveView v1.2.5

The docs don’t quite make it clear, but the args list passed in the MFA has the Plug.Conn struct (associated with the current request) prepended to it. The function should return a map with String keys, which is passed as the session (second) arg to the mount/3 function.

e-nikolov

e-nikolov

I’m pretty new to elixir. Can you please show an example of the correct syntax for the MFA?

Edit:

To answer my own question, it looks like this works:

live "/test", TestWeb.TestLive, session: {__MODULE__, :with_session, []}

def with_session(conn) do
  %{"current_user" => conn.assigns.current_user.id}
end
OvermindDL1

OvermindDL1

MFA is always {Module, FunctionName, ArgList}. So to call MyModule.blah() then it would be {MyModule, :blah, []}, or to call Something.vreep(1, 2, 3) then it would be {Something, :vreep, [1, 2, 3]}. :slight_smile:

Now when a callback is done with extra arguments, they are traditionally always prepended (since that’s the fast operation), so when the conn is prepended then to call something like Module.blah(conn, 1, 2) you’d encode it as {Module, :blah, [1, 2]} and the caller will prepend the conn. :slight_smile:

timc

timc

Is there a clearer example as I am also having trouble with using a session with a live view.

In the test setup I authenticate as per my other tests, but in the actual test I have this so far:

      setup %{conn: conn} do
      user = insert(:user)
      conn = Pow.Plug.assign_current_user(conn, user, otp_app: :myapp)
    
      {:ok, conn: conn}
    end

    test "created task will show up on the view", %{conn: conn}  do
      {:ok, view, html} = live(conn, Routes.tasks_path(conn, :index),       
        [session: {__MODULE__, :with_session, []}]
      )
    end

and just taken from above:

  def with_session(conn) do
    %{"current_user" => conn.assigns.current_user.id}
  end

Any help would be appreciated.

tenzil

tenzil

@danschultzer, any new features in POW for 1.5 phoenix version, especially on the liveview part.
how to get current_user in Phoenix.LiveView?, registering users in liveview.

unsek

unsek

Thank you! I was struggling with :not_found when calling Pow.Store.CredentialsCache.get and the solution was in that issue. :tada:

Where Next? Top

Trending in Questions Top

water
I’m aware of 2 such projects, are there others? git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Alvinkariuki
How Can I Optimise Compile Time Dependencies I have been building an elixir application for about 2 years now. Many modules and files ha...
New
leoschweizer
Hi, we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New

Other Trending Topics Top

budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
budgie
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with. But I don’t use it anymore. Serverless was the promis...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews