forked from sudiptasarkar011/FusionVision
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
189 lines (163 loc) · 5.54 KB
/
server.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
180
181
182
183
184
185
186
187
188
189
const express = require("express");
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const multer = require("multer");
const path = require("path");
const { body, validationResult } = require("express-validator");
const helmet = require("helmet");
require("dotenv").config();
const app = express();
// Middleware
app.use(express.json());
app.use(express.static("uploads"));
app.use(helmet()); // Adds security headers
// Environment Variables
const PORT = process.env.PORT || 5000;
const MONGODB_URI = process.env.MONGODB_URI;
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET || !MONGODB_URI) {
console.error("Critical environment variables are missing in .env");
process.exit(1); // Exit if critical env variables are not set
}
// MongoDB Connection
mongoose
.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB connected successfully."))
.catch((err) => {
console.error("MongoDB connection error:", err);
process.exit(1);
});
// User Schema
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
images: [
{
filename: String,
uploadedAt: { type: Date, default: Date.now },
},
],
});
const User = mongoose.model("User", userSchema);
// Register Route
app.post(
"/register",
[
body("name").notEmpty().withMessage("Name is required."),
body("email").isEmail().withMessage("Valid email is required."),
body("password")
.isLength({ min: 6 })
.withMessage("Password must be at least 6 characters."),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, password } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({ name, email, password: hashedPassword });
await user.save();
res.status(201).json({ message: "User registered successfully!" });
} catch (error) {
if (error.code === 11000) {
res.status(400).json({ message: "Email already registered." });
} else {
res.status(500).json({ message: "Error registering user.", error: error.message });
}
}
}
);
// Login Route
app.post(
"/login",
[
body("email").isEmail().withMessage("Valid email is required."),
body("password").notEmpty().withMessage("Password is required."),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
return res.status(404).json({ message: "User not found." });
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ message: "Invalid credentials." });
}
const token = jwt.sign({ id: user._id }, JWT_SECRET, { expiresIn: "1h" });
res.status(200).json({ message: "Login successful!", token });
} catch (error) {
res.status(500).json({ message: "Error logging in.", error: error.message });
}
}
);
// Upload Middleware with Validation
const storage = multer.diskStorage({
destination: "uploads/",
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname));
},
});
const upload = multer({
storage,
limits: { fileSize: 2 * 1024 * 1024 }, // Limit file size to 2MB
fileFilter: (req, file, cb) => {
const fileTypes = /jpeg|jpg|png/;
const extname = fileTypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = fileTypes.test(file.mimetype);
if (extname && mimetype) {
cb(null, true);
} else {
cb(new Error("Only images (jpeg, jpg, png) are allowed."));
}
},
});
// Save Captured Image
app.post("/upload", upload.single("image"), async (req, res) => {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(401).json({ message: "Unauthorized." });
try {
const decoded = jwt.verify(token, JWT_SECRET);
const user = await User.findById(decoded.id);
if (!user) return res.status(404).json({ message: "User not found." });
user.images.push({ filename: req.file.filename });
await user.save();
res.status(200).json({ message: "Image uploaded successfully!", filename: req.file.filename });
} catch (error) {
res.status(500).json({ message: "Error uploading image.", error: error.message });
}
});
// Fetch User Images
app.get("/images", async (req, res) => {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(401).json({ message: "Unauthorized." });
try {
const decoded = jwt.verify(token, JWT_SECRET);
const user = await User.findById(decoded.id);
if (!user) return res.status(404).json({ message: "User not found." });
res.status(200).json({ images: user.images });
} catch (error) {
res.status(500).json({ message: "Error fetching images.", error: error.message });
}
});
// Centralized Error Handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: err.message || "Something went wrong!" });
});
// Start the Server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});