Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Halt a connection after a redirect

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 ?

  • If yes, which part of my code is wrong ?
  • If no, how can I prevent the controller to render the page ?

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:

  • phoenix: 1.0.2
  • phoenix_ecto: 1.1
  • phoenix_html: 2.1
  • cowboy: 1.0
like image 544
gaelgillard Avatar asked Sep 17 '15 17:09

gaelgillard


1 Answers

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.

like image 67
Gazler Avatar answered Nov 10 '22 18:11

Gazler