6ft Dan
6ft Dan

Reputation: 2445

Specific Rails routes password protected

I want a password site wide just like Rack's Basic AUTH

/config.ru

use Rack::Auth::Basic, "Restricted Area" do |username, password|
  [username, password] == ['admin', 'admin']
end

run Rails.application

But I don't want it to block paths /API and /mailgun/incoming_email with password access. Can I accomplish this in Rack? Or should I implement a scope within the routes.rb that almost all resources are behind a Rack (enter once) password?

For the record I am using Devise within the site... that's separate. I need a sitewide password before it.

[Revised Question]

Specific Routes

I would like to password protect only the root path / and /visitors with the Rack like password. I've seen something used in a Rails routes.rb file before with a lambda condition requiring the password. I'm not having luck finding that information at the moment.

Upvotes: 3

Views: 2270

Answers (1)

6ft Dan
6ft Dan

Reputation: 2445

My website already redirects unauthenticated Devise users to /users/sign_in. So I only needed to password protect /, /users/sign_in, and /users/sign_up. This is how I did it.

config.ru

class RootSiteAuth < Rack::Auth::Basic
  def call(env)
    request = Rack::Request.new(env)
    if ['/', '/users/sign_in', '/users/sign_up'].include? request.path
      super
    else
      @app.call(env)
    end
  end
end

use RootSiteAuth, "Restricted Area" do |username, password|
  [username, password] == ['admin', 'admin']
end

run Rails.application

And it works. Every controller that has before_filter :authenticate_user! redirects to the Rack password page. After authentication we're good to go. Anything without the filter permits outside access as planned. ^_^

Upvotes: 7

Related Questions