algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
oauth.hpp
1#pragma once
2
8#define ATL_TRANSPORT_LAYER_PRESENT 1
9
10#include <boost/json.hpp>
11
12#include <charconv>
13#include <chrono>
14#include <cstdint>
15#include <optional>
16#include <stdexcept>
17#include <string>
18#include <string_view>
19
20namespace algotradelib {
21
22namespace json = boost::json;
23
24namespace network {
25
36template <typename BrokerType>
38public:
40 static constexpr std::string_view grant_type = "client_credentials";
41
47 void from_env() {
48 static_cast<BrokerType*>(this)->from_env_impl();
49 }
50
57 void from_json(const std::string& filename) {
58 static_cast<BrokerType*>(this)->from_json_impl(filename);
59 }
60
70 void from_json_text(std::string_view text, const std::string& origin) {
71 static_cast<BrokerType*>(this)->from_json_text_impl(text, origin);
72 }
73
78 const std::string& key() const noexcept {
79 return key_;
80 }
81
86 const std::string& secret() const noexcept {
87 return secret_;
88 }
89
95 std::string to_jsonbody() const {
96 json::object value;
97 value["grant_type"] = grant_type;
98 value[BrokerType::key_field()] = key_;
99 value[BrokerType::secret_field()] = secret_;
100 return json::serialize(value);
101 }
102
107 std::string to_form_urlencoded_body() const {
108 return "grant_type=client_credentials&client_id=" + form_encode(key_) + "&client_secret=" + form_encode(secret_);
109 }
110
111protected:
113 std::string key_;
115 std::string secret_;
116
117private:
118 // Percent-encodes one form value using the RFC 3986 unreserved character set.
119 //
120 // Encoding reserved characters such as `&`, `=`, `+`, and `%` prevents a
121 // credential value from changing the surrounding form-field structure.
122 static std::string form_encode(std::string_view value) {
123 static constexpr char hex[] = "0123456789ABCDEF";
124 std::string result;
125 result.reserve(value.size());
126 for (const unsigned char ch : value) {
127 const bool unreserved = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') ||
128 ch == '-' || ch == '.' || ch == '_' || ch == '~';
129 if (unreserved) {
130 result.push_back(static_cast<char>(ch));
131 } else {
132 result.push_back('%');
133 result.push_back(hex[ch >> 4]);
134 result.push_back(hex[ch & 0x0F]);
135 }
136 }
137 return result;
138 }
139};
140
149template <typename BrokerType>
150struct AuthBody {
152 std::string access_token_;
154 std::chrono::system_clock::time_point expires_at_{};
155
166 void from_json(const json::object& document) {
167 const std::string_view field = BrokerType::token_field();
168 const auto token = document.if_contains(field);
169 if (!token || !token->is_string()) {
170 throw std::runtime_error("token response has no " + std::string(field) + " string");
171 }
172 access_token_ = token->as_string().c_str();
173
174 expires_at_ = std::chrono::system_clock::time_point{};
175 if (const auto value = document.if_contains("expires_in")) {
176 std::optional<std::int64_t> expires_in;
177 if (value->is_int64()) {
178 expires_in = value->as_int64();
179 } else if (value->is_uint64()) {
180 expires_in = static_cast<std::int64_t>(value->as_uint64());
181 } else if (value->is_string()) {
182 expires_in = parse_seconds(value->as_string());
183 }
184 if (expires_in) {
185 expires_at_ = std::chrono::system_clock::now() + std::chrono::seconds(*expires_in);
186 }
187 }
188 static_cast<BrokerType*>(this)->from_json_impl(document);
189 if (expires_at_ == std::chrono::system_clock::time_point{}) {
190 throw std::runtime_error(
191 "token response states no expiry, neither expires_in nor a broker-specific absolute one"
192 );
193 }
194 }
195
201 bool valid(std::chrono::seconds margin = std::chrono::minutes(5)) const noexcept {
202 return !access_token_.empty() && std::chrono::system_clock::now() + margin < expires_at_;
203 }
204
205private:
206 // Reads a whole number of seconds, or nothing when the text is not one. A malformed `expires_in`
207 // leaves `expires_at_` unset, so it reaches the no-expiry refusal rather than throwing an
208 // exception that names neither the broker nor the field.
209 static std::optional<std::int64_t> parse_seconds(std::string_view text) {
210 std::int64_t seconds{0};
211 const auto parsed = std::from_chars(text.data(), text.data() + text.size(), seconds);
212 if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) {
213 return std::nullopt;
214 }
215 return seconds;
216 }
217};
218
219} // namespace network
220} // namespace algotradelib
OAuth client credentials (an app key and secret), the base of each broker's credentials class.
Definition oauth.hpp:37
void from_env()
Loads the credentials from the broker's environment variables.
Definition oauth.hpp:47
std::string to_form_urlencoded_body() const
Builds a form-encoded token-request body (grant_type, client_id, client_secret).
Definition oauth.hpp:107
const std::string & key() const noexcept
Returns the app key (client id).
Definition oauth.hpp:78
static constexpr std::string_view grant_type
The OAuth grant type sent in a token request.
Definition oauth.hpp:40
std::string key_
The app key (client id).
Definition oauth.hpp:113
void from_json_text(std::string_view text, const std::string &origin)
Loads the credentials from JSON text in the broker's format, as from_json reads a file's contents,...
Definition oauth.hpp:70
std::string secret_
The app secret.
Definition oauth.hpp:115
void from_json(const std::string &filename)
Loads the credentials from a JSON file, in the broker's format.
Definition oauth.hpp:57
std::string to_jsonbody() const
Builds a JSON token-request body (grant type, key and secret under the broker's field names).
Definition oauth.hpp:95
const std::string & secret() const noexcept
Returns the app secret.
Definition oauth.hpp:86
HTTP and WebSocket transport, OAuth tokens, and request pacing.
The library: broker-neutral types (core), and the modules below.
An OAuth access token and its expiry, the base of each broker's token-response class.
Definition oauth.hpp:150
bool valid(std::chrono::seconds margin=std::chrono::minutes(5)) const noexcept
Tests whether the token is set and stays valid for at least a margin.
Definition oauth.hpp:201
std::chrono::system_clock::time_point expires_at_
When the token expires.
Definition oauth.hpp:154
void from_json(const json::object &document)
Reads a token response.
Definition oauth.hpp:166
std::string access_token_
The bearer token; do not log it.
Definition oauth.hpp:152