#include "pihttpserverbasicauth.h" #include "piliterals_string.h" namespace { bool parseBasic(const PIString & auth_header, PIString & user, PIString & pass) { if (auth_header.left(6).toLowerCase() != "basic "_a) return false; PIString rest = auth_header.mid(6).trimmed(); if (rest.isEmpty()) return false; PIByteArray decoded = PIByteArray::fromBase64(rest); if (decoded.isEmpty()) return false; PIString creds = PIString::fromUTF8(decoded); int ind = creds.find(':'); if (ind < 0) return false; user = creds.takeLeft(ind); creds.pop_front(); pass = creds; return true; } } // namespace PIHTTPServerBasicAuth::PIHTTPServerBasicAuth() { auth_realm = "Restricted"_a; } PIHTTP::MessageMutable PIHTTPServerBasicAuth::accessDeniedReply(const PIHTTP::MessageConst &) { return PIHTTP::MessageMutable::fromCode(PIHTTP::Code::Unauthorized) .addHeader(PIHTTP::Header::WWWAuthenticate, "Basic realm=\"%1\", charset=\"UTF-8\""_a.arg(auth_realm)) .setBody(PIByteArray::fromAscii("Authorization required")); } PIHTTP::AuthInfo PIHTTPServerBasicAuth::authenticate(const PIHTTP::MessageConst & request) { if (!callback_auth) return PIHTTP::AuthInfo(); PIString header = request.headers().value(PIHTTP::Header::Authorization, ""); PIString user, pass; if (!parseBasic(header, user, pass)) return PIHTTP::AuthInfo(); return callback_auth(user, pass); }