From 6f4b7335f8fc68165386eb0551ae5f34df0d68a4 Mon Sep 17 00:00:00 2001 From: Ryan Cavicchioni Date: Wed, 4 Sep 2024 15:24:12 -0500 Subject: [PATCH] Add HTTP basic authentication endpoint --- app.rb | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/app.rb b/app.rb index 3935d80..cfe5f33 100644 --- a/app.rb +++ b/app.rb @@ -217,6 +217,25 @@ helpers do JSON.generate(obj, opts:) end end + + def protected! hidden = false + return if authorized? + + if hidden + halt 404, "Not Found" + else + headers["WWW-Authenticate"] = 'Basic realm="Restricted Area"' + halt 401, "Unauthorized" + end + end + + def authorized? + @auth ||= Rack::Auth::Basic::Request.new(request.env) + @auth.provided? and + @auth.basic? and + @auth.credentials and + @auth.credentials == ["qwer", "asdf"] + end end get "/" do @@ -382,3 +401,15 @@ get "/chunked/:delay" do out << "Hello, world!\n" end end + +route :delete, :get, :patch, :post, :put, "/auth/basic", provides: "json" do + pretty = params.key? :pretty + + if params.key? :hidden + protected! hidden: true + else + protected! + end + + json({authenticated: true, user: @auth.username}, pretty:) +end