Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirection inside a plug in Phoenix framework

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
like image 449
Kelu Thatsall Avatar asked Jan 24 '16 16:01

Kelu Thatsall


2 Answers

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.

like image 153
Gazler Avatar answered Oct 12 '22 23:10

Gazler


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.

like image 27
Sandesh Soni Avatar answered Oct 13 '22 00:10

Sandesh Soni