From 85adf26a787b33d69d07df0dc786516fed800e21 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Thu, 25 Jun 2015 02:14:18 +0200 Subject: Add basic auth support --- src/auth.cc | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/auth.cc (limited to 'src/auth.cc') diff --git a/src/auth.cc b/src/auth.cc new file mode 100644 index 0000000..015b2fc --- /dev/null +++ b/src/auth.cc @@ -0,0 +1,46 @@ +#include "common.hh" + +#include "auth.hh" +#include "base64.hh" +#include "cgi.hh" +#include "http.hh" +#include "strutils.hh" + +namespace stuff { + +bool Auth::auth(CGI* cgi, const std::string& realm, const std::string& passwd, + std::string* user) { + auto auth = cgi->http_auth(); + auto pos = auth.find(' '); + if (pos != std::string::npos) { + if (ascii_tolower(auth.substr(0, pos)) == "basic") { + std::string tmp; + if (Base64::decode(auth.substr(pos + 1), &tmp)) { + pos = tmp.find(':'); + if (pos != std::string::npos) { + if (tmp.substr(pos + 1) == passwd) { + if (user) user->assign(tmp.substr(0, pos)); + return true; + } + } + } + } + } + + std::map headers; + std::string tmp = realm; + for (auto it = tmp.begin(); it != tmp.end(); ++it) { + if (!((*it >= 'a' && *it <= 'z') || + (*it >= 'A' && *it <= 'Z') || + (*it >= '0' && *it <= '9') || + *it == '-' || *it == '_' || *it == '.' || *it == ' ')) { + *it = '.'; + } + } + headers.insert(std::make_pair("WWW-Authenticate", + "Basic realm=\"" + tmp + "\"")); + Http::response(401, headers, "Authentication needed"); + return false; +} + +} // namespace stuff -- cgit v1.2.3-70-g09d2