Macaw.Auth.Live (macaw_auth v0.4.1)

Copy Markdown View Source

The LiveView side of Macaw.Auth:

live_session :signed_in, on_mount: [{Macaw.Auth.Live, :require_authenticated}] do
  live "/", DashboardLive
end

live_session :admin, on_mount: [{Macaw.Auth.Live, {:require_role, ["admin"]}}] do
  live "/admin", AdminLive
end

live_session :posts,
  on_mount: [{Macaw.Auth.Live, {:authorize, :edit, resource: &MyAppWeb.Posts.post/2}}] do
  live "/posts/:id/edit", PostEditLive
end

{:authorize, action} asks the app's authorizer (Macaw.Auth.authorize/3) whether the user may do action to the resource: what the :resource option's function (a remote capture, &Mod.fun/2) gives of the page's params and socket at mount, else nil. With no authorizer configured, every such page is refused.

:mount_current_user only assigns. The others also guard an open page: it subscribes to its user's revocations and disconnects at once when its session is revoked, and re-checks its session every :revalidate_ms (default 60 s) without extending it. The re-check refreshes the user and applies the mount's guard again: a page whose user lost its role, or whose authorizer now refuses it (asked about the resource the page mounted with), goes home, and one whose session now owes a step goes to that step.

With config :macaw_auth, endpoint: MyAppWeb.Endpoint, a revocation also has Phoenix drop the session's sockets, by the live_socket_id Macaw.Auth.Plug.log_in/3 put in the session (Macaw.Auth.announce_revoked/2).