I have my api pipeline in which I want to add a plug which basically does some operations in the database and based on the response it does an assign which I then use on my view.
I´m having problems with passing the assign from the plug to the view.
web/router.ex
pipeline :api do
plug ApiV2.Plug.Authenticate, repo: Auth.Repo
plug :accepts, ["json"]
end
web/controllers/auth.ex (just the assign)
defmodule ApiV2.Plug.Authenticate do
@behaviour Plug
import Plug.Conn
import Phoenix.Controller
def init(opts), do: opts
def call(conn, _opts) do
assign(conn, :current_user, 'user')
end
end
web/controllers/address_controller.ex
defmodule ApiV2.AddressController do
use ApiV2.Web, :controller
alias ApiV2.Address
def index(conn, params) do
json conn, @current_user
end
end
I´ve got to the point where it tries to return :current_user ( I suppose), but, as the assign is wrong, it only returns
null
What am I missing?
Thanks
The values set using assign
are available in the conn.assigns
map. @current_user
is a module attribute which returns nil
since it's not set in this module.
This should work:
json conn, conn.assigns.current_user