forked from Arquisoft/wiq_0
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuser-service.js
349 lines (288 loc) · 9.61 KB
/
user-service.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
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
// user-service.js
const express = require("express");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
const { User, Group } = require("./user-model");
const app = express();
const port = 8001;
const cors = require("cors");
const corsOptions = {
origin: [
process.env.AUTH_SERVICE_URL || "http://localhost:8000",
process.env.USER_SERVICE_URL || "http://localhost:8001",
process.env.QUESTION_SERVICE_URL || "http://localhost:8002",
process.env.STATS_SERVICE_URL || "http://localhost:8003",
process.env.GATEWAY_SERVICE_URL || "http://localhost:8004",
process.env.MONGODB_URI || "mongodb://localhost:27017/userdb",
process.env.MONGODB_STATS_URI || "mongodb://localhost:27017/statsdb",
],
};
app.use(cors(corsOptions));
// Middleware to parse JSON in request body
app.use(bodyParser.json());
// Connect to MongoDB
const mongoUri = process.env.MONGODB_URI || "mongodb://localhost:27017/userdb";
mongoose.connect(mongoUri);
// Function to validate required fields in the request body
function validateRequiredFields(req, requiredFields) {
for (const field of requiredFields) {
if (!(field in req.body)) {
throw new Error(`Missing required field: ${field}`);
}
}
}
function checkInput(input) {
if (typeof input !== "string") {
throw new Error("Input debe ser una cadena de texto");
}
return input.trim();
}
app.post("/adduser", async (req, res) => {
try {
// Check if required fields are present in the request body
validateRequiredFields(req, ["username", "password"]);
const username = req.body.username;
// Check if the username already exists
const existingUser = await User.findOne({ username: username });
if (existingUser) {
return res
.status(400)
.json({
error: "Username already exists. Please choose a different username.",
});
}
// Encrypt the password before saving it
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const newUser = new User({
username: req.body.username,
password: hashedPassword,
});
await newUser.save();
const token = jwt.sign({ userId: newUser._id }, "your-secret-key", {
expiresIn: "1h",
});
res.json({
username: newUser.username,
createdAt: newUser.createdAt,
token: token,
});
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Route to get all users
app.get("/users", async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({ error: "Internal Server Error" });
}
});
app.get("/users/search", async (req, res) => {
try {
const { username } = req.query;
// Encuentra al usuario actual
const currentUser = await User.findOne({ username });
if (!currentUser) {
return res.status(404).json({ error: "User not found" });
}
// Encuentra los amigos del usuario actual
const un = username;
const currentUserFriends = currentUser.friends;
// Encuentra todos los usuarios que no son amigos del usuario actual
const users = await User.find({
username: { $ne: un, $nin: currentUserFriends },
});
res.json(users);
} catch (error) {
res.status(500).json({ error: "Internal Server Error" });
}
});
app.post("/users/add-friend", async (req, res) => {
try {
const username = req.body.username;
const friendUsername = req.body.friendUsername;
// Buscar el usuario por su nombre de usuario
const user = await User.findOne({ username: username });
if (!user) {
return res.status(404).json({ error: "User not found" });
}
// Verificar si el amigo ya está en la lista de amigos del usuario
if (user.friends.includes(friendUsername)) {
return res.status(400).json({ error: "Friend already added" });
}
// Agregar al amigo a la lista de amigos del usuario
user.friends.push(friendUsername);
await user.save();
res.json({ message: "Friend added successfully" });
} catch (error) {
res.status(500).json({ error: "Internal Server Error" });
}
});
app.post("/users/remove-friend", async (req, res) => {
try {
const username = req.body.username;
const friendUsername = req.body.friendUsername;
// Buscar el usuario por su nombre de usuario
const user = await User.findOne({ username: username });
if (!user) {
return res.status(404).json({ error: "User not found" });
}
// Verificar si el amigo está en la lista de amigos del usuario
if (!user.friends.includes(friendUsername)) {
return res
.status(400)
.json({ error: "Friend not found in the user's friend list" });
}
// Eliminar al amigo de la lista de amigos del usuario
user.friends = user.friends.filter((friend) => friend !== friendUsername);
await user.save();
res.json({ message: "Friend removed successfully" });
} catch (error) {
console.error("Error removing friend:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
// Route to get friends of the authenticated user
app.get("/friends", async (req, res) => {
try {
const username = req.query.user;
// Buscar al usuario por su nombre de usuario
const user = await User.findOne({ username });
if (!user) {
return res.status(404).json({ error: "User not found" });
}
// Devuelve la lista de amigos
res.json({ friends: user.friends });
} catch (error) {
res.status(500).json({ error: "Internal Server Error" });
}
});
app.get("/userInfo", async (req, res) => {
try {
const username = checkInput(req.query.user);
const user = await User.findOne(
{ username: username },
{ username: 1, createdAt: 1, games: 1 }
);
res.json(user);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
app.get("/userGames", async (req, res) => {
try {
const username = req.query.user;
if(!username){
return res.status(400).json({ error: "Nombre inválido" });
}
const user = await User.findOne({ username:
username,
});
if (!user) {
return res.status(404).json({ error: "Usuario no encontrado" });
}
res.json(user.games);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
app.post("/saveGameList", async (req, res) => {
try {
const username = checkInput(req.body.username);
const gamemode = checkInput(req.body.gameMode);
const gameData = req.body.gameData;
const questions = req.body.questions;
let user = await User.findOne({ username: username });
if (!user) {
return res.status(404).json({ error: "Usuario no encontrado" });
}
const gameDataWithGamemode = { ...gameData, gamemode, questions };
console.log(gameDataWithGamemode);
user.games.push(gameDataWithGamemode);
await user.save();
res.json({ message: "Partida guardada exitosamente" });
} catch (error) {
res.status(400).json({ error: "Error al guardar partida en la lista: " + error.message });
}
});
app.get('/group/list', async (req, res) => {
try {
const allGroups = await Group.find();
res.json({ groups: allGroups });
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
}
});
// Obtener un grupo por su nombre
app.get('/group/:groupName', async (req, res) => {
try {
const groupName = req.params.groupName;
const group = await Group.findOne({ name: groupName });
if (!group) {
return res.status(404).json({ error: 'Group not found' });
}
res.json({ group });
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Crear un nuevo grupo
app.post('/group/add', async (req, res) => {
try {
const name= req.body.name;
const username= req.body.username;
if (!name) {
return res.status(400).json({ error: 'Group name cannot be empty' });
}
const existingGroup = await Group.findOne({ name: name });
if (existingGroup) {
return res.status(400).json({ error: 'Group name already exists' });
}
const user = await User.findOne({ username:username });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const newGroup = new Group({ name: name,
members: [username] });
await newGroup.save();
res.json({ message: 'Group created successfully' });
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Unirse a un grupo existente
app.post('/group/join', async (req, res) => {
try {
const groupId=req.body.groupId;
const username=req.body.username;
const user = await User.findOne({ username });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const group = await Group.findById(groupId);
if (!group) {
return res.status(404).json({ error: 'Group not found' });
}
if (group.members.includes(username)) {
return res.status(400).json({ error: 'User already a member of this group' });
}
group.members.push(username);
await group.save();
res.json({ message: 'User joined the group successfully' });
} catch (error) {
res.status(400).json({ error: error.message });
}
});
const server = app.listen(port, () => {
console.log(`User Service listening at http://localhost:${port}`);
});
// Listen for the 'close' event on the Express.js server
server.on("close", () => {
// Close the Mongoose connection
mongoose.connection.close();
});
module.exports = server;