-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
298 lines (250 loc) · 11.2 KB
/
Copy pathapi.php
File metadata and controls
298 lines (250 loc) · 11.2 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
<?php
/**
* Mikhmon REST API
* Untuk integrasi sistem pembelian voucher otomatis.
*/
// Format output selalu JSON
header('Content-Type: application/json');
// Mematikan tampilan error mentah, diganti dengan respons JSON terstruktur
error_reporting(0);
ini_set('display_errors', 0);
// Rate Limiting (Maksimum 30 request per menit per IP)
$ipAddress = isset($_SERVER['HTTP_CLIENT_IP'])
? $_SERVER['HTTP_CLIENT_IP']
: (isset($_SERVER['HTTP_X_FORWARDED_FOR'])
? explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]
: $_SERVER['REMOTE_ADDR']);
$rateLimitFile = __DIR__ . '/data/rate_limit.json';
$limit = 30; // request
$period = 60; // seconds
$allowed = true;
$remaining = $limit;
$now = time();
if (file_exists($rateLimitFile) || is_writable(dirname($rateLimitFile))) {
$fp = fopen($rateLimitFile, 'c+');
if ($fp) {
if (flock($fp, LOCK_EX)) {
$size = @filesize($rateLimitFile);
$data = $size > 0 ? json_decode(fread($fp, $size), true) : [];
if (!is_array($data)) $data = [];
// Clean up expired records
foreach ($data as $ip => $record) {
if (isset($record['reset_time']) && $record['reset_time'] < $now) {
unset($data[$ip]);
}
}
if (isset($data[$ipAddress])) {
$record = $data[$ipAddress];
if (isset($record['reset_time']) && $record['reset_time'] > $now) {
if (isset($record['count']) && $record['count'] >= $limit) {
$allowed = false;
} else {
$data[$ipAddress]['count'] = isset($data[$ipAddress]['count']) ? $data[$ipAddress]['count'] + 1 : 1;
}
$remaining = max(0, $limit - $data[$ipAddress]['count']);
} else {
$data[$ipAddress] = [
'count' => 1,
'reset_time' => $now + $period
];
$remaining = $limit - 1;
}
} else {
$data[$ipAddress] = [
'count' => 1,
'reset_time' => $now + $period
];
$remaining = $limit - 1;
}
ftruncate($fp, 0);
rewind($fp);
fwrite($fp, json_encode($data));
fflush($fp);
}
flock($fp, LOCK_UN);
fclose($fp);
}
}
if (!$allowed) {
http_response_code(429);
echo json_encode(['status' => 'error', 'message' => 'Too Many Requests. Rate limit exceeded. Try again later.']);
exit;
}
// Add Rate Limit headers
header('X-RateLimit-Limit: ' . $limit);
header('X-RateLimit-Remaining: ' . $remaining);
// Load Config Utama
if (!file_exists(__DIR__ . '/include/config.php')) {
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Configuration file config.php not found.']);
exit;
}
include_once(__DIR__ . '/include/config.php');
// Verifikasi API Key
$headers = getallheaders();
$apiKey = isset($headers['X-API-Key']) ? $headers['X-API-Key'] : (isset($_REQUEST['api_key']) ? $_REQUEST['api_key'] : '');
if (empty($mikhmon_api_key) || $apiKey !== $mikhmon_api_key) {
http_response_code(401);
echo json_encode(['status' => 'error', 'message' => 'Unauthorized. Invalid or missing API Key.']);
exit;
}
// Validasi Parameter Router Session
$session = isset($_REQUEST['session']) ? $_REQUEST['session'] : '';
if (empty($session) || !isset($data[$session])) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid or missing router session name.']);
exit;
}
// Load routeros_api.class.php dan dependencies
include_once(__DIR__ . '/lib/routeros_api.class.php');
include_once(__DIR__ . '/lib/formatbytesbites.php');
// Parse data koneksi router dari data session
$iphost = explode('!', $data[$session][1])[1];
$userhost = explode('@|@', $data[$session][2])[1];
$passwdhost = explode('#|#', $data[$session][3])[1];
$currency = explode('&', $data[$session][6])[1];
$API = new RouterosAPI();
$API->debug = false;
// Konek ke MikroTik
if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
http_response_code(503);
echo json_encode(['status' => 'error', 'message' => 'Failed to connect to MikroTik router. Check router status and API configuration.']);
exit;
}
// Handle Aksi
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
switch ($action) {
case 'profiles':
// Menampilkan daftar paket/profil hotspot
$profiles = $API->comm("/ip/hotspot/user/profile/print");
$resultList = [];
foreach ($profiles as $prof) {
if ($prof['name'] === 'default') continue;
$onLogin = isset($prof['on-login']) ? $prof['on-login'] : '';
$exploded = explode(',', $onLogin);
$price = isset($exploded[2]) ? (float)$exploded[2] : 0;
$validity = isset($exploded[3]) ? $exploded[3] : '';
$resultList[] = [
'name' => $prof['name'],
'shared_users' => isset($prof['shared-users']) ? $prof['shared-users'] : '',
'rate_limit' => isset($prof['rate-limit']) ? $prof['rate-limit'] : 'Unlimited',
'price' => $price,
'validity' => $validity,
'currency' => $currency
];
}
echo json_encode(['status' => 'success', 'data' => $resultList]);
break;
case 'generate':
// Generate voucher baru
$profileName = isset($_REQUEST['profile']) ? $_REQUEST['profile'] : '';
if (empty($profileName)) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Profile name is required.']);
exit;
}
// Ambil info profil untuk mendapatkan validitas dan harga
$getProfile = $API->comm("/ip/hotspot/user/profile/print", [
"?name" => $profileName
]);
if (empty($getProfile)) {
http_response_code(404);
echo json_encode(['status' => 'error', 'message' => 'Profile not found on router.']);
exit;
}
$onLogin = isset($getProfile[0]['on-login']) ? $getProfile[0]['on-login'] : '';
$exploded = explode(',', $onLogin);
$price = isset($exploded[2]) ? (float)$exploded[2] : 0;
$validity = isset($exploded[3]) ? $exploded[3] : '';
// Parameter Kustom Pembuatan Voucher
$qty = isset($_REQUEST['qty']) ? (int)$_REQUEST['qty'] : 1;
$qty = ($qty > 100) ? 100 : (($qty < 1) ? 1 : $qty); // Batasan qty 1-100 per request
$userMode = isset($_REQUEST['user_mode']) ? $_REQUEST['user_mode'] : 'vc'; // vc (user=pass) atau up (user & pass)
$userLength = isset($_REQUEST['user_length']) ? (int)$_REQUEST['user_length'] : 5;
$userLength = ($userLength < 3 || $userLength > 12) ? 5 : $userLength;
$charSet = isset($_REQUEST['char_set']) ? $_REQUEST['char_set'] : 'mix'; // mix, lower, upper, num, mix1, mix2
$prefix = isset($_REQUEST['prefix']) ? preg_replace('/[^a-zA-Z0-9]/', '', $_REQUEST['prefix']) : '';
$commentInput = isset($_REQUEST['comment']) ? $_REQUEST['comment'] : 'API Auto';
$timelimit = isset($_REQUEST['timelimit']) ? $_REQUEST['timelimit'] : '';
$datalimit = isset($_REQUEST['datalimit']) ? (float)$_REQUEST['datalimit'] : 0; // dalam bytes
$server = isset($_REQUEST['server']) ? $_REQUEST['server'] : 'all';
// Set Comment Format
$comment = "API-" . rand(100, 999) . "-" . date("m.d.y") . "-" . $commentInput;
$generatedVouchers = [];
// Loop pembuatan voucher
for ($i = 0; $i < $qty; $i++) {
$username = '';
$password = '';
// Generate Username & Password berdasarkan charSet
if ($userMode === 'up') {
// User & Password terpisah
switch ($charSet) {
case 'lower': $username = randLC($userLength); break;
case 'upper': $username = randUC($userLength); break;
case 'upplow': $username = randULC($userLength); break;
case 'mix1': $username = randNUC($userLength); break;
case 'mix2': $username = randNULC($userLength); break;
case 'num': $username = randN($userLength); break;
case 'mix':
default: $username = randNLC($userLength); break;
}
$password = randN($userLength);
} else {
// User = Password
$shuf = $userLength;
if ($charSet !== 'num' && $charSet !== 'mix' && $charSet !== 'mix1' && $charSet !== 'mix2') {
$a = ["1" => "", "", 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6];
$shuf = $userLength - (isset($a[$userLength]) ? (int)$a[$userLength] : 2);
}
switch ($charSet) {
case 'lower': $username = randLC($shuf) . randN($userLength - $shuf); break;
case 'upper': $username = randUC($shuf) . randN($userLength - $shuf); break;
case 'upplow': $username = randULC($shuf) . randN($userLength - $shuf); break;
case 'num': $username = randN($userLength); break;
case 'mix1': $username = randNUC($userLength); break;
case 'mix2': $username = randNULC($userLength); break;
case 'mix':
default: $username = randNLC($userLength); break;
}
$password = $username;
}
$username = $prefix . $username;
// Parameter tambah user ke RouterOS
$addParams = [
"server" => $server,
"name" => $username,
"password" => $password,
"profile" => $profileName,
"comment" => $comment
];
if (!empty($timelimit)) {
$addParams["limit-uptime"] = $timelimit;
}
if ($datalimit > 0) {
$addParams["limit-bytes-total"] = (string)$datalimit;
}
// Daftarkan ke MikroTik
$API->comm("/ip/hotspot/user/add", $addParams);
$generatedVouchers[] = [
'username' => $username,
'password' => $password,
'profile' => $profileName,
'price' => $price,
'validity' => $validity,
'timelimit' => $timelimit ? $timelimit : 'Unlimited',
'datalimit' => $datalimit ? formatBytes($datalimit, 2) : 'Unlimited',
'comment' => $comment
];
}
echo json_encode([
'status' => 'success',
'message' => "Successfully generated $qty voucher(s).",
'data' => $generatedVouchers
]);
break;
default:
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid action. Supported actions: profiles, generate.']);
break;
}
$API->disconnect();