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)
27 : ioc_(ioc), ctx_(ctx), req_(config) {}
28
30 virtual ~TossAuth() = default;
31
39 std::string accessToken() {
40 std::lock_guard<std::mutex> lock(mtx_);
41 if (!rest_resp_.valid()) {
42 refresh();
43 }
44 return rest_resp_.access_token_;
45 }
46
47private:
48 net::io_context& ioc_;
49 ssl::context& ctx_;
50 TossConfig req_;
51 TossRest rest_resp_;
52 std::mutex mtx_;
53
54 void refresh() {
55 const std::string formbody = req_.to_form_urlencoded_body();
56 TossHttpClient rest(ioc_, ctx_, "openapi.tossinvest.com", "443");
57 auto response = rest.post("/oauth2/token", formbody, {{"Content-Type", "application/x-www-form-urlencoded"}});
58 if (response.result_int() < 200 || response.result_int() >= 300) {
59 throw std::runtime_error(
60 "Token authentication failed with HTTP status " + std::to_string(response.result_int())
61 );
62 }
63 const std::string resp = std::move(response.body());
64 boost::system::error_code ec;
65 const auto jv = json::parse(resp, ec);
66 if (ec || !jv.is_object()) {
67 // Not the body: a token reply that did not parse may still hold the token.
68 throw std::runtime_error(
69 "Token authentication failed: the reply is not a JSON object (" + std::to_string(resp.size()) + " bytes)"
70 );
71 }
72 rest_resp_.from_json(jv.as_object());
73 }
74};
75
76} // namespace tossinvest
77} // 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:87
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:39
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:24
A Toss REST access token and its expiry.
Definition config.hpp:88