As a noob myself, can you provide me some details about how to do that (with very little snippet of code)?
Particularly how I can load a plug from a route and how I can call a controller/action from a plug?
Looking at the docs, I can only go so far (which is completely guesstimating some arbitrary code)
In the main router.ex file
#MyAppWeb.Router
pipeline :authorize do
plug :authorize_user
end
...
scope "/", pipe_through :authorize
Then in a dedicated Plug Module (but I’m not sure at all if the following can work or even compile at all)
defmodule MyApp.Plug.AuthorizeUser do
import Plug.Conn
def init(options), do: options
def call(conn, _opts) do
# 1. Checking in the Plug.Conn object conn for the value stored in a session variable
# Which one? is it in conn["session"]?
# 2. Somehow forwarding to the dedicated sub-router
# To be done with pattern matching btw.. It's just an example here :)
case conn["session"]["user_type"]
"admin" ->
forward("/", AdminRouter)
"user" ->
forward("/", UserRouter)
...
end
end
end
Now I can have dedicated Router modules that routes only to authorized and dedicated controllers/actions.
For example for the admin:
# AdminRouter
defmodule MyAppWeb.AdminRouter do
...
resources "/users", Admin.UserController
...
end
And for a user:
# AdminRouter
defmodule MyAppWeb.UserRouter do
...
resources "/users", User.UserController, only: [:index, :show]
...
end
Again this is a little example, but in my use case I can have very complex inter-related authorized actions, and as you can notice having scoped controllers give me the ability to have completely different behavior for each kind of user.
Thank you for any guiding about how I can achieve this.






















