Redirection inside the Phoenix plug-in

I am trying to write a Plug that will authenticate users (actually session verification). I have problems with route redirection. I think this happens because the route is generated after activating this plug.

In any case, I got an error: undefined function TestApp.page_path/2

In the regular context, page_path/2 obviously exists and works.

 defmodule TestApp.Plugs.Authenticate do import Plug.Conn def init(default), do: default def call(conn, _) do user = Plug.Conn.get_session(conn, :current_user) if not is_nil(user) do assign(conn, :user, user) else conn |> Phoenix.Controller.put_flash(:warning, "User is not authenticated.") |> Phoenix.Controller.redirect(to: TestApp.page_path(conn, :index)) |> halt end end end 
+7
elixir phoenix-framework
source share
3 answers

Router assistants are included in your controllers and view the web.ex file:

  def controller do quote do use Phoenix.Controller ... import MyApp.Router.Helpers end end def view do quote do use Phoenix.View, root: "web/templates" ... import MyApp.Router.Helpers ... end end 

As you can see, the controller and view functions import the MyApp.Router.Helpers module. Helper functions are defined here ( _path and url ).

You can use the full name:

 Phoenix.Controller.redirect(to: TestAppRouter.Helpers.page_path(conn, :index)) 

Or you can import route helpers and just use page_path

 import MyApp.Router.Helpers # or import MyApp.Router.Helpers, only: [page_path: 2] 

However, if you then use the plug-in in the pipeline of your router, you will cause a circular dependency and your code will not compile.

+7
source share

It works? Phoenix.Controller.redirect(to: TestApp.Router.Helpers.page_path(conn, :index))

I think Gazler has the right moment. You can import or full path.

+2
source share

Have you brought any controller assistants?

 use TestApp.Web, :controller 

(I would post this as a comment, but did not have a rep)

0
source share

All Articles