Inside a controller, I'm checking the session of the connection to verify if the session is attached to a user. If not, I redirect it to an other page.
But the halt
returns me an error if I try to call it after the redirect:
no function clause matching in Plug.Conn.halt/1
And without the halt
the page of the original controller does a render and print an error in the console (the template is rendered without a user):
(exit) an exception was raised: (UndefinedFunctionError) undefined function: nil.username/0
So my question is: is it possible to call the halt
after a redirect ?
Here's the code of my controller and the module used in it.
defmodule Mccm.DashboardController do
use Mccm.Web, :controller
import Mccm.Plug.Session
import Mccm.Session, only: [current_user: 1]
plug :needs_to_be_logged_in
def index(conn, _params) do
conn
|> render "index.html", user: current_user(conn)
end
end
defmodule Mccm.Plug.Session do
import Mccm.Session, only: [logged_in?: 1, is_teacher?: 1]
import Phoenix.Controller, only: [redirect: 2]
import Plug.Conn, only: [halt: 1]
def needs_to_be_logged_in(conn, _) do
if !logged_in?(conn) do
conn
|> redirect to: "/"
|> halt # this give me an error
else
conn
end
end
end
Here's dependencies used:
EDIT On the master branch of Elixir, the compiler will warn if a function is piped into without parentheses if there are arguments.
Try doing:
def needs_to_be_logged_in(conn, _) do
if !logged_in?(conn) do
conn
|> redirect(to: "/") # notice the brackets
|> halt # this give me an error
else
conn
end
end
Your code was doing:
|> redirect(to: "/", |> halt)
And the error correctly identified that there is no pattern for:
halt(to: "/")
See Why Can't I Chain String.replace? for a more detailed explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With