Add both Basic auth and CGI support

This commit is contained in:
2025-12-04 13:24:23 -06:00
parent abe444d22b
commit 2861fba6f2
15 changed files with 315 additions and 18 deletions

View File

@@ -0,0 +1,47 @@
#include "TessesFramework/Http/BasicAuthServer.hpp"
#include "TessesFramework/Crypto/Crypto.hpp"
namespace Tesses::Framework::Http {
BasicAuthServer::BasicAuthServer()
{
}
BasicAuthServer::BasicAuthServer(std::shared_ptr<IHttpServer> server, std::function<bool(std::string username, std::string password)> auth,std::string realm) : server(server), authorization(auth), realm(realm)
{
}
bool BasicAuthServer::Handle(ServerContext& ctx)
{
std::string www_authenticate = "Basic realm=\"" + this->realm + "\", charset=\"UTF-8\"";
std::string user;
std::string pass;
if(!GetCreds(ctx,user,pass) || !this->authorization(user,pass)) {
ctx.responseHeaders.SetValue("WWW-Authenticate",www_authenticate);
ctx.statusCode = Unauthorized;
return false;
}
if(this->server)
return this->server->Handle(ctx);
ctx.statusCode = InternalServerError;
return false;
}
bool BasicAuthServer::GetCreds(ServerContext& ctx, std::string& user, std::string& pass)
{
std::string auth;
if(!ctx.requestHeaders.TryGetFirst("Authorization", auth)) return false;
auto security = HttpUtils::SplitString(auth," ",2);
if(security.size() < 2) return false;
if(security[0] != "Basic") return false;
auto decoded = Crypto::Base64_Decode(security[0]);
std::string decoded_str(decoded.begin(),decoded.end());
security = HttpUtils::SplitString(auth,":",2);
if(security.size() < 2) return false;
user = security[0];
pass = security[1];
return true;
}
}