pion-net  4.0.9
HTTPBasicAuth.cpp
1 // ------------------------------------------------------------------
2 // pion-net: a C++ framework for building lightweight HTTP interfaces
3 // ------------------------------------------------------------------
4 // Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com)
5 //
6 // Distributed under the Boost Software License, Version 1.0.
7 // See http://www.boost.org/LICENSE_1_0.txt
8 //
9 
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>
15 
16 
17 namespace pion { // begin namespace pion
18 namespace net { // begin namespace net (Pion Network Library)
19 
20 
21 // static members of HTTPBasicAuth
22 
23 const unsigned int HTTPBasicAuth::CACHE_EXPIRATION = 300; // 5 minutes
24 
25 
26 // HTTPBasicAuth member functions
27 
28 HTTPBasicAuth::HTTPBasicAuth(PionUserManagerPtr userManager, const std::string& realm)
29  : HTTPAuth(userManager), m_realm(realm),
30  m_cache_cleanup_time(boost::posix_time::second_clock::universal_time())
31 {
32  setLogger(PION_GET_LOGGER("pion.net.HTTPBasicAuth"));
33 }
34 
35 bool HTTPBasicAuth::handleRequest(HTTPRequestPtr& request, TCPConnectionPtr& tcp_conn)
36 {
37  if (!needAuthentication(request)) {
38  return true; // this request does not require authentication
39  }
40 
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)) {
43  // expire cache
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()) {
48  i=next;
49  ++next;
50  if (time_now > i->second.first + boost::posix_time::seconds(CACHE_EXPIRATION)) {
51  // ok - this is an old record.. expire it now
52  m_user_cache.erase(i);
53  }
54  }
55  m_cache_cleanup_time = time_now;
56  }
57 
58  // if we are here, we need to check if access authorized...
59  std::string authorization = request->getHeader(HTTPTypes::HEADER_AUTHORIZATION);
60  if (!authorization.empty()) {
61  std::string credentials;
62  if (parseAuthorization(authorization, credentials)) {
63  // to do - use fast cache to match with active 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()) {
67  // we found the credentials in our cache...
68  // we can approve authorization now!
69  request->setUser(user_cache_ptr->second.second);
70  user_cache_ptr->second.first = time_now;
71  return true;
72  }
73 
74  std::string username;
75  std::string password;
76 
77  if (parseCredentials(credentials, username, password)) {
78  // match username/password
79  PionUserPtr user=m_user_manager->getUser(username, password);
80  if (user) {
81  // add user to the cache
82  m_user_cache.insert(std::make_pair(credentials, std::make_pair(time_now, user)));
83  // add user credentials to the request object
84  request->setUser(user);
85  return true;
86  }
87  }
88  }
89  }
90 
91  // user not found
92  handleUnauthorized(request, tcp_conn);
93  return false;
94 }
95 
96 void HTTPBasicAuth::setOption(const std::string& name, const std::string& value)
97 {
98  if (name=="realm")
99  m_realm = value;
100  else
101  throw UnknownOptionException(name);
102 }
103 
104 bool HTTPBasicAuth::parseAuthorization(const std::string& authorization, std::string &credentials)
105 {
106  if (!boost::algorithm::starts_with(authorization, "Basic "))
107  return false;
108  credentials = authorization.substr(6);
109  if (credentials.empty())
110  return false;
111  return true;
112 }
113 
114 bool HTTPBasicAuth::parseCredentials(const std::string &credentials,
115  std::string &username, std::string &password)
116 {
117  std::string user_password;
118 
119  if (! algo::base64_decode(credentials, user_password))
120  return false;
121 
122  // find ':' symbol
123  std::string::size_type i = user_password.find(':');
124  if (i==0 || i==std::string::npos)
125  return false;
126 
127  username = user_password.substr(0, i);
128  password = user_password.substr(i+1);
129 
130  return true;
131 }
132 
133 void HTTPBasicAuth::handleUnauthorized(HTTPRequestPtr& http_request,
134  TCPConnectionPtr& tcp_conn)
135 {
136  // authentication failed, send 401.....
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\">"
140  "<HTML>"
141  "<HEAD>"
142  "<TITLE>Error</TITLE>"
143  "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=ISO-8859-1\">"
144  "</HEAD>"
145  "<BODY><H1>401 Unauthorized.</H1></BODY>"
146  "</HTML> ";
147  HTTPResponseWriterPtr writer(HTTPResponseWriter::create(tcp_conn, *http_request,
148  boost::bind(&TCPConnection::finish, tcp_conn)));
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);
153  writer->send();
154 }
155 
156 } // end namespace net
157 } // end namespace pion
PionUserManagerPtr m_user_manager
container used to manager user objects
Definition: HTTPAuth.hpp:157
static bool base64_decode(std::string const &input, std::string &output)
virtual bool handleRequest(HTTPRequestPtr &request, TCPConnectionPtr &tcp_conn)
virtual void setOption(const std::string &name, const std::string &value)
void setLogger(PionLogger log_ptr)
sets the logger to be used
Definition: HTTPAuth.hpp:150
static bool parseCredentials(std::string const &credentials, std::string &username, std::string &password)
static bool parseAuthorization(std::string const &authorization, std::string &credentials)
HTTPBasicAuth(PionUserManagerPtr userManager, const std::string &realm="PION:NET")
default constructor
the following enables use of the lock-free cache
void handleUnauthorized(HTTPRequestPtr &http_request, TCPConnectionPtr &tcp_conn)
bool needAuthentication(HTTPRequestPtr const &http_request) const
Definition: HTTPAuth.cpp:37
exception thrown if the service does not recognize a configuration option
Definition: HTTPAuth.hpp:36
static boost::shared_ptr< HTTPResponseWriter > create(TCPConnectionPtr &tcp_conn, HTTPResponsePtr &http_response, FinishedHandler handler=FinishedHandler())
boost::posix_time::ptime PionDateTime
PionDateTime is a typedef for boost::posix_time::ptime.