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
The dependencies used here are:
- phoenix: 1.0.2
- phoenix_ecto: 1.1
- phoenix_html: 2.1
- cowboy: 1.0
source share