forked from CSI-KJSCE/appointment_to_examiner
Fixes for Admin Login, @somaiya.edu validation, and Password Visibility
This commit is contained in:
120
server/server.js
120
server/server.js
@@ -22,20 +22,32 @@ const Course = require("./models/Course");
|
||||
const User = require("./models/User");
|
||||
|
||||
// MongoDB Connection
|
||||
mongoose
|
||||
.connect(process.env.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
|
||||
.then(() => console.log("MongoDB connected"))
|
||||
.catch((err) => {
|
||||
console.error("MongoDB connection error:", err);
|
||||
process.exit(1); // Exit the app if the database connection fails
|
||||
});
|
||||
// MongoDB Connection
|
||||
const connectDB = async () => {
|
||||
try {
|
||||
await mongoose.connect(process.env.mongoURI, {
|
||||
useNewUrlParser: true,
|
||||
useUnifiedTopology: true,
|
||||
});
|
||||
console.log("MongoDB connected");
|
||||
} catch (err) {
|
||||
console.error("MongoDB connection failed:", err.message);
|
||||
}
|
||||
};
|
||||
|
||||
connectDB();
|
||||
|
||||
// Initialize App
|
||||
const app = express();
|
||||
const PORT = 8080;
|
||||
|
||||
// Middleware
|
||||
app.use(cors({ origin: process.env.CORS_ORIGIN || "http://localhost:3000", credentials: true }));
|
||||
app.use(
|
||||
cors({
|
||||
origin: process.env.CORS_ORIGIN || "http://localhost:3000",
|
||||
credentials: true,
|
||||
})
|
||||
);
|
||||
app.use(cookieparser());
|
||||
app.use(express.json());
|
||||
app.use(bodyParser.urlencoded({ extended: true }));
|
||||
@@ -74,9 +86,19 @@ app.get(
|
||||
"/auth/google/callback",
|
||||
passport.authenticate("google", { failureRedirect: "/" }),
|
||||
(req, res) => {
|
||||
const token = jwt.sign({ userId: req.user._id }, process.env.JWT_SECRET, { expiresIn: "1h" });
|
||||
const token = jwt.sign(
|
||||
{ userId: req.user._id, isAdmin: req.user.isAdmin },
|
||||
process.env.JWT_SECRET,
|
||||
{
|
||||
expiresIn: "1h",
|
||||
}
|
||||
);
|
||||
// Set token as a cookie or send it in the response
|
||||
res.cookie("token", token, { httpOnly: true, secure: false, maxAge: 3600000 });
|
||||
res.cookie("token", token, {
|
||||
httpOnly: true,
|
||||
secure: false,
|
||||
maxAge: 3600000,
|
||||
});
|
||||
res.redirect("http://localhost:3000/Welcome"); // Redirect to a frontend route after successful login
|
||||
}
|
||||
);
|
||||
@@ -85,6 +107,14 @@ app.get(
|
||||
app.post("/api/register", async (req, res) => {
|
||||
try {
|
||||
const { username, email, password } = req.body;
|
||||
|
||||
// Validation: Only allow somaiya emails
|
||||
if (email.endsWith("@somaiya.edu") === false) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ message: "Only @somaiya.edu emails are allowed" });
|
||||
}
|
||||
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
let user = await User.findOne({ email });
|
||||
|
||||
@@ -104,11 +134,21 @@ app.post("/api/register", async (req, res) => {
|
||||
await user.save();
|
||||
}
|
||||
|
||||
// Generate a JWT token using the user's ID
|
||||
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: "1h" });
|
||||
// adding isAdmin to token so we know if user is admin
|
||||
const token = jwt.sign(
|
||||
{ userId: user._id, isAdmin: user.isAdmin },
|
||||
process.env.JWT_SECRET,
|
||||
{
|
||||
expiresIn: "1h",
|
||||
}
|
||||
);
|
||||
|
||||
// Set the token as a cookie
|
||||
res.cookie("token", token, { httpOnly: true, secure: false, maxAge: 3600000 }); // 1 hour expiry
|
||||
res.cookie("token", token, {
|
||||
httpOnly: true,
|
||||
secure: false,
|
||||
maxAge: 3600000,
|
||||
}); // 1 hour expiry
|
||||
|
||||
return res.status(200).json({
|
||||
message: "Registered and logged in successfully",
|
||||
@@ -133,10 +173,20 @@ app.post("/api/login", (req, res, next) => {
|
||||
return res.status(500).json({ message: "Internal server error" });
|
||||
}
|
||||
// Generate a JWT token using the user's ID
|
||||
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: "1h" });
|
||||
const token = jwt.sign(
|
||||
{ userId: user._id, isAdmin: user.isAdmin },
|
||||
process.env.JWT_SECRET,
|
||||
{
|
||||
expiresIn: "1h",
|
||||
}
|
||||
);
|
||||
|
||||
// Set the token as a cookie
|
||||
res.cookie("token", token, { httpOnly: true, secure: false, maxAge: 3600000 }); // 1 hour expiry
|
||||
res.cookie("token", token, {
|
||||
httpOnly: true,
|
||||
secure: false,
|
||||
maxAge: 3600000,
|
||||
}); // 1 hour expiry
|
||||
return res.status(200).json({ message: "Login successful", user });
|
||||
});
|
||||
})(req, res, next);
|
||||
@@ -158,7 +208,9 @@ app.get("/auth/logout", function (req, res) {
|
||||
console.error("Error destroying session:", err);
|
||||
return res.status(500).json({ message: "Error logging out" });
|
||||
}
|
||||
res.status(200).json({ message: "Logout successful, session destroyed" });
|
||||
res
|
||||
.status(200)
|
||||
.json({ message: "Logout successful, session destroyed" });
|
||||
});
|
||||
} else {
|
||||
// If no session, simply respond with success
|
||||
@@ -175,12 +227,18 @@ app.post("/api/refresh", (req, res) => {
|
||||
const refreshToken = req.cookies.token;
|
||||
|
||||
if (!refreshToken) {
|
||||
return res.status(401).json({ message: "No refresh token, authorization denied" });
|
||||
return res
|
||||
.status(401)
|
||||
.json({ message: "No refresh token, authorization denied" });
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(refreshToken, process.env.JWT_SECRET);
|
||||
const newToken = jwt.sign({ userId: decoded.userId }, process.env.JWT_SECRET, { expiresIn: "1h" });
|
||||
const newToken = jwt.sign(
|
||||
{ userId: decoded.userId, isAdmin: decoded.isAdmin },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: "1h" }
|
||||
);
|
||||
|
||||
return res
|
||||
.cookie("token", newToken, { httpOnly: true, maxAge: 3600000 }) // Set new access token
|
||||
@@ -196,7 +254,6 @@ app.get("/api/auth-check", (req, res) => {
|
||||
const token = req.cookies.token; // Retrieve the httpOnly cookie
|
||||
|
||||
if (!token) {
|
||||
console.log("Tehehe");
|
||||
return res.status(401).json({ message: "Unauthorized" });
|
||||
}
|
||||
|
||||
@@ -211,7 +268,8 @@ app.get("/api/auth-check", (req, res) => {
|
||||
app.get("/api/me", async (req, res) => {
|
||||
try {
|
||||
const token = req.cookies.token; // ✅ Get token from request cookies
|
||||
if (!token) return res.status(401).json({ message: "Unauthorized - No Token" });
|
||||
if (!token)
|
||||
return res.status(401).json({ message: "Unauthorized - No Token" });
|
||||
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET); // ✅ Verify token
|
||||
|
||||
@@ -223,16 +281,14 @@ app.get("/api/me", async (req, res) => {
|
||||
userId: user._id,
|
||||
isAdmin: user.isAdmin, // ✅ Return actual `isAdmin` value
|
||||
exp: decoded.exp,
|
||||
iat: decoded.iat
|
||||
iat: decoded.iat,
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error("JWT Verification Error:", error.message);
|
||||
res.status(401).json({ message: "Invalid token" });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// User Profile Route
|
||||
app.get("/api/user/profile", async (req, res) => {
|
||||
try {
|
||||
@@ -251,9 +307,6 @@ app.patch("/api/courses/:courseId", async (req, res) => {
|
||||
const { courseId } = req.params;
|
||||
const { status } = req.body;
|
||||
|
||||
console.log("Request params:", req.params);
|
||||
console.log("Request body:", req.body);
|
||||
|
||||
if (!status) {
|
||||
console.error("Status is missing in the request body.");
|
||||
return res.status(400).json({ message: "Status is required" });
|
||||
@@ -287,10 +340,17 @@ app.get("*", (req, res) =>
|
||||
// Error Handling Middleware
|
||||
app.use((err, req, res, next) => {
|
||||
console.error("Error:", err.stack);
|
||||
res.status(err.status || 500).json({ error: err.message || "Internal Server Error" });
|
||||
res
|
||||
.status(err.status || 500)
|
||||
.json({ error: err.message || "Internal Server Error" });
|
||||
});
|
||||
|
||||
// Start Server
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server is running at http://localhost:8080`);
|
||||
});
|
||||
// Start Server
|
||||
if (require.main === module) {
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server is running at http://localhost:8080`);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = app;
|
||||
|
||||
Reference in New Issue
Block a user