-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
487 lines (431 loc) · 15.5 KB
/
server.js
File metadata and controls
487 lines (431 loc) · 15.5 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
require("dotenv").config();
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const cors = require("cors");
const path = require("path");
const db = require("./models");
const axios = require("axios");
const bodyParser = require("body-parser");
const fetch = require("node-fetch");
// Controllers and Routers
const handleVideoSocket = require("./config/videoSocket");
const handleMessageSocket = require("./config/messageSocket");
const loadController = require("./controllers/LoadController");
const driverController = require("./controllers/DriverController");
const messageRouter = require("./controllers/MessageController");
const LoadsRouter = require("./config/123LoadBoards/123LoadBoards");
const {
PORT = 3001,
CLIENT_ID,
CLIENT_SECRET,
USER_AGENT,
URI_123,
DEV_URI,
} = process.env;
const app = express();
const server = http.createServer(app);
// Middleware
// app.use(express.urlencoded({ extended: true }));
// app.use(express.json());
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ limit: "50mb", extended: true }));
// app.use(bodyParser.json());
app.use(express.static("client/build"));
app.use(bodyParser.json({ limit: "50mb" }));
// app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
// app.use(cors({ origin: "http://localhost:3000", credentials: true }));
const allowedOrigins = [
"http://localhost:3000",
"https://gadzconnect.com",
"https://www.gadzconnect.com",
"https://api.gadzconnect.com"
];
app.use(
cors({
origin: function (origin, callback) {
// Allow requests with no origin (like mobile apps or curl)
if (!origin) return callback(null, true);
if (allowedOrigins.includes(origin)) return callback(null, true);
return callback(new Error("Not allowed by CORS"));
},
credentials: true,
})
);
// Socket.io
// const io = socketIo(server, {
// cors: { origin: "http://localhost:3000", methods: ["GET", "POST"] },
// });
const io = socketIo(server, {
cors: {
origin: allowedOrigins,
methods: ["GET", "POST"],
credentials: true,
},
});
io.on("connection", (socket) => {
handleVideoSocket(io, socket);
handleMessageSocket(io, socket);
});
// ✅ 123 Loadboard Routes
app.use("/api/123Loads", LoadsRouter);
// ✅ Legacy alias for old frontend routes
app.post("/api/load-search", async (req, res, next) => {
req.url = "/search";
LoadsRouter.handle(req, res, next);
});
// Route to handle token exchange and fetch loads
app.get("/auth/callback", async (req, res) => {
try {
const authCode = req.query.code;
console.log("Authorization Code:", authCode);
// Exchange authorization code for access token
const formData = new URLSearchParams({
grant_type: "authorization_code",
code: authCode,
client_id: CLIENT_ID,
redirect_uri: DEV_URI,
}).toString();
const tokenResp = await fetch(`${URI_123}/token`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"123LB-Api-Version": "1.3",
"User-Agent": "gadzconnect_dev",
"123LB-AID": "Ba76be66d-dc2e-4045-87a3-adec3ae60eaf",
Authorization:
"Basic " +
Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64"),
},
body: formData,
});
const tokenData = await tokenResp.json();
console.log("Access Token Response:", tokenData);
if (tokenData.access_token) {
const bearerToken = tokenData.access_token;
// Use access token to fetch loads
const loadResp = await fetch(`${URI_123}/loads/search`, {
method: "POST",
headers: {
"123LB-Correlation-Id": "123GADZ",
"Content-Type": "application/json",
"123LB-Api-Version": "1.3",
"User-Agent": USER_AGENT,
"123LB-AID": "Ba76be66d-dc2e-4045-87a3-adec3ae60eaf",
Authorization: `Bearer ${bearerToken}`,
},
body: JSON.stringify({
metadata: {
limit: 10,
sortBy: { field: "Origin", direction: "Ascending" },
fields: "all",
type: "Regular",
},
includeWithGreaterPickupDates: true,
origin: {
states: ["IL"],
city: "Chicago",
radius: 100,
type: "City",
},
destination: {
type: "Anywhere",
},
equipmentTypes: ["Van", "Flatbed", "Reefer"],
includeLoadsWithoutWeight: true,
includeLoadsWithoutLength: true,
}),
});
const loadData = await loadResp.json();
console.log("Load Response:", loadData);
res.send(loadData);
} else {
console.error("Access token not found in response:", tokenData);
res.status(400).send("Failed to retrieve access token.");
}
} catch (error) {
console.error(error);
res.status(500).send("An error occurred during the process.");
}
});
// Route to handle token exchange and fetch loads dynamically
app.post("/auth/callMeBack", async (req, res) => {
try {
const authCode = req.query.code || req.body.code;
const searchData = req.body;
console.log("Authorization Code:", authCode);
console.log("Search Data from Frontend:", searchData);
if (!authCode) {
return res.status(400).json({ error: "Missing authorization code." });
}
// Exchange authorization code for access token
const formData = new URLSearchParams({
grant_type: "authorization_code",
code: authCode,
client_id: CLIENT_ID,
redirect_uri: DEV_URI,
}).toString();
const tokenResp = await fetch(`${URI_123}/token`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"123LB-Api-Version": "1.3",
"User-Agent": "gadzconnect_dev",
"123LB-AID": "Ba76be66d-dc2e-4045-87a3-adec3ae60eaf",
Authorization:
"Basic " + Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64"),
},
body: formData,
});
const tokenData = await tokenResp.json();
console.log("Access Token Response:", tokenData);
if (!tokenData.access_token) {
console.error("Access token not found in response:", tokenData);
return res.status(400).json({ error: "Failed to retrieve access token." });
}
const bearerToken = tokenData.access_token;
// Use access token to fetch loads with frontend data
const loadResp = await fetch(`${URI_123}/loads/search`, {
method: "POST",
headers: {
"123LB-Correlation-Id": "123GADZ",
"Content-Type": "application/json",
"123LB-Api-Version": "1.3",
"User-Agent": USER_AGENT,
"123LB-AID": "Ba76be66d-dc2e-4045-87a3-adec3ae60eaf",
Authorization: `Bearer ${bearerToken}`,
},
body: JSON.stringify({
metadata: {
limit: searchData.limit || 10,
sortBy: { field: "Origin", direction: "Ascending" },
fields: "all",
type: "Regular",
},
includeWithGreaterPickupDates: true,
origin: {
states: [searchData.originState || "IL"],
city: searchData.originCity || "Chicago",
radius: parseInt(searchData.radius || 100),
type: "City",
},
destination: {
type: searchData.destinationType || "Anywhere",
},
equipmentTypes: searchData.equipmentTypes
? [searchData.equipmentTypes]
: ["Van", "Flatbed", "Reefer"],
includeLoadsWithoutWeight: true,
includeLoadsWithoutLength: true,
}),
});
const loadData = await loadResp.json();
console.log("Load Response:", loadData);
res.status(200).json(loadData);
} catch (error) {
console.error("Error in /auth/callback:", error);
res.status(500).json({ error: "An error occurred during the process." });
}
});
// Route to handle token exchange and fetch loads dynamically
app.post("/api/loadboard/auth/callback", async (req, res) => {
try {
const { code } = req.query; // from redirect URL
const searchData = req.body; // from frontend form
console.log("Authorization Code:", code);
console.log("Search Data from Frontend:", searchData);
if (!code) {
return res.status(400).json({ error: "Missing authorization code" });
}
// Exchange authorization code for access token
const formData = new URLSearchParams({
grant_type: "authorization_code",
code,
client_id: CLIENT_ID,
redirect_uri: DEV_URI,
}).toString();
const tokenResp = await fetch(`${URI_123}/token`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"123LB-Api-Version": "1.3",
"User-Agent": "gadzconnect_dev",
"123LB-AID": "Ba76be66d-dc2e-4045-87a3-adec3ae60eaf",
Authorization:
"Basic " +
Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64"),
},
body: formData,
});
const tokenData = await tokenResp.json();
console.log("Access Token Response:", tokenData);
if (!tokenData.access_token) {
return res.status(400).json({ error: "Failed to retrieve access token." });
}
const bearerToken = tokenData.access_token;
// Use access token to fetch loads with user input
const loadResp = await fetch(`${URI_123}/loads/search`, {
method: "POST",
headers: {
"123LB-Correlation-Id": "123GADZ",
"Content-Type": "application/json",
"123LB-Api-Version": "1.3",
"User-Agent": "gadzconnect_dev",
"123LB-AID": "Ba76be66d-dc2e-4045-87a3-adec3ae60eaf",
Authorization: `Bearer ${bearerToken}`,
},
body: JSON.stringify({
metadata: {
limit: searchData.limit || 10,
sortBy: { field: "Origin", direction: "Ascending" },
fields: "all",
type: "Regular",
},
includeWithGreaterPickupDates: true,
origin: {
city: searchData.originCity,
states: [searchData.originState],
radius: parseInt(searchData.radius || 100),
type: "City",
},
destination: {
type: searchData.destinationType || "Anywhere",
},
equipmentTypes: searchData.equipmentTypes
? [searchData.equipmentTypes]
: ["Van", "Flatbed", "Reefer"],
includeLoadsWithoutWeight: true,
includeLoadsWithoutLength: true,
}),
});
const loadData = await loadResp.json();
console.log("Load Response:", loadData);
res.status(200).json(loadData);
} catch (error) {
console.error("Error in /auth/callback:", error);
res.status(500).json({ error: "Server error during callback process." });
}
});
// Combined route: handle token exchange + dynamic search in one step
app.post("/api/123Loads/callback", async (req, res) => {
try {
const authCode = req.query.code;
const formOptions = req.body; // Frontend form data
console.log("Authorization Code:", authCode);
console.log("Form Options:", formOptions);
if (!authCode) {
return res.status(400).json({ error: "Missing authorization code" });
}
// Step 1: Exchange authorization code for access token
const formData = new URLSearchParams({
grant_type: "authorization_code",
code: authCode,
client_id: CLIENT_ID,
redirect_uri: DEV_URI,
}).toString();
const tokenResp = await fetch(`${URI_123}/token`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"123LB-Api-Version": "1.3",
"User-Agent": "gadzconnect_dev",
"123LB-AID": "Ba76be66d-dc2e-4045-87a3-adec3ae60eaf",
Authorization: "Basic " + Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64"),
},
body: formData,
});
const tokenData = await tokenResp.json();
console.log("Access Token Response:", tokenData);
if (!tokenData.access_token) {
console.error("Access token not found in response:", tokenData);
return res.status(400).json({ error: "Failed to retrieve access token." });
}
const bearerToken = tokenData.access_token;
// Step 2: Build dynamic search body using frontend data
const searchBody = {
metadata: {
limit: Number(formOptions.limit) || 10,
sortBy: formOptions.sortBy || { field: "Origin", direction: "Ascending" },
fields: "all",
type: "Regular",
},
includeWithGreaterPickupDates: true,
origin: {
states: formOptions.originState ? [formOptions.originState] : [],
city: formOptions.originCity || "",
radius: Number(formOptions.radius) || 100,
type: formOptions.originType || "City",
},
destination: {
type: formOptions.destinationType || "Anywhere",
},
equipmentTypes: formOptions.equipmentTypes?.length
? formOptions.equipmentTypes
: ["Van", "Flatbed", "Reefer"],
includeLoadsWithoutWeight: true,
includeLoadsWithoutLength: true,
weight: formOptions.minWeight
? { min: Number(formOptions.minWeight) }
: undefined,
companyRating: formOptions.companyRating || undefined,
};
// Step 3: Use access token to fetch loads dynamically
const loadResp = await fetch(`${URI_123}/loads/search`, {
method: "POST",
headers: {
"123LB-Correlation-Id": "123GADZ",
"Content-Type": "application/json",
"123LB-Api-Version": "1.3",
"User-Agent": USER_AGENT,
"123LB-AID": "Ba76be66d-dc2e-4045-87a3-adec3ae60eaf",
Authorization: `Bearer ${bearerToken}`,
},
body: JSON.stringify(searchBody),
});
const loadData = await loadResp.json();
console.log("Load Search Response:", loadData);
// Step 4: Return combined token + results to frontend
res.json({
access_token: bearerToken,
search: loadData,
});
} catch (error) {
console.error("Error during 123Loadboard callback:", error);
res.status(500).json({ error: "An error occurred during the process." });
}
});
// Message API route
app.use("/api/message", messageRouter);
// Other Controllers
app.use("/api/agreement", require("./controllers/AgreementController"));
app.use("/api/user", require("./controllers/UserAPIRoutes"));
app.use("/api/admin", require("./controllers/AdminController"));
app.use("/api/newsletter", require("./controllers/NewsLetterController"));
app.use("/api/it-help", require("./controllers/ITticketController"));
app.use("/api/employee-help", require("./controllers/EmployeeTicketController"));
app.use("/api/mail", require("./config/nodeMailer/nodeMailer"));
app.use("/api/stripe", require("./config/stripe"));
app.use(require("./routes"));
// ✅ Load and driver endpoints
app.get("/api/loads/user/:userId", loadController.getAllUserLoads);
app.get("/api/drivers/user/:userId", driverController.getAllUserDrivers);
app.get("/api/loads", loadController.getAllLoads);
app.get("/api/drivers", driverController.getAllDrivers);
app.post("/api/loads", loadController.createLoad);
app.post("/api/drivers", driverController.createDriver);
// ✅ Test route
app.get("/api/config", (req, res) => res.json({ success: true }));
// ✅ Serve React frontend
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
// ✅ Database + Server Start
db.sequelize
.sync({})
.then(() => {
server.listen(PORT, () =>
console.log(`🚀 Server running at http://localhost:${PORT}`)
);
})
.catch((err) => console.error("DB sync error:", err.message));
// { alter: true } { force: true }