Hello,
I’m trying to restrict some routes with user role.
I’ve added a role field on my user table that can take “user” “admin” or “manager”
the routes to change the role work perfectly but not the restrict access.
I’ve followed the hexdoc but doesn’t work.
This ismy ensurerole plug :
defmodule Timemanager.EnsureRolePlug do
import Plug.Conn, only: [halt: 1]
alias TimemanagerWeb.Router.Helpers, as: Routes
alias Phoenix.Controller
alias Plug.Conn
alias Pow.Plug
@doc false
@spec init(any()) :: any()
def init(config), do: config
@doc false
@spec call(Conn.t(), atom() | binary() | [atom()] | [binary()]) :: Conn.t()
def call(conn, roles) do
conn
|> Plug.current_user()
|> has_role?(roles)
|> maybe_halt(conn)
end
defp has_role?(nil, _roles), do: false
defp has_role?(user, roles) when is_list(roles), do: Enum.any?(roles, &has_role?(user, &1))
defp has_role?(user, role) when is_atom(role), do: has_role?(user, Atom.to_string(role))
defp has_role?(%{role: role}, role), do: true
defp has_role?(_user, _role), do: false
defp maybe_halt(true, conn), do: conn
defp maybe_halt(_any, conn) do
conn
|> Controller.put_flash(:error, "Unauthorized access")
|> halt()
end
end
this is my router :
pipeline :admin do
plug Timemanager.EnsureRolePlug, :admin
end
scope "/admin" do
pipe_through [:browser, :admin]
put("/manager/:userID", UserController, :manager)
put("/admin/:userID", UserController, :admin)
end
with that code i can acces the route /admin and /manager with the user role, and i want only a admin can use this routes.
thank you


















