I have created a simple plug in elixir which codes are below :
defmodule TrangellCmsService.Cms.Plugs.AdminChecker do
import Plug.Conn
import Phoenix.Controller
def init(_params) do
end
def call(%Plug.Conn{params: %{"acl" => acl}} = conn, params) do
admin_checker = case acl do
"admin" ->
assign(conn, :admin_checker, params)
_ ->
conn
|> put_status(403)
|> json(%{error_code: "403", error_msg: "You don't have an access."})
|> halt()
end
admin_checker
end
end
I have an 500 error when my user didn’t send All params like acl , but I need to show 404 error.
How do I convert plug params to optional params like this function params: defp helper(list, joiner \\ " ") do, then I was trying do it in Plug, but didn’t work , like this def call(%Plug.Conn{params: %{"acl" => acl \\ " "}} = conn, params) do
it should be noted, my user may not send the acl params, for this purpose I need to check this.
def call(%Plug.Conn{params: %{"acl" => acl}} = conn, params) do
case acl do
"admin" ->
assign(conn, :admin_checker, params)
_ ->
conn
|> put_status(403)
|> json(%{error_code: "403", error_msg: "You don't have an access."})
|> halt()
end
end
def call(conn, _params) do
conn
|> put_status(404)
|> halt()
end
I also took the freedom to realign your initial code a bit to make it more idiomatic.
Also, I’m not sure if you should import Phoenix.Controller in a Plug. I’m also not a friend of import Plug.Conn and prefer the more more explicit alias Plug.Conn. In generall I am very, very careful with imports at all.
[error] #PID<0.457.0> running TrangellCmsServiceWeb.Endpoint terminated
Server: localhost:4022 (http)
Request: PUT /api/edit-category
** (exit) an exception was raised:
** (Plug.Conn.NotSentError) a response was neither set nor sent from the connection
(plug) lib/plug/adapters/cowboy/handler.ex:45: Plug.Adapters.Cowboy.Handler.maybe_send/2
(plug) lib/plug/adapters/cowboy/handler.ex:17: Plug.Adapters.Cowboy.Handler.upgrade/4
(cowboy) /Applications/MAMP/htdocs/elixir-ex-source/Trangell_Main/trangell_cms_service_umbrella/deps/cowboy/src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4