algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
auth.hpp
1#pragma once
2
3#include "./config.hpp"
4#include "./network.hpp"
5
6#include <mutex>
7
8namespace algotradelib {
9namespace tossinvest {
10
11class TossAuth;
12
18class TossAuth {
19public:
26 TossAuth(net::io_context& ioc, ssl::context& ctx, const TossConfig& config) : ioc_(ioc), ctx_(ctx), req_(config) {}
27
29 virtual ~TossAuth() = default;
30
38 std::string accessToken() {
39 std::lock_guard<std::mutex> lock(mtx_);
40 if (!rest_resp_.valid()) {
41 refresh();
42 }
43 return rest_resp_.access_token_;
44 }
45
46private:
47 net::io_context& ioc_;
48 ssl::context& ctx_;
49 TossConfig req_;
50 TossRest rest_resp_;
51 std::mutex mtx_;
52
53 void refresh() {
54 const std::string formbody = req_.to_form_urlencoded_body();
55 TossHttpClient rest(ioc_, ctx_, "openapi.tossinvest.com", "443");
56 auto response = rest.post("/oauth2/token", formbody, {{"Content-Type", "application/x-www-form-urlencoded"}});
57 if (response.result_int() < 200 || response.result_int() >= 300) {
58 throw std::runtime_error("Token authentication failed with HTTP status " + std::to_string(response.result_int()));
59 }
60 const std::string resp = std::move(response.body());
61 boost::system::error_code ec;
62 const auto jv = json::parse(resp, ec);
63 if (ec || !jv.is_object()) {
64 // Not the body: a token reply that did not parse may still hold the token.
65 throw std::runtime_error(
66 "Token authentication failed: the reply is not a JSON object (" + std::to_string(resp.size()) + " bytes)"
67 );
68 }
69 rest_resp_.from_json(jv.as_object());
70 }
71};
72
73} // namespace tossinvest
74} // namespace algotradelib
std::string to_form_urlencoded_body() const
Builds a form-encoded token-request body (grant_type, client_id, client_secret).
Definition oauth.hpp:107
Obtains and caches a Toss access token with blocking requests; thread-safe.
Definition auth.hpp:18
virtual ~TossAuth()=default
Destroys the wrapper.
TossAuth(net::io_context &ioc, ssl::context &ctx, const TossConfig &config)
Constructs the wrapper.
Definition auth.hpp:26
std::string accessToken()
Returns an access token, requesting a new one if none is held or it expires within five minutes.
Definition auth.hpp:38
The Toss Securities Open API client.
Definition auth.hpp:9
network::HttpClient TossHttpClient
The blocking HTTP client TossAuth uses.
Definition network.hpp:9
The library: broker-neutral types (core), and the modules below.
Toss Securities credentials (client id and secret). Toss has no demo environment.
Definition config.hpp:27
A Toss REST access token and its expiry.
Definition config.hpp:120