-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
325 lines (270 loc) · 10.5 KB
/
index.js
File metadata and controls
325 lines (270 loc) · 10.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
const express = require("express");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const app = express();
const router = express.Router();
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/billsplit", {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("✅ MongoDB connected"))
.catch(err => {
console.error("❌ MongoDB connection error:", err);
process.exit(1); // stop server if DB fails
});
const authenticateToken = require("./middleware/authenticateToken");
const User = require("./models/user");
const Friend = require("./models/friend");
const Group = require("./models/group");
const Expense = require("./models/expense");
app.use(cors());
app.use(express.json());
// LOGIN
app.post("/api/login", async (req, res) => {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (!user || user.password !== password) {
return res.status(401).json({ message: "Invalid username or password" });
}
const token = jwt.sign({ username }, "secret123");
res.json({ token });
});
// REGISTER
app.post("/api/register", async (req, res) => {
try {
const { username, password } = req.body;
const existing = await User.findOne({ username });
if (existing) return res.status(400).json({ message: "Username already taken" });
const newUser = new User({ username, password });
await newUser.save();
res.json({ message: "Registration successful!" });
} catch (err) {
console.error("Registration error:", err);
res.status(500).json({ message: "Server error" });
}
});
// ADD FRIEND
app.post("/api/add-friend", async (req, res) => {
try {
const { user, friend } = req.body;
const existing = await Friend.findOne({ user, friend });
if (existing) return res.status(400).json({ message: "Friend already added" });
const newFriend = new Friend({ user, friend });
await newFriend.save();
res.json({ message: "Friend added successfully!" });
} catch (err) {
console.error("Add friend error:", err);
res.status(500).json({ message: "Server error" });
}
});
// ✅ REMOVE FRIEND
app.delete("/api/unfriend", async (req, res) => {
try {
const { user, friend } = req.body;
const deleted = await Friend.findOneAndDelete({ user, friend });
if (!deleted) return res.status(404).json({ message: "Friend not found" });
res.json({ message: "Friend removed successfully!" });
} catch (err) {
console.error("Unfriend error:", err);
res.status(500).json({ message: "Server error" });
}
});
// GET FRIENDS
app.get("/api/friends", authenticateToken, async (req, res) => {
try {
const username = req.user.username;
const friends = await Friend.find({ user: username });
const friendList = friends.map(entry => entry.friend);
res.json({ friends: friendList });
} catch (err) {
console.error("Fetch friends error:", err);
res.status(500).json({ message: "Server error" });
}
});
// CREATE GROUP
app.post("/api/create-group", authenticateToken, async (req, res) => {
try {
const { name, members } = req.body;
const allMembers = [req.user.username, ...members];
const newGroup = new Group({ name, members: allMembers });
await newGroup.save();
res.json({ message: "Group created", groupId: newGroup._id });
} catch (err) {
console.error("Create group error:", err);
res.status(500).json({ message: "Server error" });
}
});
// ✅ DELETE GROUP
app.delete("/api/delete-group/:id", authenticateToken, async (req, res) => {
try {
const group = await Group.findById(req.params.id);
if (!group) return res.status(404).json({ message: "Group not found" });
if (group.members[0] !== req.user.username) {
return res.status(403).json({ message: "Only the group creator can delete this group" });
}
await Expense.deleteMany({ groupId: req.params.id }); // also delete expenses
await Group.findByIdAndDelete(req.params.id);
res.json({ message: "Group deleted successfully!" });
} catch (err) {
console.error("Delete group error:", err);
res.status(500).json({ message: "Server error" });
}
});
// ADD EXPENSE
app.post("/api/add-expense", authenticateToken, async (req, res) => {
try {
const { groupId, description, amount, category, paidBy } = req.body;
const expense = new Expense({ groupId, description, amount, category, paidBy });
await expense.save();
res.json({ message: "Expense added successfully!" });
} catch (err) {
console.error("Expense add error:", err);
res.status(500).json({ message: "Server error" });
}
});
// ✅ DELETE EXPENSE
app.delete("/api/delete-expense/:id", authenticateToken, async (req, res) => {
try {
const expense = await Expense.findById(req.params.id);
if (!expense) return res.status(404).json({ message: "Expense not found" });
if (expense.paidBy !== req.user.username) {
return res.status(403).json({ message: "Only the user who added this expense can delete it" });
}
await Expense.findByIdAndDelete(req.params.id);
res.json({ message: "Expense deleted successfully!" });
} catch (err) {
console.error("Delete expense error:", err);
res.status(500).json({ message: "Server error" });
}
});
// ✅ GET ALL GROUPS FOR LOGGED-IN USER
app.get("/api/groups", authenticateToken, async (req, res) => {
try {
const username = req.user.username;
console.log("Fetching groups for user:", username);
const groups = await Group.find({ members: username });
console.log("Found groups:", groups);
res.json({ groups });
} catch (err) {
console.error("Fetch user groups error:", err);
res.status(500).json({ message: "Server error" });
}
});
// START SERVER
app.listen(3000, () => {
console.log("🚀 Server running on http://localhost:3000");
});
// GET /api/search-users?query=someText
app.get("/api/search-users", authenticateToken, async (req, res) => {
try {
const query = req.query.query || "";
// Use a case-insensitive regex to search usernames partially matching 'query'
const users = await User.find({
username: { $regex: query, $options: "i" }
}).select("username -_id"); // only send usernames, no _id
// Return usernames as array
res.json({ users: users.map(u => u.username) });
} catch (err) {
console.error("User search error:", err);
res.status(500).json({ message: "Server error" });
}
});
app.delete("/api/remove-member", authenticateToken, async (req, res) => {
try {
const { groupId, memberToRemove } = req.body;
const group = await Group.findById(groupId);
if (!group) return res.status(404).json({ message: "Group not found" });
if (group.members[0] !== req.user.username) {
return res.status(403).json({ message: "Only the group creator can remove members" });
}
// Don't allow the creator to remove themselves
if (memberToRemove === req.user.username) {
return res.status(400).json({ message: "Group creator cannot remove themselves" });
}
// Remove member
group.members.pull(memberToRemove);
await group.save();
res.json({ message: `${memberToRemove} removed from group` });
} catch (err) {
console.error("Remove member error:", err);
res.status(500).json({ message: "Server error" });
}
});
app.get("/api/groups/:groupId", authenticateToken, async (req, res) => {
try {
const group = await Group.findById(req.params.groupId);
if (!group) return res.status(404).json({ message: "Group not found" });
const expenses = await Expense.find({ groupId: req.params.groupId });
res.json({
_id: group._id, // ✅ Add this line
name: group.name,
members: group.members,
expenses
});
} catch (err) {
console.error("Fetch group details error:", err);
res.status(500).json({ message: "Server error" });
}
});
app.put("/api/update-password", authenticateToken, async (req, res) => {
try {
const { oldPassword, newPassword } = req.body;
if (!oldPassword || !newPassword) {
return res.status(400).json({ message: "Both old and new passwords are required." });
}
const user = await User.findOne({ username: req.user.username });
if (!user) {
return res.status(404).json({ message: "User not found." });
}
if (user.password !== oldPassword) {
return res.status(401).json({ message: "Old password is incorrect." });
}
user.password = newPassword;
await user.save();
res.json({ message: "Password updated successfully!" });
} catch (err) {
console.error("Update password error:", err);
res.status(500).json({ message: "Server error" });
}
});
app.get("/api/profile", authenticateToken, async (req, res) => {
try {
const user = await User.findOne({ username: req.user.username }).select("username name email phone pr");
if (!user) return res.status(404).json({ message: "User not found" });
res.json(user);
} catch (err) {
console.error("Fetch profile error:", err);
res.status(500).json({ message: "Server error" });
}
});
app.put("/api/update-profile", authenticateToken, async (req, res) => {
try {
const { name, email, phone } = req.body;
const user = await User.findOneAndUpdate(
{ username: req.user.username },
{ name, email, phone },
{ new: true, runValidators: true }
).select("username name email phone");
if (!user) return res.status(404).json({ message: "User not found" });
res.json({ message: "Profile updated successfully", user });
} catch (err) {
console.error("Update profile error:", err);
res.status(500).json({ message: "Server error" });
}
});
// 🚀 Upload or update profile picture
app.put("/api/upload-profile-pic", authenticateToken, async (req, res) => {
const { profilePic } = req.body;
const username = req.user.username;
if (!profilePic) {
return res.status(400).json({ message: "No profile picture provided" });
}
try {
await User.updateOne({ username }, { profilePic });
res.json({ message: "Profile picture updated successfully" });
} catch (err) {
console.error("Upload profile picture error:", err);
res.status(500).json({ message: "Server error updating profile picture" });
}
});