MishkaCmsCore.LiveUserAuth (Mishka CMS Core v0.0.1)

Copy Markdown View Source

Helpers for authenticating users in LiveViews.

Summary

Functions

The signed-in user, verified now — what :live_user_lazy left until something needed one.

The signed-in user read again, now, over whatever this socket loaded earlier.

Functions

load_current_user(socket)

@spec load_current_user(Phoenix.LiveView.Socket.t()) :: Phoenix.LiveView.Socket.t()

The signed-in user, verified now — what :live_user_lazy left until something needed one.

Exactly the checks the live session's own hook makes on mount, because underneath it is the same function: the session's token is verified, its row must still be in the token resource — so a token that was signed out, revoked or never issued by this application is refused — and only then is the subject read back into a user. A tenant user's site is loaded after it, as every hook here does.

assign_new/3, for two reasons. The first HTTP response was already given a verified user by the :load_from_session plug, so it is reused rather than read again; and a visitor who patches from one page to another inside the same LiveView keeps the user the first of them loaded, rather than paying for it once per page.

A socket that was not mounted through :live_user_lazy carries no session and answers nobody, which every caller has to treat as "not signed in" — refused wherever a page names permissions.

on_mount(arg1, params, session, socket)

reload_current_user(socket)

@spec reload_current_user(Phoenix.LiveView.Socket.t()) :: Phoenix.LiveView.Socket.t()

The signed-in user read again, now, over whatever this socket loaded earlier.

load_current_user/1 answers from the assign once it has one, which is right for a page being drawn: the user was verified when the socket mounted, and a change to that user cuts the socket (see MishkaCmsCore.Accounts.LiveSockets). It is not enough before ACTING on a page that names permissions — between the write that took a permission away and the broadcast that ends the socket there is a moment in which the assign still says the visitor may, and an event arriving in that moment must not be answered from it.

So the same verification runs again, through the same library function, with assign/3 in place of assign_new/3: the session's token is verified and its row looked for, and the user is read back with the permissions it has now. A token that was signed out, revoked or expired since the mount answers nobody, which every caller reads as "not signed in".