-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
225 lines (182 loc) · 7.01 KB
/
server.js
File metadata and controls
225 lines (182 loc) · 7.01 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
// server.js
// --- 1. Imports and Setup ---
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// --- 2. Middleware ---
// Allow all origins (for development only)
app.use(cors({
origin: '*',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
}));
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// --- 3. MongoDB Connection ---
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.error('MongoDB Connection Error:', err));
// --- 4. Mongoose Schemas (Data Models) ---
const UserSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
}, { timestamps: true });
const TaskSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
text: { type: String, required: true },
totalCount: { type: Number, required: true },
currentCount: { type: Number, default: 0 },
completed: { type: Boolean, default: false },
}, { timestamps: true });
const User = mongoose.model('User', UserSchema);
const Task = mongoose.model('Task', TaskSchema);
// --- 5. Authentication Middleware ---
const authMiddleware = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Access denied. No token provided.' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
res.status(400).json({ message: 'Invalid token.' });
}
};
// --- 6. API Routes ---
// == AUTHENTICATION ROUTES ==
app.post('/api/auth/register', async (req, res) => {
try {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ message: 'Username and password are required.' });
}
const existingUser = await User.findOne({ username });
if (existingUser) {
return res.status(400).json({ message: 'Username already taken.' });
}
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
const newUser = new User({ username, password: hashedPassword });
await newUser.save();
res.status(201).json({ message: 'User registered successfully!' });
} catch (error) {
res.status(500).json({ message: 'Server error during registration.', error: error.message });
}
});
app.post('/api/auth/login', async (req, res) => {
try {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (!user) {
return res.status(400).json({ message: 'Invalid credentials.' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({ message: 'Invalid credentials.' });
}
const payload = { id: user._id, username: user.username };
const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ message: 'Logged in successfully!', token });
} catch (error) {
res.status(500).json({ message: 'Server error during login.', error: error.message });
}
});
// == TASK ROUTES (Protected) ==
app.get('/api/tasks', authMiddleware, async (req, res) => {
try {
const tasks = await Task.find({ userId: req.user.id }).sort({ createdAt: -1 });
res.json(tasks);
} catch (error) {
res.status(500).json({ message: 'Server error fetching tasks.', error: error.message });
}
});
app.post('/api/tasks', authMiddleware, async (req, res) => {
try {
const { text, totalCount } = req.body;
if (!text || !totalCount || totalCount < 1) {
return res.status(400).json({ message: 'Task text and a positive count are required.' });
}
const newTask = new Task({
userId: req.user.id,
text: text,
totalCount: totalCount,
currentCount: 0,
completed: false,
});
await newTask.save();
res.status(201).json(newTask);
} catch (error) {
res.status(500).json({ message: 'Server error creating task.', error: error.message });
}
});
app.put('/api/tasks/:id', authMiddleware, async (req, res) => {
try {
const { completed } = req.body;
const task = await Task.findById(req.params.id);
if (!task) {
return res.status(404).json({ message: 'Task not found.' });
}
if (task.userId.toString() !== req.user.id) {
return res.status(403).json({ message: 'User not authorized to update this task.' });
}
task.completed = completed;
await task.save();
res.json(task);
} catch (error) {
res.status(500).json({ message: 'Server error updating task.', error: error.message });
}
});
app.put('/api/tasks/:id/increment', authMiddleware, async (req, res) => {
try {
const task = await Task.findById(req.params.id);
if (!task) {
return res.status(404).json({ message: 'Task not found.' });
}
if (task.userId.toString() !== req.user.id) {
return res.status(403).json({ message: 'User not authorized to update this task.' });
}
if (task.currentCount < task.totalCount) {
task.currentCount += 1;
if (task.currentCount === task.totalCount) {
task.completed = true;
}
await task.save();
res.json(task);
} else {
res.status(400).json({ message: 'Task is already completed.' });
}
} catch (error) {
res.status(500).json({ message: 'Server error updating task.', error: error.message });
}
});
app.delete('/api/tasks/:id', authMiddleware, async (req, res) => {
try {
const task = await Task.findById(req.params.id);
if (!task) {
return res.status(404).json({ message: 'Task not found.' });
}
if (task.userId.toString() !== req.user.id) {
return res.status(403).json({ message: 'User not authorized to delete this task.' });
}
await Task.findByIdAndDelete(req.params.id);
res.json({ message: 'Task deleted successfully.' });
} catch (error) {
res.status(500).json({ message: 'Server error deleting task.', error: error.message });
}
});
// --- 7. Serve Frontend ---
app.get(/^\/(?!api).*/, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// --- 8. Start Server ---
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});