Aktualizr
C++ SOTA Client
All Classes Namespaces Files Functions Variables Enumerations Enumerator Pages
oauth2.cc
1 #include <iostream>
2 #include <sstream>
3 
4 #include <curl/curl.h>
5 #include <boost/property_tree/json_parser.hpp>
6 #include <boost/property_tree/ptree.hpp>
7 
8 #include "logging/logging.h"
9 #include "oauth2.h"
10 #include "utilities/utils.h"
11 
12 using boost::property_tree::ptree;
13 using boost::property_tree::json_parser::json_parser_error;
14 using std::stringstream;
15 
16 /**
17  * Handle CURL write callbacks by appending to a stringstream
18  */
19 size_t curl_handle_write_sstream(void *buffer, size_t size, size_t nmemb, void *userp) {
20  auto *body = static_cast<stringstream *>(userp);
21  body->write(static_cast<const char *>(buffer), static_cast<std::streamsize>(size * nmemb));
22  return size * nmemb;
23 }
24 
25 AuthenticationResult OAuth2::Authenticate() {
26  CurlEasyWrapper curl_handle;
27  curlEasySetoptWrapper(curl_handle.get(), CURLOPT_VERBOSE, get_curlopt_verbose());
28  curlEasySetoptWrapper(curl_handle.get(), CURLOPT_URL, (server_ + "/token").c_str());
29  if (!ca_certs_.empty()) {
30  curlEasySetoptWrapper(curl_handle.get(), CURLOPT_CAINFO, ca_certs_.c_str());
31  curlEasySetoptWrapper(curl_handle.get(), CURLOPT_CAPATH, NULL);
32  }
33 
34  curlEasySetoptWrapper(curl_handle.get(), CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
35  curlEasySetoptWrapper(curl_handle.get(), CURLOPT_USERNAME, client_id_.c_str());
36  curlEasySetoptWrapper(curl_handle.get(), CURLOPT_PASSWORD, client_secret_.c_str());
37  curlEasySetoptWrapper(curl_handle.get(), CURLOPT_POST, 1);
38  curlEasySetoptWrapper(curl_handle.get(), CURLOPT_COPYPOSTFIELDS, "grant_type=client_credentials");
39 
40  stringstream body;
41  curlEasySetoptWrapper(curl_handle.get(), CURLOPT_WRITEFUNCTION, &curl_handle_write_sstream);
42  curlEasySetoptWrapper(curl_handle.get(), CURLOPT_WRITEDATA, &body);
43 
44  curl_easy_perform(curl_handle.get());
45 
46  long rescode; // NOLINT(google-runtime-int)
47  curl_easy_getinfo(curl_handle.get(), CURLINFO_RESPONSE_CODE, &rescode);
48  if (rescode == 200) {
49  ptree pt;
50  try {
51  read_json(body, pt);
52  token_ = pt.get("access_token", "");
53  LOG_TRACE << "Got OAuth2 access token:" << token_;
54  return AuthenticationResult::kSuccess;
55  } catch (const json_parser_error &e) {
56  token_ = "";
57  return AuthenticationResult::kFailure;
58  }
59  } else {
60  return AuthenticationResult::kFailure;
61  }
62 }
63 
64 // vim: set tabstop=2 shiftwidth=2 expandtab:
CurlEasyWrapper
Definition: utils.h:146
OAuth2::Authenticate
AuthenticationResult Authenticate()
Synchronously attempt to get an access token from Auth+.
Definition: oauth2.cc:25