10 #include <boost/algorithm/string.hpp>
11 #include <pion/PionAlgorithms.hpp>
12 #include <pion/net/HTTPBasicAuth.hpp>
13 #include <pion/net/HTTPResponseWriter.hpp>
14 #include <pion/net/HTTPServer.hpp>
23 const unsigned int HTTPBasicAuth::CACHE_EXPIRATION = 300;
29 :
HTTPAuth(userManager), m_realm(realm),
30 m_cache_cleanup_time(boost::posix_time::second_clock::universal_time())
32 setLogger(PION_GET_LOGGER(
"pion.net.HTTPBasicAuth"));
41 PionDateTime time_now(boost::posix_time::second_clock::universal_time());
42 if (time_now > m_cache_cleanup_time + boost::posix_time::seconds(CACHE_EXPIRATION)) {
44 boost::mutex::scoped_lock cache_lock(m_cache_mutex);
45 PionUserCache::iterator i;
46 PionUserCache::iterator next=m_user_cache.begin();
47 while (next!=m_user_cache.end()) {
50 if (time_now > i->second.first + boost::posix_time::seconds(CACHE_EXPIRATION)) {
52 m_user_cache.erase(i);
55 m_cache_cleanup_time = time_now;
59 std::string authorization = request->getHeader(HTTPTypes::HEADER_AUTHORIZATION);
60 if (!authorization.empty()) {
61 std::string credentials;
64 boost::mutex::scoped_lock cache_lock(m_cache_mutex);
65 PionUserCache::iterator user_cache_ptr=m_user_cache.find(credentials);
66 if (user_cache_ptr!=m_user_cache.end()) {
69 request->setUser(user_cache_ptr->second.second);
70 user_cache_ptr->second.first = time_now;
82 m_user_cache.insert(std::make_pair(credentials, std::make_pair(time_now, user)));
84 request->setUser(user);
106 if (!boost::algorithm::starts_with(authorization,
"Basic "))
108 credentials = authorization.substr(6);
109 if (credentials.empty())
115 std::string &username, std::string &password)
117 std::string user_password;
123 std::string::size_type i = user_password.find(
':');
124 if (i==0 || i==std::string::npos)
127 username = user_password.substr(0, i);
128 password = user_password.substr(i+1);
134 TCPConnectionPtr& tcp_conn)
137 static const std::string CONTENT =
138 " <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""
139 "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">"
142 "<TITLE>Error</TITLE>"
143 "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=ISO-8859-1\">"
145 "<BODY><H1>401 Unauthorized.</H1></BODY>"
149 writer->getResponse().setStatusCode(HTTPTypes::RESPONSE_CODE_UNAUTHORIZED);
150 writer->getResponse().setStatusMessage(HTTPTypes::RESPONSE_MESSAGE_UNAUTHORIZED);
151 writer->getResponse().addHeader(
"WWW-Authenticate",
"Basic realm=\"" + m_realm +
"\"");
152 writer->writeNoCopy(CONTENT);