-
Notifications
You must be signed in to change notification settings - Fork 2
/
oauth2.hpp
106 lines (87 loc) · 2.83 KB
/
oauth2.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#pragma once
#define REQUESTS_WITH_NLOHMANN_JSON
#include "requests.hpp"
#include <vector>
#include <string>
#include <random>
struct oauth2
{
std::string auth_endpoint;
std::string token_endpoint;
std::string client_id, client_secret;
std::string redirect_uri = "";
static std::string random_state(size_t n = 16)
{
std::string state(n, 'x');
constexpr std::string_view alphabet = "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789";
static std::mt19937 gen(std::random_device{}());
static std::uniform_int_distribution<> dist(0, alphabet.size() - 1);
for (auto &c : state) { c = alphabet[dist(gen)]; }
return state;
}
struct authorization_url_res_t
{
requests::url url;
std::string state;
};
enum class response_type {code, token};
auto authorization_url(
response_type rt,
std::vector<std::string_view> scopes,
const std::string &state = random_state()
) const
{
authorization_url_res_t res { { auth_endpoint }, state };
std::string scope;
for (const auto &s : scopes)
{
if (!scope.empty()) { scope += "%20"; }
scope += s;
}
std::string response = rt == response_type::code ? "code" : "token";
requests::query q = {{
{ "response_type", response },
{ "client_id", client_id },
{ "scope", scope },
{ "state", state },
{ "redirect_uri", redirect_uri }
}};
res.url.query = requests::urlencoded(q);
return res;
}
auto authorization_url(
std::vector<std::string_view> scopes,
const std::string &state = random_state()
) const { return authorization_url(response_type::code, scopes, state); }
struct token
{
std::string access_token;
std::string token_type;
unsigned expires_in = 0;
std::string refresh_token = ""; // Possibly empty
std::string scope;
};
token access_token(const std::string &code)
{
auto r = requests::post(
{ token_endpoint },
requests::data{{
{ "grant_type", "authorization_code" },
{ "code", code },
{ "client_id", client_id },
{ "client_secret", client_secret },
{ "redirect_uri", redirect_uri }
}}
);
auto json = r.json();
return token{
json["access_token"].get<std::string>(),
json["token_type"].get<std::string>(),
json["expires_in"].get<unsigned>(),
json["refresh_token"].get<std::string>(),
json["scope"].get<std::string>()
};
}
};