-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.js
179 lines (153 loc) · 6.25 KB
/
routes.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
import express from 'express';
import mongoose from 'mongoose';
import User from './data/User.js';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import {authMiddleware} from './routes/utils/auth.js';
const setupRoutes = (apiRouter) => {
apiRouter.post('/api/login', async (req, res) => {
const { username, password } = req.body;
const user = await User.findOne({ username });
console.log('user', user);
console.log('username', username);
console.log('password', password);
if (!user) {
return res.status(401).json({ error: 'Invalid username or password' });
}
const isPasswordCorrect = await bcrypt.compare(password, user.password);
if (!isPasswordCorrect) {
return res.status(401).json({ error: 'Invalid username or password' });
}
const token = signToken(user);
res.json({ token, message: 'Login successful' });
});
// POST /api/signup
apiRouter.post('/api/signup', async (req, res) => {
const { username, password } = req.body;
console.log(`Received signup request for username: ${username}, password: ${password}`);
try {
// check if user already exists in the database
const user = await User.findOne({ username });
if (user) {
console.log('Username already exists');
return res.status(400).json({ error: 'Username already exists' });
}
// hash the password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
// create new user in the database with the hashed password
const newUser = new User({
username,
password: hashedPassword,
});
console.log('New user', newUser);
await newUser.save();
res.status(200).json({ success: true, message: 'Signup successful' });
} catch (error) {
console.error('Error while signing up user:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
apiRouter.get('/api/user', authMiddleware, async (req, res) => {
const { username } = req.user;
try {
const user = await User.findOne({ username });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.status(200).json({ success: true, user });
} catch (error) {
console.error('Error while getting user:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// PUT /api/user/:id
apiRouter.put('/api/user/:id/responses/:responseId', authMiddleware, async (req, res) => {
const { id, responseId } = req.params;
const { essay, cover } = req.body;
try {
const user = await User.findOneAndUpdate({ _id: id, 'userResponses.responseId': responseId }, {
$set: {
'userResponses.$.essay': essay,
'userResponses.$.cover': cover
},
});
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.status(200).json({ success: true, message: 'Response updated successfully' });
} catch (error) {
console.error('Error while updating response:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// DELETE /api/user/:id
apiRouter.delete('/api/user/:id', authMiddleware, async (req, res) => {
const { id } = req.params;
try {
const user = await User.findByIdAndDelete(id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.status(200).json({ success: true, message: 'User deleted successfully' });
} catch (error) {
console.error('Error while deleting user:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
apiRouter.post('/api/user/:id/responses', authMiddleware, async (req, res) => {
const { id } = req.params;
const { essay, cover, createdAt } = req.body; // Add createdAt field
const responseId = mongoose.Types.ObjectId();
try {
const user = await User.findByIdAndUpdate(id, {
$push: {
userResponses: {
responseId,
essay,
cover,
createdAt, // Save createdAt field
},
},
});
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.status(200).json({ success: true, message: 'Response added successfully', responseId });
} catch (error) {
console.error('Error while adding response:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
apiRouter.get('/api/user/:id/responses', authMiddleware, async (req, res) => {
const { id } = req.params;
try {
const user = await User.findById(id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.status(200).json({ success: true, responses: user.userResponses });
} catch (error) {
console.error('Error while fetching responses:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
apiRouter.delete('/api/user/:id/responses/:responseId', authMiddleware, async (req, res) => {
const { id, responseId } = req.params;
try {
const user = await User.findByIdAndUpdate(id, {
$pull: {
userResponses: { responseId },
},
});
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.status(200).json({ success: true, message: 'Response deleted successfully' });
} catch (error) {
console.error('Error while deleting response:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
};
export default setupRoutes;