Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Middlewares at action level #1301

Open
Drowze opened this issue Mar 20, 2023 · 1 comment
Open

Middlewares at action level #1301

Drowze opened this issue Mar 20, 2023 · 1 comment

Comments

@Drowze
Copy link
Contributor

Drowze commented Mar 20, 2023

Migrating an application from Hanami v1 to Hanami v2, I've came across a few actions that were protected by basic authentication on the following manner:

module Auth::Basic
  def self.included(action)
    action.class_eval do
      use ::Rack::Auth::Basic do |username, password|
        username == ENV["BASIC_AUTH_USERNAME"] && password == ENV["BASIC_AUTH_PASSWORD"]
      end
    end
  end
end

module Api::Controllers::Users
  class Index
    include Auth::Basic
    # ...
  end
end

Is it also possible to add rack middlewares at the action level in Hanami 2? For an example, if I have the following routes, is it possible to add a middleware (e.g. Rack::Auth::Basic) to only one of them?

    get "/public_stuff", to: "public_stuff.index"
    get "/private_stuff", to: "private_stuff.index"
@Drowze
Copy link
Contributor Author

Drowze commented Mar 20, 2023

Got this workaround for setting a middleware at the route level without a namespace:

class BasicAuthActionBuilder
  def self.call(action)
    action_proc = ->(env) { Hanami.app["actions.#{action}"].(env) }
    Rack::Auth::Basic.new(action_proc) do |username, password|
      username == ENV["BASIC_AUTH_USERNAME"] && password == ENV["BASIC_AUTH_PASSWORD"]
    end
  end
end

module MyApp
  class Routes < Hanami::Routes
    get "/private_stuff", to: BasicAuthActionBuilder.("private_test.private")
    get "/public_stuff", to: "private_test.public"
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant