-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathWebControl.cpp
More file actions
859 lines (822 loc) · 27 KB
/
Copy pathWebControl.cpp
File metadata and controls
859 lines (822 loc) · 27 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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
#include "WebControl.h"
#include "logger.h"
#include <regex>
#include "json/CJsonObject.h"
#include "rbslib/CharsetConvert.h"
#include "WhiteBlackList.h"
#include <ranges>
asio::awaitable<void> WebControlServer::TimeTaskUsers(std::shared_ptr<Proxy>& proxy_client)
{
try
{
asio::steady_timer timer(co_await asio::this_coro::executor);
while (true)
{
std::shared_lock<std::shared_mutex> lock(time_online_users_mutex);
time_online_users[std::time(nullptr)] = proxy_client->GetUsersInfo().size();
lock.unlock();
timer.expires_after(std::chrono::minutes(1));
co_await timer.async_wait(asio::use_awaitable);
}
}
catch (...){}
}
void WebControlServer::SendErrorResponse(const RbsLib::Network::TCP::TCPConnection& connection, int status_code, const std::string& message)
{
neb::CJsonObject json;
json.Add("status", status_code);
json.Add("message", RbsLib::Encoding::CharsetConvert::ANSItoUTF8(message));
SendErrorResponse(connection, json);
}
void WebControlServer::SendErrorResponse(const RbsLib::Network::TCP::TCPConnection& connection, const neb::CJsonObject& json, int http_status_code)
{
RbsLib::Network::HTTP::ResponseHeader response;
response.status = http_status_code;
response.headers.AddHeader("Content-Type", "application/json; charset=utf-8");
response.headers.AddHeader("Content-Length", std::to_string(json.ToString().size()));
response.headers.AddHeader("Access-Control-Allow-Origin", "*");
RbsLib::Buffer response_buffer = response.ToBuffer();
connection.Send(response.ToBuffer());
connection.Send(json.ToString().c_str(), json.ToString().size());
}
void WebControlServer::SendSuccessResponse(const RbsLib::Network::TCP::TCPConnection& connection, const neb::CJsonObject& json)
{
neb::CJsonObject wait_send_json = json;
wait_send_json.Add("status", 200);
wait_send_json.Add("message", "OK");
auto json_str = wait_send_json.ToString();
RbsLib::Network::HTTP::ResponseHeader response;
response.status = 200;
response.headers.AddHeader("Content-Type", "application/json; charset=utf-8");
response.headers.AddHeader("Content-Length", std::to_string(json_str.size()));
response.headers.AddHeader("Access-Control-Allow-Origin", "*");
connection.Send(response.ToBuffer());
connection.Send(json_str.c_str(), json_str.length());
}
bool WebControlServer::CheckToken(const std::string& cookie, const std::string& token, const std::chrono::system_clock::time_point& token_expiry_time)
{
std::string extracted_token = cookie;
return (extracted_token == token) && (std::chrono::system_clock::now() < token_expiry_time);
}
void WebControlServer::GetOnlineUsers(neb::CJsonObject& response, const std::shared_ptr<Proxy>& proxy_client)
{
auto online_user_list = proxy_client->GetUsersInfo();
auto proxy_map = proxy_client->GetUserProxyMap();
auto default_proxy = proxy_client->GetDefaultProxy();
response.AddEmptySubArray("online_users");
for (const auto& user : online_user_list)
{
neb::CJsonObject user_info;
user_info.Add("username", user.username);
user_info.Add("uuid", user.uuid);
user_info.Add("ip", user.ip);
user_info.Add("current_proxy_flow", user.upload_bytes);
user_info.Add("total_proxy_flow", 0);
user_info.Add("online_time_stamp", user.connect_time);
if (auto proxy_item = proxy_map.find(user.username); proxy_item != proxy_map.end())
{
user_info.Add("proxy_target", proxy_item->second.first + ":" + std::to_string(proxy_item->second.second));
}
else
{
user_info.Add("proxy_target", default_proxy.first + ":" + std::to_string(default_proxy.second));
}
response["online_users"].Add(user_info);
}
}
void WebControlServer::GetWhiteList(neb::CJsonObject& response, const std::shared_ptr<Proxy>& proxy_client)
{
auto white_list = WhiteBlackList::GetWhiteList();
bool is_whitelist_on = WhiteBlackList::IsWhiteListOn();
response.Add("whitelist_status", is_whitelist_on,is_whitelist_on);
response.AddEmptySubArray("white_list");
for (const auto& user : white_list)
{
response["white_list"].Add(user);
}
}
void WebControlServer::GetBlackList(neb::CJsonObject& response, const std::shared_ptr<Proxy>& proxy_client)
{
auto black_list = WhiteBlackList::GetBlackList();
response.AddEmptySubArray("black_list");
for (const auto& user : black_list)
{
response["black_list"].Add(user);
}
}
bool WebControlServer::AddBlacklistUser(neb::CJsonObject& response, const neb::CJsonObject& request, const std::shared_ptr<Proxy>& proxy_client)
{
std::string username;
if (!request.Get("username",username))
{
response.Add("status", 400);
response.Add("message", "Missing 'username' field in request");
return false;
}
if (WhiteBlackList::IsInBlack(username))
{
response.Add("status", 400);
response.Add("message", "User is already in black list");
return false;
}
WhiteBlackList::AddBlackList(username);
Logger::LogInfo("WebAPI: Added user %s to blacklist", username.c_str());
response.Add("status", 200);
response.Add("message", "User added to black list successfully");
return true;
}
bool WebControlServer::RemoveBlacklistUser(neb::CJsonObject& response, const neb::CJsonObject& request, const std::shared_ptr<Proxy>& proxy_client)
{
std::string username;
if (!request.Get("username", username))
{
response.Add("status", 400);
response.Add("message", "Missing 'username' field in request");
return false;
}
if (!WhiteBlackList::IsInBlack(username))
{
response.Add("status", 400);
response.Add("message", "User is not in black list");
return false;
}
WhiteBlackList::RemoveBlackList(username);
Logger::LogInfo("WebAPI: Removed user %s from blacklist", username.c_str());
response.Add("status", 200);
response.Add("message", "User removed from black list successfully");
return true;
}
bool WebControlServer::AddWhitelistUser(neb::CJsonObject& response, const neb::CJsonObject& request, const std::shared_ptr<Proxy>& proxy_client)
{
std::string username;
if (!request.Get("username", username))
{
response.Add("status", 400);
response.Add("message", "Missing 'username' field in request");
return false;
}
if (WhiteBlackList::IsInWhite(username))
{
response.Add("status", 400);
response.Add("message", "User is already in white list");
return false;
}
WhiteBlackList::AddWhiteList(username);
Logger::LogInfo("WebAPI: Added user %s to whitelist", username.c_str());
response.Add("status", 200);
response.Add("message", "User added to white list successfully");
return true;
}
bool WebControlServer::RemoveWhitelistUser(neb::CJsonObject& response, const neb::CJsonObject& request, const std::shared_ptr<Proxy>& proxy_client)
{
std::string username;
if (!request.Get("username", username))
{
response.Add("status", 400);
response.Add("message", "Missing 'username' field in request");
return false;
}
if (!WhiteBlackList::IsInWhite(username))
{
response.Add("status", 400);
response.Add("message", "User is not in white list");
return false;
}
WhiteBlackList::RemoveWhiteList(username);
Logger::LogInfo("WebAPI: Removed user %s from whitelist", username.c_str());
response.Add("status", 200);
response.Add("message", "User removed from white list successfully");
return true;
}
bool WebControlServer::EnableWhitelist(neb::CJsonObject& response, const std::shared_ptr<Proxy>& proxy_client)
{
if (WhiteBlackList::IsWhiteListOn())
{
response.Add("status", 400);
response.Add("message", "Whitelist is already enabled");
return false;
}
else
{
WhiteBlackList::WhiteListOn();
Logger::LogInfo("WebAPI: Enabled whitelist");
response.Add("status", 200);
response.Add("message", "Whitelist enabled successfully");
return true;
}
}
bool WebControlServer::DisableWhitelist(neb::CJsonObject& response, const std::shared_ptr<Proxy>& proxy_client)
{
if (!WhiteBlackList::IsWhiteListOn())
{
response.Add("status", 400);
response.Add("message", "Whitelist is already disabled");
return false;
}
else
{
WhiteBlackList::WhiteListOff();
Logger::LogInfo("WebAPI: Disabled whitelist");
response.Add("status", 200);
response.Add("message", "Whitelist disabled successfully");
return true;
}
}
void WebControlServer::GetUserProxyList(neb::CJsonObject& response, const std::shared_ptr<Proxy>& proxy_client)
{
auto proxy_map = proxy_client->GetUserProxyMap();
auto default_proxy = proxy_client->GetDefaultProxy();
response.Add("default_proxy", default_proxy.first + ":" + std::to_string(default_proxy.second));
response.AddEmptySubArray("user_proxies");
for (const auto& item : proxy_map)
{
neb::CJsonObject user_proxy;
user_proxy.Add("username", item.first);
user_proxy.Add("proxy_target_addr", item.second.first);
user_proxy.Add("proxy_target_port", item.second.second);
response["user_proxies"].Add(user_proxy);
}
}
bool WebControlServer::SetUserProxy(neb::CJsonObject& response, const neb::CJsonObject& request, const std::shared_ptr<Proxy>& proxy_client)
{
std::string username;
std::string proxy_address;
int proxy_port;
if (!request.Get("username", username) || !request.Get("proxy_address", proxy_address) || !request.Get("proxy_port", proxy_port))
{
response.Add("status", 400);
response.Add("message", "Missing 'username', 'proxy_address' or 'proxy_port' field in request");
return false;
}
if (proxy_port < 1 || proxy_port > 65535)
{
response.Add("status", 400);
response.Add("message", "Invalid 'proxy_port' value, must be in range 1-65535");
return false;
}
proxy_client->SetUserProxy(username, proxy_address, static_cast<std::uint16_t>(proxy_port));
Logger::LogInfo("WebAPI: Set proxy server for user %s to %s:%d", username.c_str(), proxy_address.c_str(), proxy_port);
response.Add("status", 200);
response.Add("message", "User proxy set successfully");
return true;
}
bool WebControlServer::RemoveUserProxy(neb::CJsonObject& response, const neb::CJsonObject& request, const std::shared_ptr<Proxy>& proxy_client)
{
std::string username;
if (!request.Get("username", username))
{
response.Add("status", 400);
response.Add("message", "Missing 'username' field in request");
return false;
}
try
{
proxy_client->DeleteUserProxy(username);
Logger::LogInfo("WebAPI: Deleted proxy server setting for user %s", username.c_str());
}
catch (ProxyException const& ex)
{
response.Add("status", 400);
response.Add("message", ex.what());
return false;
}
response.Add("status", 200);
response.Add("message", "User proxy removed successfully");
return true;
}
bool WebControlServer::SetMaxUsers(neb::CJsonObject& response, const neb::CJsonObject& request, const std::shared_ptr<Proxy>& proxy_client)
{
int max_users;
if (!request.Get("max_users", max_users) || max_users < -1)
{
response.Add("status", 400);
response.Add("message", "Invalid 'max_users' value");
return false;
}
proxy_client->SetMaxPlayer(max_users);
Logger::LogInfo("WebAPI: Set maximum users to %d", max_users);
response.Add("status", 200);
response.Add("message", "Max users set successfully");
return true;
}
bool WebControlServer::KickPlayer(neb::CJsonObject& response, const neb::CJsonObject& request, const std::shared_ptr<Proxy>& proxy_client)
{
std::string username;
if (!request.Get("username", username))
{
response.Add("status", 400);
response.Add("message", "Missing 'username' field in request");
return false;
}
try
{
proxy_client->KickByUsername(username);
Logger::LogInfo("WebAPI: Kicked user %s", username.c_str());
response.Add("status", 200);
response.Add("message", "Player kicked successfully");
return true;
}
catch (ProxyException const& ex)
{
response.Add("status", 400);
response.Add("message", ex.what());
return false;
}
}
void WebControlServer::GetStartTime(neb::CJsonObject& response, const std::shared_ptr<Proxy>& proxy_client)
{
auto start_time = proxy_client->GetStartTime();
response.Add("start_time", start_time);
response.Add("now_time", std::time(nullptr));
response.Add("status", 200);
response.Add("message", "Start time retrieved successfully");
}
// 修改的函数 GetUserNumberList返回的数据
bool WebControlServer::GetUserNumberList(neb::CJsonObject& response, neb::CJsonObject& request, const std::shared_ptr<Proxy>& proxy_client)
{
// 获取时间范围
std::time_t start_time, end_time;
if (!request.Get("start_time", start_time) || !request.Get("end_time", end_time) || start_time >= end_time)
{
response.Add("status", 400);
response.Add("message", "Invalid 'start_time' or 'end_time' value");
return false;
}
// 获取粒度 minute(分钟)、hour(小时)、day(天)、week(周)、month(月)
std::string granularity;
if (!request.Get("granularity", granularity) || (granularity != "minute" && granularity != "hour" && granularity != "day" && granularity != "week" && granularity != "month"))
{
response.Add("status", 400);
response.Add("message", "Invalid 'granularity' value");
return false;
}
// 使用ranges库获取时间范围内的在线用户数量
std::shared_lock<std::shared_mutex> lock(this->time_online_users_mutex);
auto filtered_view = std::ranges::views::filter(this->time_online_users, [start_time, end_time](const auto& item) {
return item.first >= start_time && item.first <= end_time;
});
// 根据粒度分组统计
std::map<std::time_t, uint32_t> grouped,count;
for (const auto& item : filtered_view)
{
std::time_t key = 0;
if (granularity == "minute")
{
key = item.first / 60 * 60;
}
else if (granularity == "hour")
{
key = item.first / 3600 * 3600;
}
else if (granularity == "day")
{
key = item.first / 86400 * 86400;
}
else if (granularity == "week")
{
key = item.first / (7 * 86400) * (7 * 86400);
}
else if (granularity == "month")
{
std::tm tm = *std::localtime(&item.first);
tm.tm_mday = 1; // 设置为当月第一天
tm.tm_hour = 0;
tm.tm_min = 0;
tm.tm_sec = 0;
key = std::mktime(&tm);
}
grouped[key] += item.second;
count[key]++; // 统计每个时间段的数据个数
}
// 计算每个时间段平均在线用户数
for (auto& item : grouped)
{
if (count[item.first] > 0)
{
item.second = static_cast<int>(std::round(static_cast<double>(item.second) / count[item.first])); // 计算平均值
}
else
{
item.second = 0; // 如果没有数据则设置为0
}
}
response.AddEmptySubArray("user_numbers");
for (const auto& item : grouped)
{
neb::CJsonObject user_number;
user_number.Add("timestamp", item.first);
user_number.Add("online_users", item.second);
response["user_numbers"].Add(user_number);
}
lock.unlock();
response.Add("status", 200);
response.Add("message", "User number list retrieved successfully");
return true;
}
void WebControlServer::GetLogs(neb::CJsonObject& response, const std::shared_ptr<Proxy>& proxy_client)
{
response.AddEmptySubArray("logs");
std::shared_lock<std::shared_mutex> lock(this->log_mutex);
for (const auto& log : this->logs)
{
neb::CJsonObject log_entry;
log_entry.Add("timestamp", log.first);
log_entry.Add("message", log.second);
response["logs"].Add(log_entry);
}
lock.unlock();
response.Add("status", 200);
response.Add("message", "Logs retrieved successfully");
}
void WebControlServer::GetMotd(neb::CJsonObject& response, const std::shared_ptr<Proxy>& proxy_client)
{
response.Add("motd", proxy_client->GetMotd());
response.Add("status", 200);
response.Add("message", "MOTD retrieved successfully");
}
bool WebControlServer::SetMotd(neb::CJsonObject& response, const neb::CJsonObject& request, const std::shared_ptr<Proxy>& proxy_client)
{
neb::CJsonObject motd;
if (request.Get("motd", motd))
{
proxy_client->SetMotd(motd.ToString());
Logger::LogInfo("WebAPI: Set new MOTD");
response.Add("status", 200);
response.Add("message", "MOTD set successfully");
return true;
}
else
{
response.Add("status", 400);
response.Add("message", "Missing or invalid 'motd' field in request");
return false;
}
}
WebControlServer::WebControlServer(const std::string& address, std::uint16_t port)
:server(address, port)
{
}
WebControlServer::~WebControlServer() noexcept
{
if (!this->is_request_stop)
{
this->Stop();
}
}
void WebControlServer::SetUserPassword(const std::string& password)
{
this->user_password = std::make_shared<std::string>(password);
}
void WebControlServer::Start(std::shared_ptr<Proxy>& proxy_client)
{
//注册日志回调
proxy_client->on_login += [this](Proxy::ConnectionControl& control) {
std::unique_lock<std::shared_mutex> lock(this->log_mutex);
this->logs.push_back({ std::time(nullptr), RbsLib::Encoding::CharsetConvert::ANSItoUTF8("Player " + control.Username() + " uuid:" + control.UUID() + " logged in from " + control.GetAddress()) });
if (this->max_log_size > this->max_log_size)
{
this->logs.pop_front(); //删除最旧的日志
}
};
proxy_client->on_logout += [this](Proxy::ConnectionControl& control) {
double flow = control.UploadBytes();
std::string unit = "bytes";
if (flow > 10000) {
flow /= 1024;
unit = "KB";
}
if (flow > 10000) {
flow /= 1024;
unit = "MB";
}
if (flow > 10000) {
flow /= 1024;
unit = "GB";
}
double time = std::time(nullptr) - control.ConnectTime();
std::string time_unit = "seconds";
if (time > 100) {
time /= 60;
time_unit = "minutes";
}
if (time > 100) {
time /= 60;
time_unit = "hours";
}
std::unique_lock<std::shared_mutex> lock(this->log_mutex);
this->logs.push_back({ std::time(nullptr), RbsLib::Encoding::CharsetConvert::ANSItoUTF8("Player " + control.Username() + " uuid:" + control.UUID() + " logged out from " + control.GetAddress() + ", online duration " + std::to_string(time) + " " + time_unit + ", traffic used " + std::to_string(flow) + " " + unit) });
if (this->logs.size() > this->max_log_size)
{
this->logs.pop_front(); //删除最旧的日志
}
};
this->server.SetGetHandle([proxy = proxy_client, this](const RbsLib::Network::TCP::TCPConnection& connection, RbsLib::Network::HTTP::RequestHeader& header) -> int {
static const std::regex re_userproxy(R"(^/api/([a-zA-Z0-9_]{1,256})$)");
std::cmatch m;
if (std::regex_match(header.path.c_str(), m, re_userproxy) and m.size() == 2)
{
//检查token
std::string cookie = header.headers.GetHeader("Authorize");
if (!CheckToken(cookie, this->user_token, this->token_expiry_time))
{
WebControlServer::SendErrorResponse(connection, 401, "Unauthorized");
}
else
{
//处理业务逻辑并返回结果
neb::CJsonObject response_body;
if (m[1].str() == "logout")
{
this->user_token = "";
this->token_expiry_time = std::chrono::system_clock::time_point();
Logger::LogInfo("WebAPI: User logged out");
response_body.Add("status", 200);
response_body.Add("message", "Logout successful");
RbsLib::Network::HTTP::ResponseHeader response_header;
response_header.headers.AddHeader("Access-Control-Allow-Origin", "*");
response_header.status = 200;
response_header.headers.AddHeader("Content-Type", "application/json; charset=utf-8");
response_header.headers.AddHeader("Content-Length", std::to_string(response_body.ToString().size()));
connection.Send(response_header.ToBuffer());
auto str = response_body.ToString();
connection.Send(str.c_str(), str.size());
}
else if (m[1].str() == "get_online_users")
{
this->GetOnlineUsers(response_body, proxy);
this->SendSuccessResponse(connection, response_body);
}
else if (m[1].str() == "get_whitelist")
{
this->GetWhiteList(response_body, proxy);
this->SendSuccessResponse(connection, response_body);
}
else if (m[1].str() == "get_blacklist")
{
this->GetBlackList(response_body, proxy);
this->SendSuccessResponse(connection, response_body);
}
else if (m[1].str() == "enable_whitelist")
{
if (this->EnableWhitelist(response_body, proxy))
{
this->SendSuccessResponse(connection, response_body);
}
else
{
this->SendErrorResponse(connection, response_body);
}
}
else if (m[1].str() == "disable_whitelist")
{
if (this->DisableWhitelist(response_body, proxy))
{
this->SendSuccessResponse(connection, response_body);
}
else
{
this->SendErrorResponse(connection, response_body);
}
}
else if (m[1].str() == "get_user_proxies")
{
this->GetUserProxyList(response_body, proxy);
this->SendSuccessResponse(connection, response_body);
}
else if (m[1].str() == "get_start_time")
{
this->GetStartTime(response_body, proxy);
this->SendSuccessResponse(connection, response_body);
}
else if (m[1].str() == "get_logs")
{
this->GetLogs(response_body, proxy);
this->SendSuccessResponse(connection, response_body);
}
else if (m[1].str() == "get_motd")
{
this->GetMotd(response_body, proxy);
this->SendSuccessResponse(connection, response_body);
}
else
{
WebControlServer::SendErrorResponse(connection, 404, "Unknown API endpoint");
}
}
}
else
{
WebControlServer::SendErrorResponse(connection, 404, "Unknown API endpoint");
}
return 0;
});
this->server.SetPostHandle([proxy = proxy_client, this](const RbsLib::Network::TCP::TCPConnection& connection, RbsLib::Network::HTTP::RequestHeader& header, RbsLib::Buffer& buffer) -> int {
static const std::regex re_userproxy(R"(^/api/([a-zA-Z0-9_]{1,256})$)");
std::cmatch m;
if (std::regex_match(header.path.c_str(), m, re_userproxy) and m.size() == 2)
{
//解析JSON
neb::CJsonObject data;
if (!data.Parse(buffer.ToString()))
{
WebControlServer::SendErrorResponse(connection, 400, "Invalid JSON data");
return 0;
}
if (m[1].str() == "login")
{
//登录逻辑
std::string password = data("password");
if (!this->user_password || *this->user_password != password)
{
WebControlServer::SendErrorResponse(connection, 401, "Invalid password");
return 0;
}
//生成token
this->user_token = std::to_string(std::chrono::system_clock::now().time_since_epoch().count());
this->token_expiry_time = std::chrono::system_clock::now() + std::chrono::hours(1); // token有效期1小时
Logger::LogInfo("WebAPI: User successfully logged in via WebAPI");
neb::CJsonObject response;
response.Add("status", 200);
response.Add("message", "Login successful");
response.Add("token", this->user_token);
response.Add("token_expiry_time", std::chrono::system_clock::to_time_t(this->token_expiry_time));
RbsLib::Network::HTTP::ResponseHeader response_header;
response_header.status = 200;
response_header.headers.AddHeader("Content-Type", "application/json; charset=utf-8");
response_header.headers.AddHeader("Access-Control-Allow-Origin", "*");
response_header.headers.AddHeader("Content-Length", std::to_string(response.ToString().size()));
connection.Send(response_header.ToBuffer());
connection.Send(response.ToString().c_str(), response.ToString().size());
}
else
{
//检查token
std::string cookie = header.headers.GetHeader("Authorize");
if (!CheckToken(cookie, this->user_token, this->token_expiry_time))
{
WebControlServer::SendErrorResponse(connection, 401, "Unauthorized");
}
else
{
//处理业务逻辑并返回结果
neb::CJsonObject response_body;
if (m[1].str() == "add_whitelist_user")
{
if (this->AddWhitelistUser(response_body, data, proxy))
{
this->SendSuccessResponse(connection, response_body);
}
else
{
WebControlServer::SendErrorResponse(connection, response_body);
}
}
else if (m[1].str() == "remove_whitelist_user")
{
if (this->RemoveWhitelistUser(response_body, data, proxy))
{
this->SendSuccessResponse(connection, response_body);
}
else
{
WebControlServer::SendErrorResponse(connection, response_body);
}
}
else if (m[1].str() == "add_blacklist_user")
{
if (this->AddBlacklistUser(response_body, data, proxy))
{
this->SendSuccessResponse(connection, response_body);
}
else
{
WebControlServer::SendErrorResponse(connection, response_body);
}
}
else if (m[1].str() == "remove_blacklist_user")
{
if (this->RemoveBlacklistUser(response_body, data, proxy))
{
this->SendSuccessResponse(connection, response_body);
}
else
{
WebControlServer::SendErrorResponse(connection, response_body);
}
}
else if (m[1].str() == "set_user_proxy")
{
if (this->SetUserProxy(response_body, data, proxy))
{
this->SendSuccessResponse(connection, response_body);
}
else
{
WebControlServer::SendErrorResponse(connection, response_body);
}
}
else if (m[1].str() == "remove_user_proxy")
{
if (this->RemoveUserProxy(response_body, data, proxy))
{
this->SendSuccessResponse(connection, response_body);
}
else
{
WebControlServer::SendErrorResponse(connection, response_body);
}
}
else if (m[1].str() == "set_max_users")
{
if (this->SetMaxUsers(response_body, data, proxy))
{
this->SendSuccessResponse(connection, response_body);
}
else
{
WebControlServer::SendErrorResponse(connection, response_body);
}
}
else if (m[1].str() == "kick_player")
{
if (this->KickPlayer(response_body, data, proxy))
{
this->SendSuccessResponse(connection, response_body);
}
else
{
WebControlServer::SendErrorResponse(connection, response_body);
}
}
else if (m[1].str() == "get_online_number_list")
{
if (this->GetUserNumberList(response_body, data, proxy))
{
this->SendSuccessResponse(connection, response_body);
}
else
{
WebControlServer::SendErrorResponse(connection, response_body);
}
}
else if (m[1].str() == "set_motd")
{
if (this->SetMotd(response_body, data, proxy))
{
this->SendSuccessResponse(connection, response_body);
}
else
{
WebControlServer::SendErrorResponse(connection, response_body);
}
}
else
{
WebControlServer::SendErrorResponse(connection, 404, "Unknown API endpoint");
}
}
}
}
else
{
WebControlServer::SendErrorResponse(connection, 404, "Unknown API endpoint");
}
return 0;
});
this->server.SetOptionsHandle([this](const RbsLib::Network::TCP::TCPConnection& connection, RbsLib::Network::HTTP::RequestHeader& header) -> int {
//处理OPTIONS请求,主要处理CORS预检请求
RbsLib::Network::HTTP::ResponseHeader response;
response.status = 204; // No Content
response.headers.AddHeader("Access-Control-Allow-Origin", "*");
response.headers.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.headers.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorize");
response.headers.AddHeader("Access-Control-Max-Age", "86400"); // 24 hours
connection.Send(response.ToBuffer());
return 0;
});
std::thread([this]() {
try
{
this->server.LoopWait(true, 3);
}
catch (const std::exception& e)
{
}
}).detach();
std::thread([this, &proxy_client]() {
try
{
asio::co_spawn(this->io_context, this->TimeTaskUsers(proxy_client), asio::detached);
this->io_context.run();
}
catch (const std::exception& e)
{
}
}).detach();
}
void WebControlServer::Stop(void)
{
this->is_request_stop = true;
this->server.StopAndThrowExceptionInLoopThread();
this->io_context.stop();
}