veltrixcode commited on
Commit
056db93
·
verified ·
1 Parent(s): 4fc446e

Upload 8 files

Browse files
Files changed (5) hide show
  1. db.js +6 -123
  2. mongo.js +31 -0
  3. package-lock.json +381 -1
  4. package.json +1 -0
  5. server.js +172 -321
db.js CHANGED
@@ -1,127 +1,10 @@
1
- const { Pool } = require('pg');
2
 
3
- // Database connection configuration
4
- const mainDbConfig = {
5
- connectionString: 'postgresql://gc_owner:npg_Lh9UmqVT7nGb@ep-wandering-flower-a1b4axgc-pooler.ap-southeast-1.aws.neon.tech/gc?sslmode=require'
6
- };
7
-
8
- let mainPool = null;
9
-
10
- function getPool() {
11
- if (!mainPool) {
12
- mainPool = new Pool(mainDbConfig);
13
- }
14
- return mainPool;
15
- }
16
-
17
- async function initializeDatabase() {
18
- const pool = getPool();
19
- try {
20
- // Drop tables in correct order to handle foreign key constraints
21
- //await pool.query('DROP TABLE IF EXISTS messages CASCADE');
22
- //await pool.query('DROP TABLE IF EXISTS submissions CASCADE');
23
- //await pool.query('DROP TABLE IF EXISTS otps CASCADE');
24
- //await pool.query('DROP TABLE IF EXISTS users CASCADE');
25
-
26
- // Create users table
27
- await pool.query(`
28
- CREATE TABLE IF NOT EXISTS users (
29
- id SERIAL PRIMARY KEY,
30
- name VARCHAR(255) NOT NULL,
31
- email VARCHAR(255) UNIQUE NOT NULL,
32
- password VARCHAR(255) NOT NULL,
33
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
34
- )
35
- `);
36
-
37
- // Create OTP table
38
- await pool.query(`
39
- CREATE TABLE IF NOT EXISTS otps (
40
- id SERIAL PRIMARY KEY,
41
- email VARCHAR(255) NOT NULL,
42
- otp VARCHAR(6) NOT NULL,
43
- type VARCHAR(20) NOT NULL,
44
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
45
- expires_at TIMESTAMP NOT NULL,
46
- verified BOOLEAN DEFAULT FALSE,
47
- is_used BOOLEAN DEFAULT FALSE
48
- )
49
- `);
50
-
51
- // Create submissions table
52
- await pool.query(`
53
- CREATE TABLE IF NOT EXISTS submissions (
54
- id SERIAL PRIMARY KEY,
55
- user_id INTEGER REFERENCES users(id),
56
- ticket_user_name VARCHAR(255) NOT NULL,
57
- gc_code VARCHAR(255) NOT NULL,
58
- gc_phone VARCHAR(255) NOT NULL,
59
- ticket_number VARCHAR(255) NOT NULL,
60
- payment_address VARCHAR(255) NOT NULL,
61
- amount DECIMAL(10,2) NOT NULL,
62
- proof_video_url TEXT NOT NULL,
63
- status VARCHAR(50) NOT NULL DEFAULT 'pending',
64
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
65
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
66
- )
67
- `);
68
-
69
- // Add status constraint
70
- await pool.query(`
71
- ALTER TABLE submissions
72
- DROP CONSTRAINT IF EXISTS submissions_status_check;
73
-
74
- ALTER TABLE submissions
75
- ADD CONSTRAINT submissions_status_check
76
- CHECK (status IN ('pending', 'approved', 'rejected', 'paid', 'closed'));
77
- `);
78
-
79
- // Create messages table
80
- await pool.query(`
81
- CREATE TABLE IF NOT EXISTS messages (
82
- id SERIAL PRIMARY KEY,
83
- user_id INTEGER REFERENCES users(id),
84
- content TEXT NOT NULL,
85
- sender VARCHAR(50) NOT NULL,
86
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
87
- )
88
- `);
89
-
90
- // Migration: Rename upi_id to payment_address if needed
91
- await pool.query(`
92
- DO $$
93
- BEGIN
94
- IF EXISTS (
95
- SELECT 1 FROM information_schema.columns
96
- WHERE table_name='submissions' AND column_name='upi_id'
97
- ) THEN
98
- EXECUTE 'ALTER TABLE submissions RENAME COLUMN upi_id TO payment_address';
99
- END IF;
100
- END
101
- $$;
102
- `);
103
-
104
- console.log('Database tables initialized successfully');
105
- } catch (error) {
106
- console.error('Error initializing database:', error);
107
- throw error;
108
- }
109
- }
110
-
111
- async function closePool() {
112
- if (mainPool) {
113
- await mainPool.end();
114
- mainPool = null;
115
- }
116
  }
117
 
118
  module.exports = {
119
- getPool,
120
- initializeDatabase,
121
- closePool
122
- };
123
-
124
- // If this file is run directly, initialize the database
125
- if (require.main === module) {
126
- initializeDatabase();
127
- }
 
1
+ const { connectToMongo } = require('./mongo');
2
 
3
+ // Returns the MongoDB database instance
4
+ async function getDb() {
5
+ return await connectToMongo();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  }
7
 
8
  module.exports = {
9
+ getDb
10
+ };
 
 
 
 
 
 
 
mongo.js ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { MongoClient, ServerApiVersion } = require('mongodb');
2
+
3
+ const uri = "mongodb+srv://bob17040246:shashwat1234@cluster0.u1ox3.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";
4
+ const dbName = 'GCX';
5
+
6
+ const client = new MongoClient(uri, {
7
+ serverApi: {
8
+ version: ServerApiVersion.v1,
9
+ strict: true,
10
+ deprecationErrors: true,
11
+ }
12
+ });
13
+
14
+ let db;
15
+
16
+ async function connectToMongo() {
17
+ if (!db) {
18
+ try {
19
+ console.log("Attempting to connect to MongoDB Atlas...");
20
+ await client.connect();
21
+ db = client.db(dbName);
22
+ console.log("Connected to MongoDB Atlas!");
23
+ } catch (err) {
24
+ console.error("Failed to connect to MongoDB Atlas:", err);
25
+ throw err;
26
+ }
27
+ }
28
+ return db;
29
+ }
30
+
31
+ module.exports = { connectToMongo };
package-lock.json CHANGED
@@ -19,10 +19,12 @@
19
  "express": "^4.18.2",
20
  "helmet": "^7.0.0",
21
  "jsonwebtoken": "^9.0.2",
 
22
  "morgan": "^1.10.0",
23
  "multer": "^1.4.5-lts.1",
24
  "nodemailer": "^6.9.5",
25
- "pg": "^8.16.0"
 
26
  },
27
  "devDependencies": {
28
  "nodemon": "^3.0.1"
@@ -31,6 +33,54 @@
31
  "node": ">=14.0.0"
32
  }
33
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  "node_modules/accepts": {
35
  "version": "1.3.8",
36
  "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
@@ -160,6 +210,15 @@
160
  ],
161
  "license": "MIT"
162
  },
 
 
 
 
 
 
 
 
 
163
  "node_modules/basic-auth": {
164
  "version": "2.0.1",
165
  "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz",
@@ -259,6 +318,15 @@
259
  "node": ">=8"
260
  }
261
  },
 
 
 
 
 
 
 
 
 
262
  "node_modules/buffer": {
263
  "version": "4.9.2",
264
  "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.2.tgz",
@@ -591,6 +659,67 @@
591
  "node": ">= 0.8"
592
  }
593
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594
  "node_modules/es-define-property": {
595
  "version": "1.0.1",
596
  "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
@@ -1267,6 +1396,12 @@
1267
  "node": ">= 0.6"
1268
  }
1269
  },
 
 
 
 
 
 
1270
  "node_modules/merge-descriptors": {
1271
  "version": "1.0.3",
1272
  "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
@@ -1340,6 +1475,62 @@
1340
  "url": "https://github.com/sponsors/ljharb"
1341
  }
1342
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1343
  "node_modules/morgan": {
1344
  "version": "1.10.0",
1345
  "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz",
@@ -2081,6 +2272,125 @@
2081
  "node": ">=10"
2082
  }
2083
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2084
  "node_modules/split2": {
2085
  "version": "4.2.0",
2086
  "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
@@ -2152,6 +2462,27 @@
2152
  "nodetouch": "bin/nodetouch.js"
2153
  }
2154
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2155
  "node_modules/type-is": {
2156
  "version": "1.6.18",
2157
  "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
@@ -2178,6 +2509,12 @@
2178
  "dev": true,
2179
  "license": "MIT"
2180
  },
 
 
 
 
 
 
2181
  "node_modules/unpipe": {
2182
  "version": "1.0.0",
2183
  "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
@@ -2234,6 +2571,28 @@
2234
  "node": ">= 0.8"
2235
  }
2236
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2237
  "node_modules/which-typed-array": {
2238
  "version": "1.1.19",
2239
  "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.19.tgz",
@@ -2255,6 +2614,27 @@
2255
  "url": "https://github.com/sponsors/ljharb"
2256
  }
2257
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2258
  "node_modules/xml2js": {
2259
  "version": "0.6.2",
2260
  "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz",
 
19
  "express": "^4.18.2",
20
  "helmet": "^7.0.0",
21
  "jsonwebtoken": "^9.0.2",
22
+ "mongodb": "^6.17.0",
23
  "morgan": "^1.10.0",
24
  "multer": "^1.4.5-lts.1",
25
  "nodemailer": "^6.9.5",
26
+ "pg": "^8.16.0",
27
+ "socket.io": "^4.8.1"
28
  },
29
  "devDependencies": {
30
  "nodemon": "^3.0.1"
 
33
  "node": ">=14.0.0"
34
  }
35
  },
36
+ "node_modules/@mongodb-js/saslprep": {
37
+ "version": "1.3.0",
38
+ "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.3.0.tgz",
39
+ "integrity": "sha512-zlayKCsIjYb7/IdfqxorK5+xUMyi4vOKcFy10wKJYc63NSdKI8mNME+uJqfatkPmOSMMUiojrL58IePKBm3gvQ==",
40
+ "license": "MIT",
41
+ "dependencies": {
42
+ "sparse-bitfield": "^3.0.3"
43
+ }
44
+ },
45
+ "node_modules/@socket.io/component-emitter": {
46
+ "version": "3.1.2",
47
+ "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
48
+ "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
49
+ "license": "MIT"
50
+ },
51
+ "node_modules/@types/cors": {
52
+ "version": "2.8.19",
53
+ "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz",
54
+ "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==",
55
+ "license": "MIT",
56
+ "dependencies": {
57
+ "@types/node": "*"
58
+ }
59
+ },
60
+ "node_modules/@types/node": {
61
+ "version": "24.0.13",
62
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.0.13.tgz",
63
+ "integrity": "sha512-Qm9OYVOFHFYg3wJoTSrz80hoec5Lia/dPp84do3X7dZvLikQvM1YpmvTBEdIr/e+U8HTkFjLHLnl78K/qjf+jQ==",
64
+ "license": "MIT",
65
+ "dependencies": {
66
+ "undici-types": "~7.8.0"
67
+ }
68
+ },
69
+ "node_modules/@types/webidl-conversions": {
70
+ "version": "7.0.3",
71
+ "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz",
72
+ "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==",
73
+ "license": "MIT"
74
+ },
75
+ "node_modules/@types/whatwg-url": {
76
+ "version": "11.0.5",
77
+ "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz",
78
+ "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==",
79
+ "license": "MIT",
80
+ "dependencies": {
81
+ "@types/webidl-conversions": "*"
82
+ }
83
+ },
84
  "node_modules/accepts": {
85
  "version": "1.3.8",
86
  "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
 
210
  ],
211
  "license": "MIT"
212
  },
213
+ "node_modules/base64id": {
214
+ "version": "2.0.0",
215
+ "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz",
216
+ "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==",
217
+ "license": "MIT",
218
+ "engines": {
219
+ "node": "^4.5.0 || >= 5.9"
220
+ }
221
+ },
222
  "node_modules/basic-auth": {
223
  "version": "2.0.1",
224
  "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz",
 
318
  "node": ">=8"
319
  }
320
  },
321
+ "node_modules/bson": {
322
+ "version": "6.10.4",
323
+ "resolved": "https://registry.npmjs.org/bson/-/bson-6.10.4.tgz",
324
+ "integrity": "sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==",
325
+ "license": "Apache-2.0",
326
+ "engines": {
327
+ "node": ">=16.20.1"
328
+ }
329
+ },
330
  "node_modules/buffer": {
331
  "version": "4.9.2",
332
  "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.2.tgz",
 
659
  "node": ">= 0.8"
660
  }
661
  },
662
+ "node_modules/engine.io": {
663
+ "version": "6.6.4",
664
+ "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.4.tgz",
665
+ "integrity": "sha512-ZCkIjSYNDyGn0R6ewHDtXgns/Zre/NT6Agvq1/WobF7JXgFff4SeDroKiCO3fNJreU9YG429Sc81o4w5ok/W5g==",
666
+ "license": "MIT",
667
+ "dependencies": {
668
+ "@types/cors": "^2.8.12",
669
+ "@types/node": ">=10.0.0",
670
+ "accepts": "~1.3.4",
671
+ "base64id": "2.0.0",
672
+ "cookie": "~0.7.2",
673
+ "cors": "~2.8.5",
674
+ "debug": "~4.3.1",
675
+ "engine.io-parser": "~5.2.1",
676
+ "ws": "~8.17.1"
677
+ },
678
+ "engines": {
679
+ "node": ">=10.2.0"
680
+ }
681
+ },
682
+ "node_modules/engine.io-parser": {
683
+ "version": "5.2.3",
684
+ "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
685
+ "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
686
+ "license": "MIT",
687
+ "engines": {
688
+ "node": ">=10.0.0"
689
+ }
690
+ },
691
+ "node_modules/engine.io/node_modules/cookie": {
692
+ "version": "0.7.2",
693
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
694
+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
695
+ "license": "MIT",
696
+ "engines": {
697
+ "node": ">= 0.6"
698
+ }
699
+ },
700
+ "node_modules/engine.io/node_modules/debug": {
701
+ "version": "4.3.7",
702
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
703
+ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
704
+ "license": "MIT",
705
+ "dependencies": {
706
+ "ms": "^2.1.3"
707
+ },
708
+ "engines": {
709
+ "node": ">=6.0"
710
+ },
711
+ "peerDependenciesMeta": {
712
+ "supports-color": {
713
+ "optional": true
714
+ }
715
+ }
716
+ },
717
+ "node_modules/engine.io/node_modules/ms": {
718
+ "version": "2.1.3",
719
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
720
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
721
+ "license": "MIT"
722
+ },
723
  "node_modules/es-define-property": {
724
  "version": "1.0.1",
725
  "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
 
1396
  "node": ">= 0.6"
1397
  }
1398
  },
1399
+ "node_modules/memory-pager": {
1400
+ "version": "1.5.0",
1401
+ "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz",
1402
+ "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==",
1403
+ "license": "MIT"
1404
+ },
1405
  "node_modules/merge-descriptors": {
1406
  "version": "1.0.3",
1407
  "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
 
1475
  "url": "https://github.com/sponsors/ljharb"
1476
  }
1477
  },
1478
+ "node_modules/mongodb": {
1479
+ "version": "6.17.0",
1480
+ "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.17.0.tgz",
1481
+ "integrity": "sha512-neerUzg/8U26cgruLysKEjJvoNSXhyID3RvzvdcpsIi2COYM3FS3o9nlH7fxFtefTb942dX3W9i37oPfCVj4wA==",
1482
+ "license": "Apache-2.0",
1483
+ "dependencies": {
1484
+ "@mongodb-js/saslprep": "^1.1.9",
1485
+ "bson": "^6.10.4",
1486
+ "mongodb-connection-string-url": "^3.0.0"
1487
+ },
1488
+ "engines": {
1489
+ "node": ">=16.20.1"
1490
+ },
1491
+ "peerDependencies": {
1492
+ "@aws-sdk/credential-providers": "^3.188.0",
1493
+ "@mongodb-js/zstd": "^1.1.0 || ^2.0.0",
1494
+ "gcp-metadata": "^5.2.0",
1495
+ "kerberos": "^2.0.1",
1496
+ "mongodb-client-encryption": ">=6.0.0 <7",
1497
+ "snappy": "^7.2.2",
1498
+ "socks": "^2.7.1"
1499
+ },
1500
+ "peerDependenciesMeta": {
1501
+ "@aws-sdk/credential-providers": {
1502
+ "optional": true
1503
+ },
1504
+ "@mongodb-js/zstd": {
1505
+ "optional": true
1506
+ },
1507
+ "gcp-metadata": {
1508
+ "optional": true
1509
+ },
1510
+ "kerberos": {
1511
+ "optional": true
1512
+ },
1513
+ "mongodb-client-encryption": {
1514
+ "optional": true
1515
+ },
1516
+ "snappy": {
1517
+ "optional": true
1518
+ },
1519
+ "socks": {
1520
+ "optional": true
1521
+ }
1522
+ }
1523
+ },
1524
+ "node_modules/mongodb-connection-string-url": {
1525
+ "version": "3.0.2",
1526
+ "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.2.tgz",
1527
+ "integrity": "sha512-rMO7CGo/9BFwyZABcKAWL8UJwH/Kc2x0g72uhDWzG48URRax5TCIcJ7Rc3RZqffZzO/Gwff/jyKwCU9TN8gehA==",
1528
+ "license": "Apache-2.0",
1529
+ "dependencies": {
1530
+ "@types/whatwg-url": "^11.0.2",
1531
+ "whatwg-url": "^14.1.0 || ^13.0.0"
1532
+ }
1533
+ },
1534
  "node_modules/morgan": {
1535
  "version": "1.10.0",
1536
  "resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz",
 
2272
  "node": ">=10"
2273
  }
2274
  },
2275
+ "node_modules/socket.io": {
2276
+ "version": "4.8.1",
2277
+ "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.1.tgz",
2278
+ "integrity": "sha512-oZ7iUCxph8WYRHHcjBEc9unw3adt5CmSNlppj/5Q4k2RIrhl8Z5yY2Xr4j9zj0+wzVZ0bxmYoGSzKJnRl6A4yg==",
2279
+ "license": "MIT",
2280
+ "dependencies": {
2281
+ "accepts": "~1.3.4",
2282
+ "base64id": "~2.0.0",
2283
+ "cors": "~2.8.5",
2284
+ "debug": "~4.3.2",
2285
+ "engine.io": "~6.6.0",
2286
+ "socket.io-adapter": "~2.5.2",
2287
+ "socket.io-parser": "~4.2.4"
2288
+ },
2289
+ "engines": {
2290
+ "node": ">=10.2.0"
2291
+ }
2292
+ },
2293
+ "node_modules/socket.io-adapter": {
2294
+ "version": "2.5.5",
2295
+ "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.5.tgz",
2296
+ "integrity": "sha512-eLDQas5dzPgOWCk9GuuJC2lBqItuhKI4uxGgo9aIV7MYbk2h9Q6uULEh8WBzThoI7l+qU9Ast9fVUmkqPP9wYg==",
2297
+ "license": "MIT",
2298
+ "dependencies": {
2299
+ "debug": "~4.3.4",
2300
+ "ws": "~8.17.1"
2301
+ }
2302
+ },
2303
+ "node_modules/socket.io-adapter/node_modules/debug": {
2304
+ "version": "4.3.7",
2305
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
2306
+ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
2307
+ "license": "MIT",
2308
+ "dependencies": {
2309
+ "ms": "^2.1.3"
2310
+ },
2311
+ "engines": {
2312
+ "node": ">=6.0"
2313
+ },
2314
+ "peerDependenciesMeta": {
2315
+ "supports-color": {
2316
+ "optional": true
2317
+ }
2318
+ }
2319
+ },
2320
+ "node_modules/socket.io-adapter/node_modules/ms": {
2321
+ "version": "2.1.3",
2322
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
2323
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
2324
+ "license": "MIT"
2325
+ },
2326
+ "node_modules/socket.io-parser": {
2327
+ "version": "4.2.4",
2328
+ "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz",
2329
+ "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==",
2330
+ "license": "MIT",
2331
+ "dependencies": {
2332
+ "@socket.io/component-emitter": "~3.1.0",
2333
+ "debug": "~4.3.1"
2334
+ },
2335
+ "engines": {
2336
+ "node": ">=10.0.0"
2337
+ }
2338
+ },
2339
+ "node_modules/socket.io-parser/node_modules/debug": {
2340
+ "version": "4.3.7",
2341
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
2342
+ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
2343
+ "license": "MIT",
2344
+ "dependencies": {
2345
+ "ms": "^2.1.3"
2346
+ },
2347
+ "engines": {
2348
+ "node": ">=6.0"
2349
+ },
2350
+ "peerDependenciesMeta": {
2351
+ "supports-color": {
2352
+ "optional": true
2353
+ }
2354
+ }
2355
+ },
2356
+ "node_modules/socket.io-parser/node_modules/ms": {
2357
+ "version": "2.1.3",
2358
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
2359
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
2360
+ "license": "MIT"
2361
+ },
2362
+ "node_modules/socket.io/node_modules/debug": {
2363
+ "version": "4.3.7",
2364
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
2365
+ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
2366
+ "license": "MIT",
2367
+ "dependencies": {
2368
+ "ms": "^2.1.3"
2369
+ },
2370
+ "engines": {
2371
+ "node": ">=6.0"
2372
+ },
2373
+ "peerDependenciesMeta": {
2374
+ "supports-color": {
2375
+ "optional": true
2376
+ }
2377
+ }
2378
+ },
2379
+ "node_modules/socket.io/node_modules/ms": {
2380
+ "version": "2.1.3",
2381
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
2382
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
2383
+ "license": "MIT"
2384
+ },
2385
+ "node_modules/sparse-bitfield": {
2386
+ "version": "3.0.3",
2387
+ "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz",
2388
+ "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==",
2389
+ "license": "MIT",
2390
+ "dependencies": {
2391
+ "memory-pager": "^1.0.2"
2392
+ }
2393
+ },
2394
  "node_modules/split2": {
2395
  "version": "4.2.0",
2396
  "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
 
2462
  "nodetouch": "bin/nodetouch.js"
2463
  }
2464
  },
2465
+ "node_modules/tr46": {
2466
+ "version": "5.1.1",
2467
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
2468
+ "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
2469
+ "license": "MIT",
2470
+ "dependencies": {
2471
+ "punycode": "^2.3.1"
2472
+ },
2473
+ "engines": {
2474
+ "node": ">=18"
2475
+ }
2476
+ },
2477
+ "node_modules/tr46/node_modules/punycode": {
2478
+ "version": "2.3.1",
2479
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
2480
+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
2481
+ "license": "MIT",
2482
+ "engines": {
2483
+ "node": ">=6"
2484
+ }
2485
+ },
2486
  "node_modules/type-is": {
2487
  "version": "1.6.18",
2488
  "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
 
2509
  "dev": true,
2510
  "license": "MIT"
2511
  },
2512
+ "node_modules/undici-types": {
2513
+ "version": "7.8.0",
2514
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.8.0.tgz",
2515
+ "integrity": "sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw==",
2516
+ "license": "MIT"
2517
+ },
2518
  "node_modules/unpipe": {
2519
  "version": "1.0.0",
2520
  "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
 
2571
  "node": ">= 0.8"
2572
  }
2573
  },
2574
+ "node_modules/webidl-conversions": {
2575
+ "version": "7.0.0",
2576
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
2577
+ "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
2578
+ "license": "BSD-2-Clause",
2579
+ "engines": {
2580
+ "node": ">=12"
2581
+ }
2582
+ },
2583
+ "node_modules/whatwg-url": {
2584
+ "version": "14.2.0",
2585
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
2586
+ "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
2587
+ "license": "MIT",
2588
+ "dependencies": {
2589
+ "tr46": "^5.1.0",
2590
+ "webidl-conversions": "^7.0.0"
2591
+ },
2592
+ "engines": {
2593
+ "node": ">=18"
2594
+ }
2595
+ },
2596
  "node_modules/which-typed-array": {
2597
  "version": "1.1.19",
2598
  "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.19.tgz",
 
2614
  "url": "https://github.com/sponsors/ljharb"
2615
  }
2616
  },
2617
+ "node_modules/ws": {
2618
+ "version": "8.17.1",
2619
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz",
2620
+ "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==",
2621
+ "license": "MIT",
2622
+ "engines": {
2623
+ "node": ">=10.0.0"
2624
+ },
2625
+ "peerDependencies": {
2626
+ "bufferutil": "^4.0.1",
2627
+ "utf-8-validate": ">=5.0.2"
2628
+ },
2629
+ "peerDependenciesMeta": {
2630
+ "bufferutil": {
2631
+ "optional": true
2632
+ },
2633
+ "utf-8-validate": {
2634
+ "optional": true
2635
+ }
2636
+ }
2637
+ },
2638
  "node_modules/xml2js": {
2639
  "version": "0.6.2",
2640
  "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz",
package.json CHANGED
@@ -28,6 +28,7 @@
28
  "express": "^4.18.2",
29
  "helmet": "^7.0.0",
30
  "jsonwebtoken": "^9.0.2",
 
31
  "morgan": "^1.10.0",
32
  "multer": "^1.4.5-lts.1",
33
  "nodemailer": "^6.9.5",
 
28
  "express": "^4.18.2",
29
  "helmet": "^7.0.0",
30
  "jsonwebtoken": "^9.0.2",
31
+ "mongodb": "^6.17.0",
32
  "morgan": "^1.10.0",
33
  "multer": "^1.4.5-lts.1",
34
  "nodemailer": "^6.9.5",
server.js CHANGED
@@ -1,10 +1,9 @@
1
- require('dotenv').config();
2
  const express = require('express');
3
  const cors = require('cors');
4
  const path = require('path');
5
  const bcrypt = require('bcrypt');
6
  const multer = require('multer');
7
- const { getPool, initializeDatabase, closePool } = require('./db');
8
  const otpService = require('./otpService');
9
  const axios = require('axios');
10
  const http = require('http');
@@ -19,28 +18,7 @@ const io = socketIo(server, {
19
  methods: ["GET", "POST"]
20
  }
21
  });
22
- const port = process.env.PORT || 3000;
23
-
24
- // Initialize database and start server
25
- (async () => {
26
- try {
27
- await initializeDatabase();
28
- console.log('Database initialized successfully.');
29
-
30
- // Test database connection
31
- const pool = getPool();
32
- const client = await pool.connect();
33
- client.release();
34
- console.log('Connected to main database');
35
-
36
- server.listen(port, () => {
37
- console.log(`Server running on port ${port}`);
38
- });
39
- } catch (err) {
40
- console.error('Failed to initialize database or start server:', err);
41
- process.exit(1);
42
- }
43
- })();
44
 
45
  // Middleware
46
  app.use(cors());
@@ -130,7 +108,7 @@ function log(level, message, details = {}) {
130
  console.log(`[${level.toUpperCase()}] ${message}`, details);
131
  }
132
 
133
- // OTP Authentication middleware
134
  const requireOtpAuth = async (req, res, next) => {
135
  const otp = req.headers['x-otp-token'];
136
  const email = req.headers['x-user-email'];
@@ -140,16 +118,16 @@ const requireOtpAuth = async (req, res, next) => {
140
  }
141
 
142
  try {
143
- const pool = getPool();
144
- const result = await pool.query(
145
- 'SELECT * FROM otps WHERE email = $1 AND otp = $2 AND verified = true AND expires_at > NOW()',
146
- [email, otp]
147
- );
148
-
149
- if (result.rows.length === 0) {
 
150
  return res.status(401).json({ error: 'Invalid or expired OTP' });
151
  }
152
-
153
  req.user = { email };
154
  next();
155
  } catch (err) {
@@ -158,46 +136,29 @@ const requireOtpAuth = async (req, res, next) => {
158
  }
159
  };
160
 
161
- // Admin OTP Authentication middleware
162
  const requireAdminOtpAuth = async (req, res, next) => {
163
  try {
164
  const otp = req.headers['x-otp-token'];
165
  const email = req.headers['x-user-email'];
166
-
167
  if (!otp || !email) {
168
- return res.status(401).json({
169
- success: false,
170
- error: 'Missing authentication headers'
171
- });
172
  }
173
-
174
- const pool = getPool();
175
- // Verify OTP
176
- const result = await pool.query(
177
- 'SELECT * FROM otps WHERE email = $1 AND otp = $2 AND is_used = false AND expires_at > NOW()',
178
- [email, otp]
179
- );
180
-
181
- if (result.rows.length === 0) {
182
- return res.status(401).json({
183
- success: false,
184
- error: 'Invalid or expired OTP'
185
- });
186
  }
187
-
188
- // Mark OTP as used
189
- await pool.query(
190
- 'UPDATE otps SET is_used = true WHERE email = $1 AND otp = $2',
191
- [email, otp]
192
- );
193
-
194
  next();
195
  } catch (error) {
196
  console.error('Admin auth error:', error);
197
- res.status(500).json({
198
- success: false,
199
- error: 'Authentication error'
200
- });
201
  }
202
  };
203
 
@@ -304,185 +265,103 @@ app.post('/api/verify-otp', async (req, res) => {
304
  }
305
  });
306
 
307
- // Register new user
308
  app.post('/api/register', async (req, res) => {
309
  const { name, email, password } = req.body;
310
-
311
  if (!name || !email || !password) {
312
- return res.status(400).json({
313
- success: false,
314
- error: 'Name, email and password are required'
315
- });
316
  }
317
-
318
  try {
319
- // Check if user already exists
320
- const { rows: existingUsers } = await getPool().query(
321
- 'SELECT * FROM users WHERE email = $1',
322
- [email]
323
- );
324
-
325
- if (existingUsers.length > 0) {
326
- return res.status(400).json({
327
- success: false,
328
- error: 'Email already registered'
329
- });
330
  }
331
-
332
- // Hash password
333
  const hashedPassword = await bcrypt.hash(password, 10);
334
-
335
- // Create new user
336
- const { rows: newUser } = await getPool().query(
337
- 'INSERT INTO users (name, email, password) VALUES ($1, $2, $3) RETURNING id, name, email',
338
- [name, email, hashedPassword]
339
- );
340
-
341
- res.json({
342
- success: true,
343
- user: newUser[0],
344
- message: 'Registration successful'
345
- });
346
  } catch (error) {
347
  console.error('Error registering user:', error);
348
- res.status(500).json({
349
- success: false,
350
- error: 'Failed to register user'
351
- });
352
  }
353
  });
354
 
355
- // Login
356
  app.post('/api/login', async (req, res) => {
357
  const { email, password } = req.body;
358
-
359
  if (!email || !password) {
360
- return res.status(400).json({
361
- success: false,
362
- error: 'Email and password are required'
363
- });
364
  }
365
-
366
  try {
367
- const { rows: users } = await getPool().query(
368
- 'SELECT * FROM users WHERE email = $1',
369
- [email]
370
- );
371
-
372
- if (users.length === 0) {
373
- return res.status(401).json({
374
- success: false,
375
- error: 'Invalid email or password'
376
- });
377
  }
378
-
379
- const user = users[0];
380
  const validPassword = await bcrypt.compare(password, user.password);
381
-
382
  if (!validPassword) {
383
- return res.status(401).json({
384
- success: false,
385
- error: 'Invalid email or password'
386
- });
387
  }
388
-
389
- res.json({
390
- success: true,
391
- user: {
392
- id: user.id,
393
- name: user.name,
394
- email: user.email
395
- }
396
- });
397
  } catch (error) {
398
  console.error('Error logging in:', error);
399
- res.status(500).json({
400
- success: false,
401
- error: 'Login failed'
402
- });
403
  }
404
  });
405
 
406
- // Get user submissions (protected route example)
407
  app.get('/api/user-submissions/:userId', checkOtpAuth, async (req, res) => {
408
- const { userId } = req.params;
409
-
410
- try {
411
- const result = await getPool().query(
412
- 'SELECT * FROM submissions WHERE user_id = $1 ORDER BY created_at DESC',
413
- [userId]
414
- );
415
- // Ensure card_type, payment_method, and payment_address are always present, and remove upi_id
416
- const submissions = result.rows.map(sub => {
417
- const payment_address = sub.payment_address || sub.upi_id || 'oldsub';
418
- const mapped = {
419
- ...sub,
420
- payment_address,
421
- card_type: sub.card_type || 'oldsub',
422
- payment_method: sub.payment_method || 'oldsub'
423
- };
424
- delete mapped.upi_id;
425
- return mapped;
426
- });
427
- res.json({ success: true, submissions });
428
- } catch (error) {
429
- res.status(500).json({ success: false, error: 'Failed to fetch submissions' });
430
- }
431
  });
432
 
433
- // Gift Card Routes
434
  app.post('/api/gift-cards', checkOtpAuth, async (req, res) => {
435
- const {
436
- ticket_user_name,
437
- gc_code,
438
- gc_phone,
439
- ticket_number,
440
- payment_address,
441
- amount,
442
- proof_video_url,
443
- card_type, // new field
444
- payment_method // new field
445
- } = req.body;
446
  const userId = req.headers['x-user-id'];
447
-
448
- // Generate ticket number if not provided
449
  const finalTicketNumber = ticket_number || `TKT-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
450
-
451
  if (!ticket_user_name || !gc_code || !gc_phone || !payment_address || !amount || !proof_video_url || !card_type || !payment_method) {
452
- return res.status(400).json({
453
- success: false,
454
- error: 'All fields are required including the video URL, card type, payment address, and payment method'
455
- });
456
- }
457
-
458
- try {
459
- const result = await getPool().query(
460
- `INSERT INTO submissions (
461
- user_id,
462
- ticket_user_name,
463
- gc_code,
464
- gc_phone,
465
- ticket_number,
466
- payment_address,
467
- amount,
468
- proof_video_url,
469
- card_type,
470
- payment_method
471
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING id`,
472
- [userId, ticket_user_name, gc_code, gc_phone, finalTicketNumber, payment_address, amount, proof_video_url, card_type, payment_method]
473
- );
474
- res.json({
475
- success: true,
476
- submissionId: result.rows[0].id,
477
- message: 'Gift card submission successful'
478
  });
 
479
  } catch (error) {
480
  console.error('Gift card submission error:', error);
481
- res.status(500).json({
482
- success: false,
483
- error: 'Failed to submit gift card. Please try again.'
484
- });
485
- }
486
  });
487
 
488
  // File2Link Upload Route
@@ -514,61 +393,51 @@ app.post('/api/upload', async (req, res) => {
514
  }
515
  });
516
 
517
- // Get chat messages
518
  app.get('/api/messages/:userId', checkOtpAuth, async (req, res) => {
519
- const { userId } = req.params;
520
- const userEmail = req.headers['x-user-email'];
521
-
522
- try {
523
- // Verify that the user is requesting their own messages
524
- const userResult = await getPool().query('SELECT id FROM users WHERE email = $1', [userEmail]);
525
- if (userResult.rows.length === 0 || userResult.rows[0].id !== parseInt(userId)) {
526
- return res.status(403).json({ success: false, error: 'Unauthorized access' });
527
- }
528
-
529
- const result = await getPool().query(
530
- 'SELECT * FROM messages WHERE user_id = $1 ORDER BY created_at ASC',
531
- [userId]
532
- );
533
- res.json({ success: true, messages: result.rows });
534
- } catch (error) {
535
- console.error('Error fetching messages:', error);
536
- res.status(500).json({ success: false, error: 'Failed to fetch messages' });
537
- }
538
  });
539
 
540
- // Send message
541
  app.post('/api/messages', checkOtpAuth, async (req, res) => {
542
- const { userId, content, sender } = req.body;
543
- const userEmail = req.headers['x-user-email'];
544
-
545
- if (!content || !sender) {
546
- return res.status(400).json({ success: false, error: 'Content and sender are required' });
547
- }
548
-
549
- try {
550
- // Verify that the user is sending a message to their own chat
551
- const userResult = await getPool().query('SELECT id FROM users WHERE email = $1', [userEmail]);
552
- if (userResult.rows.length === 0 || userResult.rows[0].id !== parseInt(userId)) {
553
- return res.status(403).json({ success: false, error: 'Unauthorized access' });
554
- }
555
-
556
- const result = await getPool().query(
557
- 'INSERT INTO messages (user_id, content, sender) VALUES ($1, $2, $3) RETURNING *',
558
- [userId, content, sender]
559
- );
560
- res.json({ success: true, message: result.rows[0] });
561
- } catch (error) {
562
- console.error('Error sending message:', error);
563
- res.status(500).json({ success: false, error: 'Failed to send message' });
564
- }
565
  });
566
 
567
- // Admin routes
568
  app.get('/api/admin/users', async (req, res) => {
569
  try {
570
- const result = await getPool().query('SELECT id, email, created_at FROM users ORDER BY created_at DESC');
571
- res.json({ success: true, users: result.rows });
 
572
  } catch (error) {
573
  console.error('Error fetching users:', error);
574
  res.status(500).json({ success: false, error: 'Failed to fetch users' });
@@ -577,13 +446,9 @@ app.get('/api/admin/users', async (req, res) => {
577
 
578
  app.get('/api/admin/messages/all', async (req, res) => {
579
  try {
580
- const result = await getPool().query(`
581
- SELECT m.*, u.email as user_email
582
- FROM messages m
583
- JOIN users u ON m.user_id = u.id
584
- ORDER BY m.created_at DESC
585
- `);
586
- res.json({ success: true, messages: result.rows });
587
  } catch (error) {
588
  console.error('Error fetching messages:', error);
589
  res.status(500).json({ success: false, error: 'Failed to fetch messages' });
@@ -593,11 +458,9 @@ app.get('/api/admin/messages/all', async (req, res) => {
593
  app.get('/api/admin/messages/:userId', async (req, res) => {
594
  const { userId } = req.params;
595
  try {
596
- const result = await getPool().query(
597
- 'SELECT * FROM messages WHERE user_id = $1 ORDER BY created_at ASC',
598
- [userId]
599
- );
600
- res.json({ success: true, messages: result.rows });
601
  } catch (error) {
602
  console.error('Error fetching messages:', error);
603
  res.status(500).json({ success: false, error: 'Failed to fetch messages' });
@@ -607,10 +470,8 @@ app.get('/api/admin/messages/:userId', async (req, res) => {
607
  app.post('/api/admin/messages', async (req, res) => {
608
  try {
609
  const { userId, content } = req.body;
610
- await getPool().query(
611
- 'INSERT INTO messages (user_id, content, sender) VALUES ($1, $2, $3)',
612
- [userId, content, 'admin']
613
- );
614
  res.json({ success: true });
615
  } catch (error) {
616
  console.error('Error sending message:', error);
@@ -621,7 +482,8 @@ app.post('/api/admin/messages', async (req, res) => {
621
  app.delete('/api/admin/messages/:messageId', async (req, res) => {
622
  const { messageId } = req.params;
623
  try {
624
- await getPool().query('DELETE FROM messages WHERE id = $1', [messageId]);
 
625
  res.json({ success: true });
626
  } catch (error) {
627
  console.error('Error deleting message:', error);
@@ -632,10 +494,11 @@ app.delete('/api/admin/messages/:messageId', async (req, res) => {
632
  app.delete('/api/admin/users/:userId', async (req, res) => {
633
  const { userId } = req.params;
634
  try {
 
635
  // First delete all messages for the user
636
- await getPool().query('DELETE FROM messages WHERE user_id = $1', [userId]);
637
  // Then delete the user
638
- await getPool().query('DELETE FROM users WHERE id = $1', [userId]);
639
  res.json({ success: true });
640
  } catch (error) {
641
  console.error('Error deleting user:', error);
@@ -645,14 +508,9 @@ app.delete('/api/admin/users/:userId', async (req, res) => {
645
 
646
  app.get('/api/admin/submissions', async (req, res) => {
647
  try {
648
- const result = await getPool().query(`
649
- SELECT s.*, u.email as user_email
650
- FROM submissions s
651
- JOIN users u ON s.user_id = u.id
652
- ORDER BY s.created_at DESC
653
- `);
654
- // Ensure card_type, payment_method, and payment_address are always present, and remove upi_id
655
- const submissions = result.rows.map(sub => {
656
  const payment_address = sub.payment_address || sub.upi_id || 'oldsub';
657
  const mapped = {
658
  ...sub,
@@ -663,7 +521,7 @@ app.get('/api/admin/submissions', async (req, res) => {
663
  delete mapped.upi_id;
664
  return mapped;
665
  });
666
- res.json({ success: true, submissions });
667
  } catch (error) {
668
  console.error('Error fetching submissions:', error);
669
  res.status(500).json({ success: false, error: 'Failed to fetch submissions' });
@@ -685,30 +543,21 @@ app.post('/api/admin/submissions/:submissionId/status', async (req, res) => {
685
  }
686
 
687
  try {
 
688
  // First check if submission exists
689
- const checkResult = await getPool().query(
690
- 'SELECT * FROM submissions WHERE id = $1',
691
- [submissionId]
692
- );
693
 
694
- if (checkResult.rows.length === 0) {
695
  return res.status(404).json({ success: false, error: 'Submission not found' });
696
  }
697
 
698
  // Update submission status with a CASE statement to ensure valid status
699
- const updateResult = await getPool().query(
700
- `UPDATE submissions
701
- SET status = CASE
702
- WHEN $1 IN ('pending', 'approved', 'rejected', 'paid', 'closed')
703
- THEN $1
704
- ELSE status
705
- END
706
- WHERE id = $2
707
- RETURNING *`,
708
- [status, submissionId]
709
  );
710
 
711
- if (updateResult.rows.length === 0) {
712
  return res.status(500).json({
713
  success: false,
714
  error: 'Failed to update submission status'
@@ -717,7 +566,7 @@ app.post('/api/admin/submissions/:submissionId/status', async (req, res) => {
717
 
718
  res.json({
719
  success: true,
720
- submission: updateResult.rows[0],
721
  message: `Status updated to ${status}`
722
  });
723
  } catch (error) {
@@ -734,27 +583,22 @@ app.post('/api/admin/submissions/:submissionId/status', async (req, res) => {
734
  app.get('/api/admin/submissions/:submissionId', async (req, res) => {
735
  const { submissionId } = req.params;
736
  try {
737
- const result = await getPool().query(`
738
- SELECT s.*, u.email as user_email
739
- FROM submissions s
740
- JOIN users u ON s.user_id = u.id
741
- WHERE s.id = $1
742
- `, [submissionId]);
743
 
744
- if (result.rows.length === 0) {
745
  return res.status(404).json({ success: false, error: 'Submission not found' });
746
  }
747
  // Ensure card_type, payment_method, and payment_address are always present, and remove upi_id
748
- const sub = result.rows[0];
749
- const payment_address = sub.payment_address || sub.upi_id || 'oldsub';
750
- const submission = {
751
- ...sub,
752
  payment_address,
753
- card_type: sub.card_type || 'oldsub',
754
- payment_method: sub.payment_method || 'oldsub'
755
  };
756
- delete submission.upi_id;
757
- res.json({ success: true, submission });
758
  } catch (error) {
759
  console.error('Error fetching submission details:', error);
760
  res.status(500).json({ success: false, error: 'Failed to fetch submission details' });
@@ -764,16 +608,19 @@ app.get('/api/admin/submissions/:submissionId', async (req, res) => {
764
  // Utility endpoint to update old submissions: set card_type and payment_method to 'oldsub' where missing
765
  app.post('/api/admin/fix-old-submissions', async (req, res) => {
766
  try {
767
- const result = await getPool().query(
768
- `UPDATE submissions
769
- SET card_type = 'oldsub', payment_method = 'oldsub'
770
- WHERE (card_type IS NULL OR card_type = '')
771
- OR (payment_method IS NULL OR payment_method = '')
772
- RETURNING id`);
 
 
 
 
773
  res.json({
774
  success: true,
775
- updatedCount: result.rows.length,
776
- updatedIds: result.rows.map(r => r.id)
777
  });
778
  } catch (error) {
779
  console.error('Error updating old submissions:', error);
@@ -888,4 +735,8 @@ setInterval(() => {
888
  });
889
  }, 30000); // Every 30 seconds
890
 
 
 
 
 
891
  module.exports = app;
 
 
1
  const express = require('express');
2
  const cors = require('cors');
3
  const path = require('path');
4
  const bcrypt = require('bcrypt');
5
  const multer = require('multer');
6
+ const { getDb } = require('./db');
7
  const otpService = require('./otpService');
8
  const axios = require('axios');
9
  const http = require('http');
 
18
  methods: ["GET", "POST"]
19
  }
20
  });
21
+ const port = 3000;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  // Middleware
24
  app.use(cors());
 
108
  console.log(`[${level.toUpperCase()}] ${message}`, details);
109
  }
110
 
111
+ // OTP Authentication middleware (MongoDB version)
112
  const requireOtpAuth = async (req, res, next) => {
113
  const otp = req.headers['x-otp-token'];
114
  const email = req.headers['x-user-email'];
 
118
  }
119
 
120
  try {
121
+ const db = await getDb();
122
+ const result = await db.collection('otps').findOne({
123
+ email,
124
+ otp,
125
+ verified: true,
126
+ expires_at: { $gt: new Date() }
127
+ });
128
+ if (!result) {
129
  return res.status(401).json({ error: 'Invalid or expired OTP' });
130
  }
 
131
  req.user = { email };
132
  next();
133
  } catch (err) {
 
136
  }
137
  };
138
 
139
+ // Admin OTP Authentication middleware (MongoDB version)
140
  const requireAdminOtpAuth = async (req, res, next) => {
141
  try {
142
  const otp = req.headers['x-otp-token'];
143
  const email = req.headers['x-user-email'];
 
144
  if (!otp || !email) {
145
+ return res.status(401).json({ success: false, error: 'Missing authentication headers' });
 
 
 
146
  }
147
+ const db = await getDb();
148
+ const result = await db.collection('otps').findOne({
149
+ email,
150
+ otp,
151
+ is_used: false,
152
+ expires_at: { $gt: new Date() }
153
+ });
154
+ if (!result) {
155
+ return res.status(401).json({ success: false, error: 'Invalid or expired OTP' });
 
 
 
 
156
  }
157
+ await db.collection('otps').updateOne({ email, otp }, { $set: { is_used: true } });
 
 
 
 
 
 
158
  next();
159
  } catch (error) {
160
  console.error('Admin auth error:', error);
161
+ res.status(500).json({ success: false, error: 'Authentication error' });
 
 
 
162
  }
163
  };
164
 
 
265
  }
266
  });
267
 
268
+ // Register new user (MongoDB version)
269
  app.post('/api/register', async (req, res) => {
270
  const { name, email, password } = req.body;
 
271
  if (!name || !email || !password) {
272
+ return res.status(400).json({ success: false, error: 'Name, email and password are required' });
 
 
 
273
  }
 
274
  try {
275
+ const db = await getDb();
276
+ const existingUser = await db.collection('users').findOne({ email });
277
+ if (existingUser) {
278
+ return res.status(400).json({ success: false, error: 'Email already registered' });
 
 
 
 
 
 
 
279
  }
 
 
280
  const hashedPassword = await bcrypt.hash(password, 10);
281
+ const result = await db.collection('users').insertOne({ name, email, password: hashedPassword, created_at: new Date() });
282
+ res.json({ success: true, user: { id: result.insertedId, name, email }, message: 'Registration successful' });
 
 
 
 
 
 
 
 
 
 
283
  } catch (error) {
284
  console.error('Error registering user:', error);
285
+ res.status(500).json({ success: false, error: 'Failed to register user' });
 
 
 
286
  }
287
  });
288
 
289
+ // Login (MongoDB version)
290
  app.post('/api/login', async (req, res) => {
291
  const { email, password } = req.body;
 
292
  if (!email || !password) {
293
+ return res.status(400).json({ success: false, error: 'Email and password are required' });
 
 
 
294
  }
 
295
  try {
296
+ const db = await getDb();
297
+ const user = await db.collection('users').findOne({ email });
298
+ if (!user) {
299
+ return res.status(401).json({ success: false, error: 'Invalid email or password' });
 
 
 
 
 
 
300
  }
 
 
301
  const validPassword = await bcrypt.compare(password, user.password);
 
302
  if (!validPassword) {
303
+ return res.status(401).json({ success: false, error: 'Invalid email or password' });
 
 
 
304
  }
305
+ res.json({ success: true, user: { id: user._id, name: user.name, email: user.email } });
 
 
 
 
 
 
 
 
306
  } catch (error) {
307
  console.error('Error logging in:', error);
308
+ res.status(500).json({ success: false, error: 'Login failed' });
 
 
 
309
  }
310
  });
311
 
312
+ // Get user submissions (MongoDB version)
313
  app.get('/api/user-submissions/:userId', checkOtpAuth, async (req, res) => {
314
+ const { userId } = req.params;
315
+ try {
316
+ const db = await getDb();
317
+ const submissions = await db.collection('submissions').find({ user_id: userId }).sort({ created_at: -1 }).toArray();
318
+ const mappedSubs = submissions.map(sub => {
319
+ const payment_address = sub.payment_address || sub.upi_id || 'oldsub';
320
+ const mapped = {
321
+ ...sub,
322
+ payment_address,
323
+ card_type: sub.card_type || 'oldsub',
324
+ payment_method: sub.payment_method || 'oldsub'
325
+ };
326
+ delete mapped.upi_id;
327
+ return mapped;
328
+ });
329
+ res.json({ success: true, submissions: mappedSubs });
330
+ } catch (error) {
331
+ res.status(500).json({ success: false, error: 'Failed to fetch submissions' });
332
+ }
 
 
 
 
333
  });
334
 
335
+ // Gift Card Submission (MongoDB version)
336
  app.post('/api/gift-cards', checkOtpAuth, async (req, res) => {
337
+ const { ticket_user_name, gc_code, gc_phone, ticket_number, payment_address, amount, proof_video_url, card_type, payment_method } = req.body;
 
 
 
 
 
 
 
 
 
 
338
  const userId = req.headers['x-user-id'];
 
 
339
  const finalTicketNumber = ticket_number || `TKT-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
 
340
  if (!ticket_user_name || !gc_code || !gc_phone || !payment_address || !amount || !proof_video_url || !card_type || !payment_method) {
341
+ return res.status(400).json({ success: false, error: 'All fields are required including the video URL, card type, payment address, and payment method' });
342
+ }
343
+ try {
344
+ const db = await getDb();
345
+ const result = await db.collection('submissions').insertOne({
346
+ user_id: userId,
347
+ ticket_user_name,
348
+ gc_code,
349
+ gc_phone,
350
+ ticket_number: finalTicketNumber,
351
+ payment_address,
352
+ amount,
353
+ proof_video_url,
354
+ card_type,
355
+ payment_method,
356
+ status: 'pending',
357
+ created_at: new Date(),
358
+ updated_at: new Date()
 
 
 
 
 
 
 
 
359
  });
360
+ res.json({ success: true, submissionId: result.insertedId, message: 'Gift card submission successful' });
361
  } catch (error) {
362
  console.error('Gift card submission error:', error);
363
+ res.status(500).json({ success: false, error: 'Failed to submit gift card. Please try again.' });
364
+ }
 
 
 
365
  });
366
 
367
  // File2Link Upload Route
 
393
  }
394
  });
395
 
396
+ // Get chat messages (MongoDB version)
397
  app.get('/api/messages/:userId', checkOtpAuth, async (req, res) => {
398
+ const { userId } = req.params;
399
+ const userEmail = req.headers['x-user-email'];
400
+ try {
401
+ const db = await getDb();
402
+ const user = await db.collection('users').findOne({ email: userEmail });
403
+ if (!user || user._id.toString() !== userId) {
404
+ return res.status(403).json({ success: false, error: 'Unauthorized access' });
405
+ }
406
+ const messages = await db.collection('messages').find({ user_id: userId }).sort({ created_at: 1 }).toArray();
407
+ res.json({ success: true, messages });
408
+ } catch (error) {
409
+ console.error('Error fetching messages:', error);
410
+ res.status(500).json({ success: false, error: 'Failed to fetch messages' });
411
+ }
 
 
 
 
 
412
  });
413
 
414
+ // Send message (MongoDB version)
415
  app.post('/api/messages', checkOtpAuth, async (req, res) => {
416
+ const { userId, content, sender } = req.body;
417
+ const userEmail = req.headers['x-user-email'];
418
+ if (!content || !sender) {
419
+ return res.status(400).json({ success: false, error: 'Content and sender are required' });
420
+ }
421
+ try {
422
+ const db = await getDb();
423
+ const user = await db.collection('users').findOne({ email: userEmail });
424
+ if (!user || user._id.toString() !== userId) {
425
+ return res.status(403).json({ success: false, error: 'Unauthorized access' });
426
+ }
427
+ const result = await db.collection('messages').insertOne({ user_id: userId, content, sender, created_at: new Date() });
428
+ res.json({ success: true, message: result.ops?.[0] || { user_id: userId, content, sender } });
429
+ } catch (error) {
430
+ console.error('Error sending message:', error);
431
+ res.status(500).json({ success: false, error: 'Failed to send message' });
432
+ }
 
 
 
 
 
 
433
  });
434
 
435
+ // Admin routes (MongoDB version)
436
  app.get('/api/admin/users', async (req, res) => {
437
  try {
438
+ const db = await getDb();
439
+ const users = await db.collection('users').find({}, { projection: { password: 0 } }).sort({ created_at: -1 }).toArray();
440
+ res.json({ success: true, users });
441
  } catch (error) {
442
  console.error('Error fetching users:', error);
443
  res.status(500).json({ success: false, error: 'Failed to fetch users' });
 
446
 
447
  app.get('/api/admin/messages/all', async (req, res) => {
448
  try {
449
+ const db = await getDb();
450
+ const messages = await db.collection('messages').find({}).sort({ created_at: -1 }).toArray();
451
+ res.json({ success: true, messages });
 
 
 
 
452
  } catch (error) {
453
  console.error('Error fetching messages:', error);
454
  res.status(500).json({ success: false, error: 'Failed to fetch messages' });
 
458
  app.get('/api/admin/messages/:userId', async (req, res) => {
459
  const { userId } = req.params;
460
  try {
461
+ const db = await getDb();
462
+ const messages = await db.collection('messages').find({ user_id: userId }).sort({ created_at: 1 }).toArray();
463
+ res.json({ success: true, messages });
 
 
464
  } catch (error) {
465
  console.error('Error fetching messages:', error);
466
  res.status(500).json({ success: false, error: 'Failed to fetch messages' });
 
470
  app.post('/api/admin/messages', async (req, res) => {
471
  try {
472
  const { userId, content } = req.body;
473
+ const db = await getDb();
474
+ const result = await db.collection('messages').insertOne({ user_id: userId, content, sender: 'admin', created_at: new Date() });
 
 
475
  res.json({ success: true });
476
  } catch (error) {
477
  console.error('Error sending message:', error);
 
482
  app.delete('/api/admin/messages/:messageId', async (req, res) => {
483
  const { messageId } = req.params;
484
  try {
485
+ const db = await getDb();
486
+ await db.collection('messages').deleteOne({ _id: messageId });
487
  res.json({ success: true });
488
  } catch (error) {
489
  console.error('Error deleting message:', error);
 
494
  app.delete('/api/admin/users/:userId', async (req, res) => {
495
  const { userId } = req.params;
496
  try {
497
+ const db = await getDb();
498
  // First delete all messages for the user
499
+ await db.collection('messages').deleteMany({ user_id: userId });
500
  // Then delete the user
501
+ await db.collection('users').deleteOne({ _id: userId });
502
  res.json({ success: true });
503
  } catch (error) {
504
  console.error('Error deleting user:', error);
 
508
 
509
  app.get('/api/admin/submissions', async (req, res) => {
510
  try {
511
+ const db = await getDb();
512
+ const submissions = await db.collection('submissions').find({}).sort({ created_at: -1 }).toArray();
513
+ const mappedSubs = submissions.map(sub => {
 
 
 
 
 
514
  const payment_address = sub.payment_address || sub.upi_id || 'oldsub';
515
  const mapped = {
516
  ...sub,
 
521
  delete mapped.upi_id;
522
  return mapped;
523
  });
524
+ res.json({ success: true, submissions: mappedSubs });
525
  } catch (error) {
526
  console.error('Error fetching submissions:', error);
527
  res.status(500).json({ success: false, error: 'Failed to fetch submissions' });
 
543
  }
544
 
545
  try {
546
+ const db = await getDb();
547
  // First check if submission exists
548
+ const checkResult = await db.collection('submissions').findOne({ _id: submissionId });
 
 
 
549
 
550
+ if (!checkResult) {
551
  return res.status(404).json({ success: false, error: 'Submission not found' });
552
  }
553
 
554
  // Update submission status with a CASE statement to ensure valid status
555
+ const updateResult = await db.collection('submissions').updateOne(
556
+ { _id: submissionId },
557
+ { $set: { status: status, updated_at: new Date() } }
 
 
 
 
 
 
 
558
  );
559
 
560
+ if (updateResult.matchedCount === 0) {
561
  return res.status(500).json({
562
  success: false,
563
  error: 'Failed to update submission status'
 
566
 
567
  res.json({
568
  success: true,
569
+ submission: updateResult.value,
570
  message: `Status updated to ${status}`
571
  });
572
  } catch (error) {
 
583
  app.get('/api/admin/submissions/:submissionId', async (req, res) => {
584
  const { submissionId } = req.params;
585
  try {
586
+ const db = await getDb();
587
+ const submission = await db.collection('submissions').findOne({ _id: submissionId });
 
 
 
 
588
 
589
+ if (!submission) {
590
  return res.status(404).json({ success: false, error: 'Submission not found' });
591
  }
592
  // Ensure card_type, payment_method, and payment_address are always present, and remove upi_id
593
+ const payment_address = submission.payment_address || submission.upi_id || 'oldsub';
594
+ const submissionDetails = {
595
+ ...submission,
 
596
  payment_address,
597
+ card_type: submission.card_type || 'oldsub',
598
+ payment_method: submission.payment_method || 'oldsub'
599
  };
600
+ delete submissionDetails.upi_id;
601
+ res.json({ success: true, submission: submissionDetails });
602
  } catch (error) {
603
  console.error('Error fetching submission details:', error);
604
  res.status(500).json({ success: false, error: 'Failed to fetch submission details' });
 
608
  // Utility endpoint to update old submissions: set card_type and payment_method to 'oldsub' where missing
609
  app.post('/api/admin/fix-old-submissions', async (req, res) => {
610
  try {
611
+ const db = await getDb();
612
+ const result = await db.collection('submissions').updateMany(
613
+ {
614
+ $or: [
615
+ { card_type: { $in: [null, ''] } },
616
+ { payment_method: { $in: [null, ''] } }
617
+ ]
618
+ },
619
+ { $set: { card_type: 'oldsub', payment_method: 'oldsub' } }
620
+ );
621
  res.json({
622
  success: true,
623
+ updatedCount: result.modifiedCount
 
624
  });
625
  } catch (error) {
626
  console.error('Error updating old submissions:', error);
 
735
  });
736
  }, 30000); // Every 30 seconds
737
 
738
+ server.listen(port, () => {
739
+ console.log(`Server running on port ${port}`);
740
+ });
741
+
742
  module.exports = app;