Compare commits

...

2 Commits

Author SHA1 Message Date
6f4b7335f8
Add HTTP basic authentication endpoint
All checks were successful
Gitea Actions Demo / lint (push) Successful in 1m32s
Gitea Actions Demo / test (push) Successful in 1m18s
Gitea Actions Demo / release-image (push) Successful in 1m7s
2024-09-04 15:24:12 -05:00
9f222725d1
Add json() helper 2024-09-04 15:23:53 -05:00

41
app.rb
View File

@ -209,6 +209,35 @@ before do
request.session_options[:skip] = !request.path_info.start_with?("/session")
end
helpers do
def json(obj, opts: nil, pretty: false)
if pretty
JSON.pretty_generate obj, opts:
else
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
"hello there!\n"
end
@ -372,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