Hi,
I’d like to redirect unauthenticated users to my login page.
According to these considerations, I added a redirect plug in my router which works as intended:
defmodule CloudNewsWeb.Plugs.CheckLoggedIn do
import Plug.Conn
use Phoenix.Controller
def init(default), do: default
def call(%{assigns: %{current_user: user}} = conn, _default) do
case user do
nil ->
conn
|> redirect(to: "/login?from=#{URI.encode_www_form(conn.request_path)}")
|> halt()
_ ->
conn
end
conn
end
end
In my liveview I added:
def mount(_params, session, socket) do
user = get_current_user(session)
if user do
[...]
{:ok, socket}
else do
{:ok, redirect(socket, to: Routes.login_path(socket, :show))}
As a result of this I get two redirects, one from the plug and one from the LiveView, I don’t understand why I would need that.
[info] Sent 302 in 3ms
[info] Sent 302 in 3ms
And I get an error from Cowboy:
[error] Ranch listener CloudNewsWeb.Endpoint.HTTP had connection process started with :cowboy_clear:start_link/4 at #PID<0.1162.0> exit with reason: {:function_clause, [{:cowboy_http, :commands, ...
Do you have any idea on how to fix this?
Thank you !