-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
277 lines (240 loc) · 7.89 KB
/
server.js
File metadata and controls
277 lines (240 loc) · 7.89 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
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const path = require("path");
const bcrypt = require("bcrypt");
const app = express();
const PORT = 3000;
app.use(cors({
origin: '*',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type']
}));
app.use(express.json());
app.use(express.static(path.join(__dirname)));
mongoose.connect("mongodb://127.0.0.1:27017/BloggingWebsite")
.then(() => console.log("MongoDB Connected"))
.catch(err => console.error("MongoDB Connection Error:", err));
const userSchema = new mongoose.Schema({
username: String,
email: { type: String, unique: true },
password: String,
profession: String,
birthdate: String,
gender: String
});
const User = mongoose.model("User", userSchema);
// Blog Schema
const blogSchema = new mongoose.Schema({
title: {
type: String,
required: true,
trim: true
},
content: {
type: String,
required: true
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
authorName: {
type: String,
required: true
},
category: {
type: String,
required: true,
enum: ['Technology', 'Science', 'Education', 'Arts', 'Other']
},
tags: [{
type: String,
trim: true
}],
coverImage: {
type: String, // URL to the image
default: null
},
createdAt: {
type: Date,
default: Date.now
},
updatedAt: {
type: Date,
default: Date.now
},
likes: {
type: Number,
default: 0
},
comments: [{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
text: String,
createdAt: {
type: Date,
default: Date.now
}
}]
});
const Blog = mongoose.model("Blog", blogSchema);
app.post("/SignUp", async (req, res) => {
try {
const { username, email, password, profession, birthdate, gender } = req.body;
console.log("Received data:", { username, email, profession, birthdate, gender });
if (!username || !email || !password) {
return res.status(400).json({ message: "Username, email, and password are required!" });
}
// Validate password length
if (password.length < 6) {
return res.status(400).json({ message: "Password must be at least 6 characters long!" });
}
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ message: "Email already exists!" });
}
// Hash the password
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);
// Create a new user with hashed password
const newUser = new User({
username,
email,
password: hashedPassword, // Store the hashed password
profession,
birthdate,
gender
});
console.log("Attempting to save user:", { ...newUser.toObject(), password: '[HASHED]' });
await newUser.save();
console.log("User saved successfully:", { ...newUser.toObject(), password: '[HASHED]' });
res.json({ message: "Signup successful!" });
} catch (error) {
console.error("Error saving user:", error);
if (error.code === 11000) {
res.status(400).json({ message: "Email already exists!" });
} else {
res.status(500).json({ message: error.message || "Internal Server Error" });
}
}
});
app.post("/login", async (req, res) => {
try {
const { email, password } = req.body;
console.log("Login attempt for email:", email);
if (!email || !password) {
console.log("Missing email or password");
return res.status(400).json({ message: "Email and password are required!" });
}
// Find the user by email
const user = await User.findOne({ email });
console.log("User found:", user ? "Yes" : "No");
// If user doesn't exist
if (!user) {
console.log("User not found");
return res.status(401).json({ message: "Invalid email or password!" });
}
// Compare the provided password with the hashed password
const isPasswordValid = await bcrypt.compare(password, user.password);
console.log("Password valid:", isPasswordValid);
if (!isPasswordValid) {
console.log("Invalid password");
return res.status(401).json({ message: "Invalid email or password!" });
}
// User authenticated successfully
console.log("Login successful for user:", user.email);
res.status(200).json({
success: true,
message: "Login successful!",
user: {
id: user._id,
username: user.username,
email: user.email,
profession: user.profession
}
});
} catch (error) {
console.error("Login error:", error);
res.status(500).json({ message: error.message || "Internal Server Error" });
}
});
// Create a new blog post
app.post("/api/blogs", async (req, res) => {
try {
const { title, content, category, tags, coverImage, userId, authorName } = req.body;
// Validate required fields
if (!title || !content || !category || !userId || !authorName) {
return res.status(400).json({
message: "Title, content, category, and author information are required!"
});
}
// Create new blog post
const newBlog = new Blog({
title,
content,
author: userId,
authorName,
category,
tags: tags || [],
coverImage: coverImage || null,
});
await newBlog.save();
console.log("Blog saved successfully:", { id: newBlog._id, title });
res.status(201).json({
success: true,
message: "Blog posted successfully!",
blog: newBlog
});
} catch (error) {
console.error("Error creating blog:", error);
res.status(500).json({
success: false,
message: error.message || "Error creating blog post"
});
}
});
// Get all blogs
app.get("/api/blogs", async (req, res) => {
try {
const blogs = await Blog.find()
.sort({ createdAt: -1 }) // Sort by newest first
.limit(10); // Limit to 10 posts per page
res.json({
success: true,
blogs
});
} catch (error) {
console.error("Error fetching blogs:", error);
res.status(500).json({
success: false,
message: error.message || "Error fetching blogs"
});
}
});
// Get blogs by user
app.get("/api/blogs/user/:userId", async (req, res) => {
try {
const blogs = await Blog.find({ author: req.params.userId })
.sort({ createdAt: -1 });
res.json({
success: true,
blogs
});
} catch (error) {
console.error("Error fetching user blogs:", error);
res.status(500).json({
success: false,
message: error.message || "Error fetching user blogs"
});
}
});
app.use((req, res) => {
res.status(404).send("Page not found!");
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});