Any idea how I can make Sinatra HTTP auth display only on one page in a modular Sinatra application?
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With