Hi all,
I currently build an app with authentication and authorization.
As foundation I use the latest mix phx.gen.auth
.
And my app contains (except of some authentication routes) almost only live_views.
I have completely read the live_view docs and think I understood it also. Especially about security model
I have a question about the past paragraph on this page:
live_session
can be used to draw boundaries between groups of LiveViews. While you could uselive_session
to draw lines between different authorization rules, doing so would lead to frequent page reloads. For this reason, we typically uselive_session
to enforce different authenticationrequirements or whenever you need to change root layouts
So that’s clear and I recognized that already, that a page-reload is triggered, when navigating between live_session
.
From the said, I thought I would do:
- live_session blocks for authentication
- and on_mount for checking authorization.
But how to do that best?
I thought I just use the on_mount hook in my live_view like so…
defmodule MyAppWeb.MySecretPageLive do
use PortalWeb, :live_view
on_mount MyAppWeb.UserAuth, :any
… but okay, that’s not how you use it…
The on_mount should look something like this, where I can conditionally add a permission, which will be checked if the user has the permission…
def on_mount(permission, _params, session, socket) do
socket = mount_current_user(session, socket)
if permission in socket.assigns.current_user.acl do
{:cont, socket}
else
{:halt, redirect(socket, to: "/login")}
end
end
So any hints what’s best practice?
Or should I just also wrap authorization into live_sessions ? But as the docs say, that is probably not the best way for user-experience?