How can I password-protect my /sidekiq route (i.e. require authentication for the Sidekiq::Web tool)?

前端 未结 8 1259
太阳男子
太阳男子 2021-02-01 00:52

I am using sidekiq in my rails application. By Default, Sidekiq can be accessed by anybody by appending \"/sidekiq\" after the url. I want to password protect / authenticate onl

8条回答
  •  一向
    一向 (楼主)
    2021-02-01 01:11

    If you're using Sorcery for authentication, here's how to use Rails routes constraints to protect certain routes.


    Copied here from the sorcery wiki for redundancy:

    This tutorial shows how to use Rails routes constraints with Sorcery gem. Thanks to @anthonator for writing it!

    First, define UserConstraint module that will be used for all constraints:

    module RouteConstraints::UserConstraint
      def current_user(request)
        User.find_by_id(request.session[:user_id])
      end
    end
    

    Then, having that module defined, you can specify specific constraint classes. In these examples, first route will work only if there's no user logged in, the second will work only for logged user who is an admin:

    class RouteConstraints::NoUserRequiredConstraint
      include RouteConstraints::UserConstraint
    
      def matches?(request)
        !current_user(request).present?
      end
    end
    
    class RouteConstraints::AdminRequiredConstraint
      include RouteConstraints::UserConstraint
    
      def matches?(request)
        user = current_user(request)
        user.present? && user.is_admin?
      end
    end
    

    Finally, you can add the constraints to the config/routes.rb:

    MyApp::Application.routes.draw do
    
      # other routes …
    
      root :to => 'admin#dashboard', :constraints => RouteConstraints::AdminRequiredConstraint.new
      root :to => 'home#welcome', :constraints => RouteConstraints::NoUserRequiredConstraint.new
    
    end
    

提交回复
热议问题