Niansuh commited on
Commit
8db0f37
1 Parent(s): 270d0fb

Create app.js

Browse files
Files changed (1) hide show
  1. app.js +280 -0
app.js ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // app.js
2
+
3
+ const express = require('express');
4
+ const bodyParser = require('body-parser');
5
+ const axios = require('axios');
6
+ const path = require('path');
7
+ const mysql = require('mysql2');
8
+ const morgan = require('morgan'); // For logging HTTP requests
9
+ const helmet = require('helmet'); // For securing HTTP headers
10
+ const { body, validationResult } = require('express-validator'); // For input validation
11
+ require('dotenv').config(); // For environment variables
12
+
13
+ const app = express();
14
+ const port = process.env.PORT || 3000;
15
+
16
+ // Middleware Setup
17
+ app.use(bodyParser.urlencoded({ extended: true }));
18
+ app.use(bodyParser.json());
19
+ app.use(helmet());
20
+ app.use(morgan('combined'));
21
+ app.use(express.static('public')); // Serve static files from 'public' directory
22
+
23
+ // Database Connection Configuration with Connection Pooling
24
+ const pool = mysql.createPool({
25
+ host: process.env.DB_HOST,
26
+ port: process.env.DB_PORT || 3306,
27
+ user: process.env.DB_USER,
28
+ password: process.env.DB_PASSWORD,
29
+ database: process.env.DB_NAME,
30
+ waitForConnections: true,
31
+ connectionLimit: 10, // Adjust based on your requirements
32
+ queueLimit: 0
33
+ });
34
+
35
+ // Promisify for async/await usage
36
+ const promisePool = pool.promise();
37
+
38
+ // Function to Initialize Database Tables
39
+ async function initializeDatabase() {
40
+ try {
41
+ // Create redemption_codes Table
42
+ const createRedemptionCodesTable = `
43
+ CREATE TABLE IF NOT EXISTS redemption_codes (
44
+ id INT AUTO_INCREMENT PRIMARY KEY,
45
+ code TEXT NOT NULL,
46
+ name VARCHAR(255),
47
+ quota INT,
48
+ count INT,
49
+ user_ip VARCHAR(45),
50
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
51
+ )
52
+ `;
53
+
54
+ await promisePool.query(createRedemptionCodesTable);
55
+ console.log('Redemption codes table is ready.');
56
+
57
+ // Create session_cookies Table
58
+ const createSessionCookiesTable = `
59
+ CREATE TABLE IF NOT EXISTS session_cookies (
60
+ id INT AUTO_INCREMENT PRIMARY KEY,
61
+ username VARCHAR(255) NOT NULL,
62
+ session_cookies TEXT NOT NULL,
63
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
64
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
65
+ )
66
+ `;
67
+
68
+ await promisePool.query(createSessionCookiesTable);
69
+ console.log('Session_cookies table is ready.');
70
+ } catch (err) {
71
+ console.error('Error initializing database tables:', err);
72
+ process.exit(1);
73
+ }
74
+ }
75
+
76
+ // Initialize Database Tables
77
+ initializeDatabase();
78
+
79
+ // Serve the HTML Form (Assuming you have an index.html in the 'views' directory)
80
+ app.get('/', (req, res) => {
81
+ res.sendFile(path.join(__dirname, 'views', 'index.html'));
82
+ });
83
+
84
+ // Utility Function to Get User's IP Address
85
+ function getUserIP(req) {
86
+ const xForwardedFor = req.headers['x-forwarded-for'];
87
+ if (xForwardedFor) {
88
+ const ips = xForwardedFor.split(',').map(ip => ip.trim());
89
+ return ips[0];
90
+ }
91
+ return req.socket.remoteAddress;
92
+ }
93
+
94
+ // Function to Save Session Cookies to the Database
95
+ async function saveSessionCookies(username, sessionCookies) {
96
+ try {
97
+ const insertQuery = `
98
+ INSERT INTO session_cookies (username, session_cookies)
99
+ VALUES (?, ?)
100
+ `;
101
+
102
+ await promisePool.query(insertQuery, [username, sessionCookies]);
103
+ console.log(`New session cookies for user '${username}' saved successfully.`);
104
+ } catch (err) {
105
+ console.error(`Error saving session cookies for user '${username}':`, err);
106
+ throw err;
107
+ }
108
+ }
109
+
110
+ // Function to Perform Login and Retrieve Session Cookies
111
+ async function performLogin() {
112
+ const loginUrl = `${process.env.REDEMPTION_API_BASE_URL}/api/user/login?turnstile=`;
113
+
114
+ const headers = {
115
+ 'Accept': 'application/json, text/plain, */*',
116
+ 'Accept-Language': 'en-US,en;q=0.9',
117
+ 'Connection': 'keep-alive',
118
+ 'Content-Type': 'application/json',
119
+ 'Origin': process.env.REDEMPTION_API_BASE_URL,
120
+ 'Referer': `${process.env.REDEMPTION_API_BASE_URL}/login`,
121
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
122
+ 'VoApi-User': '-1'
123
+ };
124
+
125
+ const data = {
126
+ username: process.env.ADMIN_USERNAME,
127
+ password: process.env.ADMIN_PASSWORD
128
+ };
129
+
130
+ try {
131
+ const response = await axios.post(loginUrl, data, {
132
+ headers: headers,
133
+ withCredentials: true,
134
+ httpsAgent: new (require('https').Agent)({ rejectUnauthorized: false }) // Equivalent to --insecure
135
+ });
136
+
137
+ // Extract all cookies from response headers
138
+ const setCookieHeader = response.headers['set-cookie'];
139
+ if (setCookieHeader) {
140
+ // Parse the set-cookie header to extract all cookies
141
+ const cookies = setCookieHeader.map(cookie => cookie.split(';')[0]);
142
+ const cookieString = cookies.join('; '); // Join all cookies into a single string
143
+
144
+ if (cookieString) {
145
+ console.log('Session cookies obtained from login.');
146
+ return cookieString;
147
+ }
148
+ }
149
+
150
+ throw new Error('No session cookies received from login response.');
151
+ } catch (error) {
152
+ if (error.response) {
153
+ throw new Error(`Login API Error: ${JSON.stringify(error.response.data)}`);
154
+ } else if (error.request) {
155
+ throw new Error('Login API Error: No response received from the login service.');
156
+ } else {
157
+ throw new Error(`Login Error: ${error.message}`);
158
+ }
159
+ }
160
+ }
161
+
162
+ // Function to Generate Redemption Code
163
+ async function generateRedemptionCode(name, quota, count, sessionCookies) {
164
+ console.log(`Using session cookies: ${sessionCookies}`); // Log the cookies being used
165
+
166
+ const url = `${process.env.REDEMPTION_API_BASE_URL}/api/redemption/`;
167
+
168
+ const headers = {
169
+ 'Accept': 'application/json, text/plain, */*',
170
+ 'Accept-Language': 'en-US,en;q=0.9',
171
+ 'Connection': 'keep-alive',
172
+ 'Content-Type': 'application/json',
173
+ 'Origin': process.env.REDEMPTION_API_BASE_URL,
174
+ 'Referer': `${process.env.REDEMPTION_API_BASE_URL}/redemption`,
175
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
176
+ 'VoApi-User': '1',
177
+ 'Cookie': sessionCookies // Use all stored cookies
178
+ };
179
+
180
+ const data = {
181
+ name: name,
182
+ quota: parseInt(quota),
183
+ count: parseInt(count)
184
+ };
185
+
186
+ try {
187
+ const response = await axios.post(url, data, {
188
+ headers: headers,
189
+ httpsAgent: new (require('https').Agent)({ rejectUnauthorized: false }) // Equivalent to --insecure
190
+ });
191
+
192
+ console.log('Redemption code generated successfully.');
193
+ return response.data;
194
+ } catch (error) {
195
+ if (error.response) {
196
+ throw new Error(`API Error: ${JSON.stringify(error.response.data)}`);
197
+ } else if (error.request) {
198
+ throw new Error('API Error: No response received from the redemption service.');
199
+ } else {
200
+ throw new Error(`Error: ${error.message}`);
201
+ }
202
+ }
203
+ }
204
+
205
+ // Function to Save Redemption Code to the Database
206
+ async function saveRedemptionCode(codeData, name, quota, count, userIP) {
207
+ try {
208
+ // Assuming the API returns the code in codeData.code
209
+ const code = codeData.code || JSON.stringify(codeData);
210
+
211
+ const insertQuery = `
212
+ INSERT INTO redemption_codes (code, name, quota, count, user_ip)
213
+ VALUES (?, ?, ?, ?, ?)
214
+ `;
215
+
216
+ await promisePool.query(insertQuery, [code, name, quota, count, userIP]);
217
+ console.log('Redemption code saved to database.');
218
+ } catch (err) {
219
+ console.error('Error saving redemption code to database:', err);
220
+ throw err;
221
+ }
222
+ }
223
+
224
+ // Route: POST /api/create
225
+ app.post('/api/create', [
226
+ body('username').isString().trim().notEmpty(),
227
+ body('name').isString().trim().notEmpty(),
228
+ body('quota').isInt({ min: 1 }),
229
+ body('count').isInt({ min: 1 })
230
+ ], async (req, res) => {
231
+ // Validate Input
232
+ const errors = validationResult(req);
233
+ if (!errors.isEmpty()) {
234
+ return res.status(400).json({ success: false, errors: errors.array() });
235
+ }
236
+
237
+ const { username, name, quota, count } = req.body;
238
+ const userIP = getUserIP(req);
239
+ const apiKey = req.headers['x-api-key'];
240
+
241
+ // Check API Key
242
+ if (apiKey !== process.env.API_KEY) {
243
+ return res.status(401).json({
244
+ success: false,
245
+ error: 'Unauthorized: Invalid API key'
246
+ });
247
+ }
248
+
249
+ try {
250
+ // Perform Login to Obtain New Session Cookies
251
+ console.log('Performing login to obtain new session cookies...');
252
+ const sessionCookies = await performLogin();
253
+
254
+ // Save the New Session Cookies to the Database
255
+ await saveSessionCookies(username, sessionCookies);
256
+ console.log('New session cookies saved to the database.');
257
+
258
+ // Generate Redemption Code Using the New Session Cookies
259
+ const redemptionCode = await generateRedemptionCode(name, quota, count, sessionCookies);
260
+
261
+ // Save Redemption Code to Database
262
+ await saveRedemptionCode(redemptionCode, name, quota, count, userIP);
263
+
264
+ res.json({
265
+ success: true,
266
+ data: redemptionCode
267
+ });
268
+ } catch (error) {
269
+ console.error('Error:', error.message);
270
+ res.status(500).json({
271
+ success: false,
272
+ error: error.message
273
+ });
274
+ }
275
+ });
276
+
277
+ // Start the Server
278
+ app.listen(port, () => {
279
+ console.log(`App is running at http://localhost:${port}`);
280
+ });