Stop connection after redirect

Inside the controller, I check the connection session to check if the session is connected to the user. If not, I redirect it to another page.

But halt returns me an error if I try to call it after the redirect:

lack of matching functions in Plug.Conn.halt / 1

And without halt page of the source controller renders and displays an error on the console (the template is rendered without a user):

(exit) an exception was thrown: (UndefinedFunctionError) undefined function: nil.username / 0

So my question is : is it possible to call halt after the redirect?

  • If so, what part of my code is incorrect?
  • If not, how can I prevent the controller from displaying the page?

Here is the code for 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 

The dependencies used here are:

  • phoenix: 1.0.2
  • phoenix_ecto: 1.1
  • phoenix_html: 2.1
  • cowboy: 1.0
+6
source share
1 answer

EDIT On the Elixir main branch, the compiler will warn if the function is passed without parentheses, if there are arguments.


Try to do:

  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:

 |> redirect(to: "/", |> halt) 

And the error correctly determined that there is no template for:

 halt(to: "/") 

See Why can't I bind String.replace? for a more detailed explanation.

+4
source

All Articles