-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathgsheets_auth.cpp
More file actions
247 lines (204 loc) · 9.01 KB
/
gsheets_auth.cpp
File metadata and controls
247 lines (204 loc) · 9.01 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
#include "gsheets_auth.hpp"
#include "gsheets_requests.hpp"
#include "gsheets_utils.hpp"
#include "duckdb/common/exception.hpp"
#include "duckdb/main/secret/secret.hpp"
#include "duckdb/main/extension_util.hpp"
#include <fstream>
#include <cstdlib>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#endif
namespace duckdb
{
std::string read_token_from_file(const std::string &file_path)
{
std::ifstream file(file_path);
if (!file.is_open())
{
throw duckdb::IOException("Unable to open token file: " + file_path);
}
std::string token;
std::getline(file, token);
return token;
}
// This code is copied, with minor modifications from https://github.com/duckdb/duckdb_azure/blob/main/src/azure_secret.cpp
static void CopySecret(const std::string &key, const CreateSecretInput &input, KeyValueSecret &result)
{
auto val = input.options.find(key);
if (val != input.options.end())
{
result.secret_map[key] = val->second;
}
}
static void RegisterCommonSecretParameters(CreateSecretFunction &function)
{
// Register google sheets common parameters
function.named_parameters["token"] = LogicalType::VARCHAR;
}
static void RedactCommonKeys(KeyValueSecret &result)
{
result.redact_keys.insert("proxy_password");
}
// TODO: Maybe this should be a KeyValueSecret
static unique_ptr<BaseSecret> CreateGsheetSecretFromAccessToken(ClientContext &context, CreateSecretInput &input) {
auto scope = input.scope;
auto result = make_uniq<KeyValueSecret>(scope, input.type, input.provider, input.name);
// Manage specific secret option
CopySecret("token", input, *result);
// Redact sensible keys
RedactCommonKeys(*result);
result->redact_keys.insert("token");
return std::move(result);
}
static unique_ptr<BaseSecret> CreateGsheetSecretFromOAuth(ClientContext &context, CreateSecretInput &input)
{
auto scope = input.scope;
auto result = make_uniq<KeyValueSecret>(scope, input.type, input.provider, input.name);
// Initiate OAuth flow
string token = InitiateOAuthFlow();
result->secret_map["token"] = token;
// Redact sensible keys
RedactCommonKeys(*result);
result->redact_keys.insert("token");
return std::move(result);
}
void CreateGsheetSecretFunctions::Register(DatabaseInstance &instance)
{
string type = "gsheet";
// Register the new type
SecretType secret_type;
secret_type.name = type;
secret_type.deserializer = KeyValueSecret::Deserialize<KeyValueSecret>;
secret_type.default_provider = "oauth";
ExtensionUtil::RegisterSecretType(instance, secret_type);
// Register the access_token secret provider
CreateSecretFunction access_token_function = {type, "access_token", CreateGsheetSecretFromAccessToken};
access_token_function.named_parameters["access_token"] = LogicalType::VARCHAR;
RegisterCommonSecretParameters(access_token_function);
ExtensionUtil::RegisterFunction(instance, access_token_function);
// Register the oauth secret provider
CreateSecretFunction oauth_function = {type, "oauth", CreateGsheetSecretFromOAuth};
oauth_function.named_parameters["use_oauth"] = LogicalType::BOOLEAN;
RegisterCommonSecretParameters(oauth_function);
ExtensionUtil::RegisterFunction(instance, oauth_function);
}
std::string InitiateOAuthFlow()
{
const int PORT = 8765; // Define port constant
const std::string client_id = "793766532675-rehqgocfn88h0nl88322ht6d1i12kl4e.apps.googleusercontent.com";
const std::string redirect_uri = "http://localhost:" + std::to_string(PORT);
const std::string auth_url = "https://accounts.google.com/o/oauth2/v2/auth";
std::string access_token;
// Create socket
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) {
throw IOException("Failed to create socket");
}
// Set socket options to allow reuse
int opt = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
close(server_fd);
throw IOException("Failed to set socket options");
}
// Bind to localhost:8765
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
close(server_fd);
throw IOException("Failed to bind to port " + std::to_string(PORT));
}
if (listen(server_fd, 1) < 0) {
close(server_fd);
throw IOException("Failed to listen on socket");
}
// Generate state for CSRF protection
std::string state = generate_random_string(10);
// Construct auth URL
std::string auth_request_url = auth_url + "?client_id=" + client_id +
"&redirect_uri=" + redirect_uri +
"&response_type=token" +
"&scope=https://www.googleapis.com/auth/spreadsheets" +
"&state=" + state;
// Open browser
#ifdef _WIN32
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
throw std::runtime_error("Failed to initialize Winsock");
}
system(("start \"\" \"" + auth_request_url + "\"").c_str());
#elif __APPLE__
system(("open \"" + auth_request_url + "\"").c_str());
#elif __linux__
system(("xdg-open \"" + auth_request_url + "\"").c_str());
#endif
std::cout << std::endl << "Waiting for Login via Browser..." << std::endl << std::endl;
// Accept first connection (GET request)
int client_socket;
if ((client_socket = accept(server_fd, nullptr, nullptr)) < 0) {
close(server_fd);
throw IOException("Failed to accept connection");
}
// Read initial request
char buffer[4096] = {0};
ssize_t bytes_read = read(client_socket, buffer, sizeof(buffer));
// Send response to browser
std::string response = "HTTP/1.1 200 OK\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Access-Control-Allow-Methods: POST, OPTIONS\r\n"
"Access-Control-Allow-Headers: Content-Type\r\n"
"Content-Type: text/html\r\n\r\n"
"<script>"
"const hash = window.location.hash.substring(1);"
"const params = new URLSearchParams(hash);"
"const token = params.get('access_token');"
"if (token) {"
" fetch('/', {"
" method: 'POST',"
" body: token"
" }).then(() => {"
" window.location.href = 'https://duckdb-gsheets.com/oauth#ready=1&access_token=success';"
" });"
"}"
"</script></body></html>";
write(client_socket, response.c_str(), response.length());
close(client_socket);
// Accept second connection (POST request)
if ((client_socket = accept(server_fd, nullptr, nullptr)) < 0) {
close(server_fd);
throw IOException("Failed to accept second connection");
}
// Read the POST request
memset(buffer, 0, sizeof(buffer));
bytes_read = read(client_socket, buffer, sizeof(buffer));
std::string token_request(buffer);
// Send response to POST request
std::string post_response = "HTTP/1.1 200 OK\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Content-Length: 0\r\n\r\n";
write(client_socket, post_response.c_str(), post_response.length());
// Extract token from POST body
size_t body_start = token_request.find("\r\n\r\n");
if (body_start != std::string::npos) {
access_token = token_request.substr(body_start + 4);
}
// Clean up
close(client_socket);
close(server_fd);
if (access_token.empty()) {
throw IOException("Failed to obtain access token");
}
return access_token;
}
#ifdef _WIN32
WSACleanup();
#endif
} // namespace duckdb