elixirphoenix-frameworkplug

Roles plug inside of router phoenix


At the moment I have a roles plug, that looks the following:

plug Roles, :role

It receives as the second parameter the specific role and the current user is obtained from the current token that is in use. I am using the plug inside of the controller module this way:

plug Roles, :manage_users when action in [:index, :show, :delete]

The problem with this is that I want to move all this logic to router.ex, to make it clear what the configs for controllers are.

From the documentation the default pipeline/1 and pipe_through/1 receive only an atom that is an identifier, so there is no way to pass parameters to my plug.

What would be the correct way to use this plug so that I can use it inside of router.ex?


Solution

  • I ended up using some macro magic:

    defmodule PlugUtils do
    
      defmacro __using__(_) do
        quote do
          import unquote(__MODULE__)
        end
      end
    
      defmacro param_pipe(pipe_name, plug_name, plug_params) do
        quote do
          pipeline unquote(pipe_name) do
            plug unquote(plug_name), unquote(plug_params)
          end
    
          pipe_through unquote(pipe_name)
        end
      end
    end
    

    Witch in turn can be used in router module the following way:

    use PlugUtils
    param_pipe :backups_upload, RolePlug, :upload_backup
    

    The only downside to this approach is that I cannot point to the atoms of the controllers, since this plug is executed before the router plug, however by making separate scopes same thing can be achieved.