Skip to content
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
cbefec9
chore(config): move db connection and passport strategy to config folder
codewkaushik404 Jan 29, 2026
78dbc24
fix(schema): update user schema to support correct login and registra…
codewkaushik404 Jan 29, 2026
f2e5883
refactor(auth): replace passport-local-mongoose with manual auth impl…
codewkaushik404 Jan 29, 2026
ae0295f
feat(validation): add zod validation for auth routes with IIT Bhilai …
codewkaushik404 Jan 29, 2026
57c4189
feat(auth): add manual JWT authentication middleware
codewkaushik404 Jan 30, 2026
61dfd89
refactor(schema): update certificate schema
codewkaushik404 Jan 30, 2026
29bc583
feat(certificates): implement controller logic to create certificate …
codewkaushik404 Jan 30, 2026
a8b4d8e
feat(certificates): implement controller logic to create certificate …
codewkaushik404 Jan 30, 2026
82d3b70
feat(validation): add Zod schema to validate certificate batch creati…
codewkaushik404 Jan 30, 2026
bde7d5e
Fix crashes and ensure intended behavior
codewkaushik404 Jan 30, 2026
ecc1ebd
refactor(auth): split schemas into separate files and fix local auth …
codewkaushik404 Feb 9, 2026
8126097
refactor(auth, models, middleware): refactor code to ensure robust l…
codewkaushik404 Feb 9, 2026
4e96a8e
Refactored authentication logic and fixed related bugs.
codewkaushik404 Feb 17, 2026
d3c0261
Refactored authentication logic and fixed related bugs. Switched to s…
codewkaushik404 Feb 17, 2026
2a31781
refactor few segments
codewkaushik404 Feb 17, 2026
53d7216
fix: api responses to handle frontend requirements
codewkaushik404 Feb 17, 2026
cdf07e2
refactor
codewkaushik404 Feb 17, 2026
c342d2b
fix: imports for models in controllers according to the updated struc…
codewkaushik404 Feb 17, 2026
649fb09
fix: imports for models in controllers according to the updated struc…
codewkaushik404 Feb 17, 2026
3fe6ed8
refactor
codewkaushik404 Feb 17, 2026
f521062
refactor: streamline authentication and registration processes, enhan…
codewkaushik404 Feb 18, 2026
2ef2e05
fix: incorrect imports for models in routes.
codewkaushik404 Feb 19, 2026
0f47b6a
refactor: improve auth flow
codewkaushik404 Feb 19, 2026
0bd1220
feat: add certificate page and update navbar config for role-based ac…
codewkaushik404 Feb 19, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions backend/db.js → backend/config/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ dotenv.config();
const connectDB = async () => {
try {
const ConnectDB = process.env.MONGODB_URI;
await mongoose.connect(ConnectDB, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
//Removing the options as they are no longer needed from mongoose6+
await mongoose.connect(ConnectDB);
console.log("MongoDB Connected");
} catch (error) {
console.error("MongoDB Connection Error:", error);
Expand Down
67 changes: 67 additions & 0 deletions backend/config/passportConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const isIITBhilaiEmail = require("../utils/isIITBhilaiEmail");
const User = require("../models/userSchema");

// Google OAuth Strategy
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: `${process.env.BACKEND_URL}/auth/google/verify`, // Update with your callback URL
},
async (accessToken, refreshToken, profile, done) => {
// Check if the user already exists in your database
if (!isIITBhilaiEmail(profile.emails[0].value)) {
console.log("Google OAuth blocked for: ", profile.emails[0].value);
return done(null, false, {
message: "Only @iitbhilai.ac.in emails are allowed.",
});
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
try {
const user = await User.findOne({ username: profile.emails[0].value });

if (user) {
// If user exists, return the user
return done(null, user);
}
// If user doesn't exist, create a new user in your database
const newUser = new User({
username: profile.emails[0].value,
role: "STUDENT",
strategy: "google",
personal_info: {
name: profile.displayName || "No Name",
email: profile.emails[0].value,
profilePic:
profile.photos && profile.photos.length > 0
? profile.photos[0].value
: "https://www.gravatar.com/avatar/?d=mp",
},
onboardingComplete: false,
});

await newUser.save();
return done(null, newUser);
} catch (error) {
return done(error);
}
},
),
);

passport.serializeUser((user, done) => {
done(null, user);
});

passport.deserializeUser(async (userKey, done) => {
try {
let user = await User.findById(userKey._id);
done(null, user);
} catch (err) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
done(err);
}
});

module.exports = passport;
152 changes: 152 additions & 0 deletions backend/controllers/certificateController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
const {
User,
PositionHolder,
Position,
OrganizationalUnit,
} = require("../models/schema");
const { CertificateBatch } = require("../models/certificateSchema");
const { validateBatchSchema, zodObjectId } = require("../utils/batchValidate");

async function createBatch(req, res) {
//console.log(req.user);
const id = req.user.id;
const user = await User.findById(id);
if (!user) {
return res.status(404).json({ messge: "Invalid data (User not found)" });
}

if (user.role && user.role !== "CLUB_COORDINATOR") {
return res.status(403).json({ message: "Not authorized to perform the task" });
}
Comment thread
codewkaushik404 marked this conversation as resolved.
Outdated

//to get user club
// positionHolders({user_id: id}) -> positions({_id: position_id}) -> organizationalUnit({_id: unit_id}) -> unit_id = "Club name"
const { title, unit_id, commonData, template_id, users } = req.body;
const validation = validateBatchSchema.safeParse({
title,
unit_id,
commonData,
template_id,
users,
});

if (!validation.success) {
let errors = validation.error.issues.map(issue => issue.message);
return res.status(400).json({ message: errors });
}

// Get coordinator's position and unit
const positionHolder = await PositionHolder.findOne({ user_id: id });
if (!positionHolder) {
return res.status(403).json({ message: "You are not part of any position in a unit" });
}

const position = await Position.findById(positionHolder.position_id);
console.log(position._id);
if (!position) {
return res.status(403).json({ message: "Your position is invalid" });
}
Comment thread
codewkaushik404 marked this conversation as resolved.
Outdated

const userUnitId = position.unit_id.toString();
if (userUnitId !== unit_id) {
return res
.status(403)
.json({
message:
"You are not authorized to initiate batches outside of your club",
});
}

//const clubId = unit_id;
// Ensure unit_id is a Club
const unitObj = await OrganizationalUnit.findById(unit_id);
if (!unitObj || unitObj.type !== "Club") {
return res
.status(403)
.json({ message: "Invalid Data: unit is not a Club" });
}
console.log(unitObj._id);

// Get council (parent unit) and ensure it's a Council
if (!unitObj.parent_unit_id) {
return res
.status(403)
.json({ message: "Invalid Data: club does not belong to a council" });
}
console.log(unitObj.parent_unit_id);

const councilObj = await OrganizationalUnit.findById(unitObj.parent_unit_id);
if (!councilObj || councilObj.type !== "Council") {
return res.status(403).json({ message: "Invalid Data: council not found" });
}

//const councilId = councilObj._id.toString();
const presidentOrgUnitId = councilObj.parent_unit_id;
const category = councilObj.category.toUpperCase();

// Resolve General Secretary and President for the council (server-side, tamper-proof)
const gensecObj = await User.findOne({ role: `GENSEC_${category}` });
console.log(gensecObj._id);

const presidentPosition = await Position.findOne({
unit_id: presidentOrgUnitId,
title: /president/i,
});
if (!presidentPosition) {
return res
.status(500)
.json({ message: "President position not found for council" });
}
console.log(presidentPosition._id);

const presidentHolder = await PositionHolder.findOne({
position_id: presidentPosition._id,
});
const presidentId = presidentHolder.user_id.toString();
console.log(presidentId);
const presidentObj = await User.findById(presidentId);

console.log(presidentObj._id);
if (!gensecObj || !presidentObj) {
return res.status(500).json({ message: "Approvers not found" });
}
Comment thread
codewkaushik404 marked this conversation as resolved.
Outdated

const approverIds = [gensecObj._id.toString(), presidentId];

const userChecks = await Promise.all(
users.map(async (uid) => {
const validation = zodObjectId.safeParse(uid);
if (!validation) {
return { uid, ok: false, reason: "Invalid ID" };
}

const userObj = await User.findById(uid);
if (!userObj) return { uid, ok: false, reason: "User not found" };

return { uid, ok: true };
}),
);
Comment thread
codewkaushik404 marked this conversation as resolved.
Outdated

const invalidData = userChecks.filter((c) => !c.ok);
if (invalidData.length > 0) {
return res
.status(400)
.json({ message: "Invalid user data sent", details: invalidData });
}

const newBatch = await CertificateBatch.create({
title,
unit_id,
commonData,
templateId: template_id,
initiatedBy: id,
approverIds,
users,
});

res.json({ message: "New Batch created successfully", details: newBatch });
}
Comment thread
codewkaushik404 marked this conversation as resolved.

module.exports = {
createBatch,
};
15 changes: 9 additions & 6 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
const express = require("express");
require("dotenv").config();
// eslint-disable-next-line node/no-unpublished-require
const { connectDB } = require("./config/db.js");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const routes_auth = require("./routes/auth");
const routes_general = require("./routes/route");
const session = require("express-session");
const bodyParser = require("body-parser");
const { connectDB } = require("./db");
const myPassport = require("./models/passportConfig"); // Adjust the path accordingly
const myPassport = require("./config/passportConfig.js"); // Adjust the path accordingly
const onboardingRoutes = require("./routes/onboarding.js");
const profileRoutes = require("./routes/profile.js");
const feedbackRoutes = require("./routes/feedbackRoutes.js");
Expand All @@ -18,20 +18,22 @@ const positionsRoutes = require("./routes/positionRoutes.js");
const organizationalUnitRoutes = require("./routes/orgUnit.js");
const announcementRoutes = require("./routes/announcements.js");
const dashboardRoutes = require("./routes/dashboard.js");

const analyticsRoutes = require("./routes/analytics.js");
const certificateRoutes = require("./routes/certificateRoutes.js");
const app = express();

if (process.env.NODE_ENV === "production") {
app.set("trust proxy", 1);
}

app.use(cors({ origin: process.env.FRONTEND_URL, credentials: true }));

// Connect to MongoDB
connectDB();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

connectDB() silently swallows connection failures.

Per the snippet in config/db.js, a failed connection only logs the error but doesn't throw or exit. The server will continue to run without a database connection, leading to 500 errors on every request. Consider calling process.exit(1) in the catch block or re-throwing the error.

🤖 Prompt for AI Agents
In `@backend/index.js` around lines 29 - 31, The current connectDB() call silently
continues on failures; update either the connectDB implementation in
config/db.js to re-throw the caught error or call process.exit(1) inside its
catch block, or change the startup flow in backend/index.js to await connectDB()
and wrap it in a try/catch that logs the error and exits (e.g., catch(err) {
processLogger.error(..., err); process.exit(1); }). Ensure you reference the
connectDB function (connectDB and the connectDB() call) and the catch block in
config/db.js so the process fails fast when DB connection fails.


app.use(bodyParser.json());
app.use(cookieParser());

//Replaced bodyParser with express.json() - the new standard
app.use(express.json());

app.use(
session({
Expand Down Expand Up @@ -67,6 +69,7 @@ app.use("/api/announcements", announcementRoutes);
app.use("/api/dashboard", dashboardRoutes);
app.use("/api/announcements", announcementRoutes);
app.use("/api/analytics", analyticsRoutes);
app.use("/api/certificate-batches", certificateRoutes);

// Start the server
app.listen(process.env.PORT || 8000, () => {
Expand Down
79 changes: 78 additions & 1 deletion backend/middlewares/isAuthenticated.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,84 @@
const jwt = require("jsonwebtoken");

//Passport based middleware to check whether the req are coming from authenticated users
function isAuthenticated(req, res, next) {
if (req.isAuthenticated && req.isAuthenticated()) {
return next();
}
return res.status(401).json({ message: "Unauthorized: Please login first" });
}
module.exports = isAuthenticated;

//Token based middleware to check whether the req are coming from authenticated users or not

function jwtIsAuthenticated(req, res, next) {
let token;
/**
* const headerData = req.headers.authorization;
if (!headerData || !headerData.startsWith("Bearer ")) {
return res.status(401).json({ message: "User not authenticated " });
}

token = headerData.split(" ")[1];
*/

token = req.cookies.token;
if(!token){
return res.status(401).json({message: "User not authenticated"});
}

try {
const userData = jwt.verify(token, process.env.JWT_SECRET_TOKEN);
req.user = userData;
//console.log(userData);
next();
} catch (err) {
res.status(401).json({ message: "Invalid or expired token sent" });
}
}

module.exports = {
isAuthenticated,
jwtIsAuthenticated,
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/*

const presidentObj = await User.findById(presidentId);

console.log(presidentObj._id);
if(!gensecObj || !presidentObj) {
return res.status(500).json({ message: "Approvers not found" });
}

const approverIds = [gensecObj._id.toString(), presidentId];

const userChecks = await Promise.all(
users.map(async (uid) => {
const validation = zodObjectId.safeParse(uid);
if(!validation){
return {uid, ok: false, reason:"Invalid ID"};
}

const userObj = await User.findById(uid);
if(!userObj) return {uid, ok:false, reason: "User not found"};

return {uid, ok: true};
})
);

const invalidData = userChecks.filter((c) => !c.ok);
if(invalidData.length > 0){
return res.status(400).json({message: "Invalid user data sent", details: invalidData});
}

const newBatch = await CertificateBatch.create({
title,
unit_id,
commonData,
template_id,
initiatedBy: id,
approverIds,
users
});

*/
Loading