Hi, I created a simple plug to force my user to login, and added it to my router.
Normal redirect
def init(default), do: default
def call(conn, _default) do
with {:ok, :sesion_check, current_token} <- sesion_check(conn, :current_token),
{:ok, :verify_token, :current, current_token_info} <- CurrentPhoenixToken.verify_token(current_token, :current) do
conn
|> assign(:current_token, current_token_info["token"])
else
_ ->
conn
|> put_flash(:error, "Denied")
|> redirect(to: "#{MishkaHtmlWeb.Router.Helpers.auth_path(conn, :login)}")
|> halt()
end
end
by the way, I used
|> redirect(to: "#{MishkaHtmlWeb.Router.Helpers.live_path(conn, MishkaHtmlWeb.LoginLive)}")
and it had same result
when I use redirect it loads my login page several times.
please see
now I changed it with live_render
it loads fewer:
def call(conn, _default) do
with {:ok, :sesion_check, current_token} <- sesion_check(conn, :current_token),
{:ok, :verify_token, :current, current_token_info} <- CurrentPhoenixToken.verify_token(current_token, :current) do
conn
|> assign(:current_token, current_token_info["token"])
else
_ ->
conn
|> put_flash(:error, "Denied")
|> live_render(MishkaHtmlWeb.LoginLive, sesssion: %{})
|> halt()
end
end
this is good, but there is a problem with it, when I select a live_redirect link
like my menu it loads websocket
again, i’m confused, is it my way wrong?
Thanks.
it should be noted after some request it shows me this error, but I did all of them on my project
[debug] LiveView session was misconfigured or the user token is outdated.
1) Ensure your session configuration in your endpoint is in a module attribute:
@session_options [
...
]
2) Change the `plug Plug.Session` to use said attribute:
plug Plug.Session, @session_options
3) Also pass the `@session_options` to your LiveView socket:
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [session: @session_options]]
4) Ensure the `protect_from_forgery` plug is in your router pipeline:
plug :protect_from_forgery
5) Define the CSRF meta tag inside the `<head>` tag in your layout:
<%= csrf_meta_tag() %>
6) Pass it forward in your app.js:
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}});