Thanks for the hint. Using a custom plug to check if the user exists in the session works for authentication. I did it using a dedicated pipeline that uses my custom plug:
pipeline :authenticated do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug Phoenix.LiveView.Flash
plug :protect_from_forgery
plug :put_secure_browser_headers
plug HelloWeb.Auth
end
and creating scopes that use that pipeline:
scope "/me", HelloWeb do
pipe_through :authenticated
live "/", MeLive, session: [:user_id, :current_user]
end
My custom plug redirects to login page if no user is logged.
However, I still can’t figure how to do this for the liveviews in mount/2. Adding a redirect like this:
{:ok,
socket
|> put_flash(:error, "Unauthorized resource")
|> redirect(to: "/access-denied")
}
gives the following error:
cannot redirect socket on mount/2
mount/2 doesn’t look like the place to do authorization checks with redirects