-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
224 lines (188 loc) · 6.17 KB
/
server.js
File metadata and controls
224 lines (188 loc) · 6.17 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
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const nodemailer = require('nodemailer');
const app = express();
app.use(express.json());
app.use(cors({ origin: '*', credentials: true }));
// app.use(
// cors({
// origin: ['https://dev-task-flow.vercel.app'],
// methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
// credentials: true,
// })
// );
mongoose
.connect(process.env.MONGO_URI)
.then(() => console.log('✅ Connected to MongoDB'))
.catch((err) => console.error('❌ MongoDB connection error:', err));
// **USER SCHEMA**
const UserSchema = new mongoose.Schema({
username: String,
email: { type: String, unique: true },
passwordHash: String,
});
const User = mongoose.model('User', UserSchema);
// **TASK SCHEMA**
const TaskSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
title: { type: String, required: true },
description: String,
priority: { type: String, enum: ['Low', 'Medium', 'High'], default: 'Low' },
deadline: Date,
pinned: { type: Boolean, default: false },
completed: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now },
});
const Task = mongoose.model('Task', TaskSchema);
// **EMAIL TRANSPORTER**
const transporter = nodemailer.createTransport({
host: 'smtp.aol.com',
port: 465,
secure: true,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
// **REGISTER ROUTE**
app.post('/register', async (req, res) => {
const { username, email, password } = req.body;
try {
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ error: 'User already registered.' });
}
const hashedPassword = await bcrypt.hash(password, 12);
await User.create({ username, email, passwordHash: hashedPassword });
res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
res.status(400).json({ error: 'User registration failed' });
}
});
// **LOGIN ROUTE**
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) return res.status(401).json({ error: 'User not found' });
const isValid = await bcrypt.compare(password, user.passwordHash);
if (!isValid) return res.status(401).json({ error: 'Invalid credentials' });
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, {
expiresIn: '1h',
});
res.json({ message: 'Login successful', token });
});
// **MIDDLEWARE: AUTHENTICATE USER**
const authenticate = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.userId = decoded.userId;
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
};
// **GET USER TASKS**
app.get('/tasks', authenticate, async (req, res) => {
try {
const tasks = await Task.find({ userId: req.userId }).sort({
createdAt: -1,
});
res.json(tasks);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch tasks' });
}
});
// **CREATE A NEW TASK**
app.post('/tasks', authenticate, async (req, res) => {
const { title, description, priority, deadline, pinned, completed } =
req.body;
if (!title) return res.status(400).json({ error: 'Title is required' });
try {
const newTask = await Task.create({
userId: req.userId,
title,
description,
priority,
deadline,
pinned,
completed,
});
res.status(201).json(newTask);
} catch (error) {
res.status(500).json({ error: 'Failed to create task' });
}
});
// **UPDATE A TASK**
app.put('/tasks/:taskId', authenticate, async (req, res) => {
try {
const updatedTask = await Task.findOneAndUpdate(
{ _id: req.params.taskId, userId: req.userId },
req.body,
{ new: true }
);
if (!updatedTask) return res.status(404).json({ error: 'Task not found' });
res.json(updatedTask);
} catch (error) {
res.status(500).json({ error: 'Failed to update task' });
}
});
// **DELETE A TASK**
app.delete('/tasks/:taskId', authenticate, async (req, res) => {
try {
const deletedTask = await Task.findOneAndDelete({
_id: req.params.taskId,
userId: req.userId,
});
if (!deletedTask) return res.status(404).json({ error: 'Task not found' });
res.json({ message: 'Task deleted' });
} catch (error) {
res.status(500).json({ error: 'Failed to delete task' });
}
});
// **DELETE ALL TASKS FOR A USER**
app.delete('/tasks', authenticate, async (req, res) => {
try {
await Task.deleteMany({ userId: req.userId });
res.json({ message: 'All tasks deleted' });
} catch (error) {
res.status(500).json({ error: 'Failed to delete tasks' });
}
});
// **FORGOT PASSWORD (Generate & Send New Password)**
app.post('/forgot-password', async (req, res) => {
const { email } = req.body;
try {
const user = await User.findOne({ email });
if (!user) return res.status(404).json({ error: 'User not found' });
const newPassword = Math.random().toString(36).slice(-8);
user.passwordHash = await bcrypt.hash(newPassword, 12);
await user.save();
const mailOptions = {
from: process.env.EMAIL_USER,
to: email,
subject: 'New Password - DevTaskFlow',
html: `
<h2>New Password Generated</h2>
<p>Hello <b>${user.username}</b>,</p>
<p>Your new password is: <b>${newPassword}</b></p>
<p>Thank you,</p>
<p><b>DevTaskFlow Team</b></p>
`,
};
transporter.sendMail(mailOptions, (error) => {
if (error) return res.status(500).json({ error: 'Failed to send email' });
res.json({ message: 'New password sent to your email.' });
});
} catch (err) {
res.status(500).json({ error: 'Internal server error' });
}
});
// **START SERVER**
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`✅ Server running on port ${PORT}`));