I'm trying to write a Plug
which will authenticate users (checking session actually). I have trouble getting redirect route. I think it is because the route generation happens after this plug is activated.
Anyway I got an error like this: undefined function TestApp.page_path/2
In 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
Router helpers are included in your controllers and view via 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, both controller
and view
functions import the MyApp.Router.Helpers
module. This is where your helper (_path
and url
) functions are defined.
You can either use the fully qualified name:
Phoenix.Controller.redirect(to: TestAppRouter.Helpers.page_path(conn, :index))
Or you can import the 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 a pipeline in your router, you will cause a circular dependency and your code will not compile.
Does this work ?
Phoenix.Controller.redirect(to: TestApp.Router.Helpers.page_path(conn, :index))
I think Gazler has a valid point. you can either import or full path.
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