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