-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
291 lines (246 loc) · 9.4 KB
/
server.js
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
const express = require("express");
const mysql = require("mysql2/promise");
const bodyParser = require("body-parser");
const path = require("path");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const app = express();
const port = process.env.PORT || 8080;
const JWT_SECRET = process.env.JWT_SECRET || "la_ia_nos_esta_carreando"; // Use an environment variable in production
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname)));
// MySQL connection pool
const pool = mysql.createPool({
host: process.env.DB_HOST || "localhost",
user: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD || "root",
database: process.env.DB_NAME || "Mathez",
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
// Middleware to verify JWT
const verifyToken = (req, res, next) => {
const token = req.headers["authorization"]?.split(" ")[1];
if (!token) {
return res.status(403).json({ error: "No token provided" });
}
jwt.verify(token, JWT_SECRET, (err, decoded) => {
if (err) {
return res.status(401).json({ error: "Unauthorized" });
}
req.userId = decoded.id;
next();
});
};
// Login route
app.post("/login", async (req, res) => {
const { numCta, passwd } = req.body;
console.log("Login attempt for numCta:", numCta);
try {
const [results] = await pool.query("SELECT numCta, passwd FROM Alumnos WHERE numCta = ?", [numCta]);
if (results.length === 1) {
const isMatch = await bcrypt.compare(passwd, results[0].passwd);
if (isMatch) {
const token = jwt.sign({ id: results[0].numCta }, JWT_SECRET, { expiresIn: "1h" });
console.log("Login successful for numCta:", numCta);
res.json({ success: true, message: "Login successful", token: token });
} else {
console.log("Invalid password for numCta:", numCta);
res.status(401).json({ success: false, message: "Invalid username or password" });
}
} else {
console.log("User not found for numCta:", numCta);
res.status(401).json({ success: false, message: "Invalid username or password" });
}
} catch (error) {
console.error("Error executing query:", error);
res.status(500).json({ error: "Internal server error" });
}
});
// Register route
app.post("/register", async (req, res) => {
const { apellidoP, apellidoM, nombres, email, passwd } = req.body;
if (!apellidoP || !apellidoM || !nombres || !email || !passwd) {
return res.status(400).json({ success: false, message: "All fields are required" });
}
try {
const connection = await pool.getConnection();
const [maxResult] = await connection.query("SELECT MAX(numCta) as maxNumCta FROM Alumnos");
let nextNumCta = Math.max(1001, (maxResult[0].maxNumCta || 1000) + 1);
const hashedPassword = await bcrypt.hash(passwd, 10);
const query =
"INSERT INTO Alumnos (numCta, apellidoP, apellidoM, nombres, email, passwd) VALUES (?, ?, ?, ?, ?, ?)";
await connection.query(query, [nextNumCta, apellidoP, apellidoM, nombres, email, hashedPassword]);
connection.release();
res.json({ success: true, message: "Registration successful", numCta: nextNumCta });
} catch (error) {
console.error("Database error:", error);
res.status(500).json({ success: false, message: "Internal server error" });
}
});
// New route to get user data
app.get("/api/user", verifyToken, async (req, res) => {
try {
const [results] = await pool.query(
"SELECT numCta, apellidoP, apellidoM, nombres, email FROM Alumnos WHERE numCta = ?",
[req.userId]
);
if (results.length === 0) {
return res.status(404).json({ error: "User not found" });
}
res.json(results[0]);
} catch (error) {
console.error("Error fetching user data:", error);
res.status(500).json({ error: "Internal server error" });
}
});
// Update user information
app.post("/api/user/update", verifyToken, async (req, res) => {
const { nombres, apellidoP, apellidoM, email } = req.body;
const numCta = req.userId;
try {
const query = "UPDATE Alumnos SET nombres = ?, apellidoP = ?, apellidoM = ?, email = ? WHERE numCta = ?";
await pool.query(query, [nombres, apellidoP, apellidoM, email, numCta]);
res.json({ success: true, message: "User information updated successfully" });
} catch (error) {
console.error("Error updating user information:", error);
res.status(500).json({ success: false, message: "Internal server error" });
}
});
// Update security settings
app.post("/api/user/security", verifyToken, async (req, res) => {
const { passwd } = req.body;
const numCta = req.userId;
try {
if (passwd) {
const hashedPassword = await bcrypt.hash(passwd, 10);
const query = "UPDATE Alumnos SET passwd = ? WHERE numCta = ?";
await pool.query(query, [hashedPassword, numCta]);
}
// Note: twoFactorAuth is not implemented yet
res.json({ success: true, message: "Security settings updated successfully" });
} catch (error) {
console.error("Error updating security settings:", error);
res.status(500).json({ success: false, message: "Internal server error" });
}
});
// Update notification settings
app.post("/api/user/notifications", verifyToken, async (req, res) => {
// Note: This is a temporary implementation
console.log("Notification settings update requested:", req.body);
res.json({ success: true, message: "Notification settings update acknowledged (not implemented yet)" });
});
// Update privacy settings
app.post("/api/user/privacy", verifyToken, async (req, res) => {
// Note: This is a temporary implementation
console.log("Privacy settings update requested:", req.body);
res.json({ success: true, message: "Privacy settings update acknowledged (not implemented yet)" });
});
// Route to fetch available courses
app.get("/api/courses", verifyToken, async (req, res) => {
try {
const [results] = await pool.query(
`
SELECT c.nombre
FROM Cursos c
WHERE c.id_curso NOT IN (
SELECT i.id_curso
FROM Inscripciones i
WHERE i.numCta = ?
)
`,
[req.userId]
);
res.json(results);
} catch (error) {
console.error("Error fetching available courses:", error);
res.status(500).json({ error: "Internal server error" });
}
});
// Route to register for a course
app.post("/api/register-course", verifyToken, async (req, res) => {
const { courseName } = req.body;
try {
// First, get the course ID
const [courseResults] = await pool.query("SELECT id_curso FROM Cursos WHERE nombre = ?", [courseName]);
if (courseResults.length === 0) {
return res.status(404).json({ success: false, message: "Curso no encontrado" });
}
const courseId = courseResults[0].id_curso;
// Now, register the user for the course
await pool.query(
"INSERT INTO Inscripciones (id_curso, numCta, fecha_inicio, progreso, estatus) VALUES (?, ?, CURRENT_DATE(), 0, 'En progreso')",
[courseId, req.userId]
);
res.json({ success: true, message: "Registro de curso exitoso" });
} catch (error) {
console.error("Error registering for course:", error);
res.status(500).json({ success: false, message: "Error interno del servidor" });
}
});
// Homepage route
app.get("/homepage", verifyToken, async (req, res) => {
console.log("Homepage request for userId:", req.userId);
try {
const [userResults] = await pool.query(
"SELECT apellidoP, apellidoM, nombres FROM Alumnos WHERE numCta = ?",
[req.userId]
);
const [inscripcionResults] = await pool.query("SELECT * FROM Inscripciones WHERE numCta = ?", [
req.userId,
]);
if (userResults.length === 0) {
console.log("User not found for userId:", req.userId);
return res.status(404).json({ error: "User not found" });
}
const userData = {
nombre: userResults[0].nombres,
apellidoP: userResults[0].apellidoP,
apellidoM: userResults[0].apellidoM,
matricula: req.userId,
inscrito: inscripcionResults.length > 0,
};
console.log("Sending user data:", userData);
res.json(userData);
} catch (error) {
console.error("Error fetching user data:", error);
if (error.code === "ER_NO_SUCH_TABLE") {
res.status(500).json({ error: "Database table missing. Please contact the administrator." });
} else {
res.status(500).json({ error: "Internal server error" });
}
}
});
// Catch-all route to serve index.html for any unmatched routes
app.get("*", (req, res) => {
// Only serve index.html for routes that should be handled by the frontend router
if (req.path.startsWith("/api/") || req.path === "/logout") {
res.status(404).json({ error: "Not found" });
} else {
res.sendFile(path.join(__dirname, "index.html"));
}
});
// Routes for specific pages
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
});
app.get("/homepage", verifyToken, (req, res) => {
res.sendFile(path.join(__dirname, "homepage.html"));
});
app.get("/sobreNos", (req, res) => {
res.sendFile(path.join(__dirname, "sobreNos.html"));
});
// API routes
app.post("/logout", (req, res) => {
res.json({ success: true, message: "Logout successful" });
});
// Catch-all route for API requests
app.all("/api/*", (req, res) => {
res.status(404).json({ error: "API endpoint not found" });
});
app.listen(port, "0.0.0.0", () => {
console.log(`Server running on http://0.0.0.0:${port}`);
});