How to skip or switch to a different router scope from plug

I have two router scopes as follows

scope "/api", Api.Customer do
    pipe_through [:api, :customer_auth] # customer has 'key' and 'authorization' header
    resources "/help", HelpController, only: [:create]
    resources "/profile", ProfileController, only: [:create]
end

scope "/api", Api.Partner do
    pipe_through [:api, :partner_auth] # partner has 'key' header
    resources "/help", HelpController, only: [:create]
    resources "/profile", ProfileController, only: [:create]
end

i want to check if request does not have ‘authorization’ header then request should go to partner scope but i dont have any idea how should i do it. any help is much appreciated.

i can create a plug as follows.

 defmodule Api.Auth.AuthHeaderExists do
   import Plug.Conn

   def init(opts),  do: _opts

   def call(conn, _opts) do
     if header_exists?(conn) do
       conn
     else
       # here i want to redirect the request to partner scope
       # or
       # how can i skip current scope (customer scope)
       # what should i do?
     end
   end
end

I don’t think you can easily stop a pipeline like this.
Could you not add the scope to your routes, e. g. with /api/customer/ and /api/partner?

actually i already have a lot of urls in both pipelines and now clients requirement is, do not change existing endpoints thats why i am trying to find a way so i can use a plug.

All router definitions match on unique http method + path + host so you cannot match then continue down. Ultimately the router definitions become:

def match(conn, "GET", ["api", "customer"], "somehost") do

So you can’t skip for the same reason you can’t match a function clause, then tell it to continue calling the function but skip the current one. You need to handle it how you’d handle wanting something like this with a function –– by having a single path match, then have logic in that plug/controller that invoked your desired code paths based on whatever logic, such as an authorization header in this case.

3 Likes