Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Sinatra Basic HTTP Auth On One Page Only

Tags:

ruby

sinatra

Any idea how I can make Sinatra HTTP auth display only on one page in a modular Sinatra application?

like image 795
James A. Anderson Avatar asked Jan 20 '13 23:01

James A. Anderson


3 Answers

Adding to @iain answer, since you have asked HTTP Auth(I am assuming Basic auth).

class MyApp < Sinatra::Base
  def authorized?
    @auth ||=  Rack::Auth::Basic::Request.new(request.env)
    @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ["CUSTOM_USERNAME","SECRET_PASSWORD"]
  end

  def protected!
    unless authorized?
      response['WWW-Authenticate'] = %(Basic realm="Restricted Area")
      throw(:halt, [401, "Oops... we need your login name & password\n"])
    end
  end

  get "/protected_content" do
    protected!
    "in secure"
  end

  get "/" do
    "anyone can access"
  end
end
like image 116
ch4nd4n Avatar answered Nov 09 '22 23:11

ch4nd4n


The comment by Vicky Chijwani is correct, you should give a lot more info (take note!) but here's an answer.

You could do it several ways. If we assume your authentication method is called protected!:

class MyApp < Sinatra::Base # assumed for all examples

  get "/only-this-page-has-auth" do
    protected!
    "Only admin allowed!"
  end

  get "/this-wont-have-auth" do
    "Everybody can access this"
  end
end

Or you could use a filter

  before "/only-this-page-has-auth" do
    protected!
  end

  get "/only-this-page-has-auth" do
    "Only admin allowed!"
  end

  get "/this-wont-have-auth" do
    "Everybody can access this"
  end

Or if you're going to use Sinatra::Namespace from the sinatra-contrib gem (maybe a bit more of an advanced usage, but I use this a lot as I find it a nice way to do things) and the protected page would now be at "/admin/only-this-page-has-auth"

  namespace "/admin" do
    before do
      protected!
    end
    get "/only-this-page-has-auth" do
      "Only admin allowed!"
    end
  end

  get "/this-wont-have-auth" do
    "Everybody can access this"
  end
like image 33
ian Avatar answered Nov 10 '22 00:11

ian


The best way is to use: https://rubygems.org/gems/sinatra-basic-auth The documentation is great:

require "sinatra"
require "sinatra/basic_auth"

# Specify your authorization logic
authorize do |username, password|
  username == "john" && password == "doe"
end

# Set protected routes
protect do
  get "/admin" do
    "Restricted page that only admin can access"
  end
end

http://www.rubydoc.info/gems/sinatra-basic-auth/0.1.0 It's really simple to use

like image 23
dangalg Avatar answered Nov 10 '22 00:11

dangalg