A job portal has two very different kinds of users. Job seekers browse jobs, upload a resume and apply. Companies post jobs, hide or show them, review applicants and accept or reject applications. A job seeker should never be able to post a job, and a company should never be able to edit another company's listings.
That's role-based access control (RBAC). Here's how I structured it in the MERN Job Portal I built during my internship at NIQOX, and the checklist I now use to make it solid.
Two roles, two collections
Instead of one users collection with a role field, the app stores job seekers and companies in separate MongoDB collections, User and Company. The two have very different data (a company has a logo and its posted jobs; a job seeker has a resume and applications), and they register and log in through separate endpoints.
Applications link the two sides together:
const jobApplicationSchema = mongoose.Schema({
userId: { type: String, ref: 'User', required: true },
companyId: { type: mongoose.Types.ObjectId, ref: 'Company', required: true },
jobId: { type: mongoose.Types.ObjectId, ref: 'Job', required: true },
status: { type: String, default: 'Pending' },
date: { type: Number, required: true },
});
One auth middleware per role
Each role gets its own Express middleware. It verifies the JWT, loads the account from that role's collection, and attaches it to the request. Here is the company version (the job-seeker one is the same with User and req.userData):
import jwt from 'jsonwebtoken';
import Company from '../models/Company.js';
const companyAuthMiddleware = async (req, res, next) => {
try {
const token = req.headers.token;
if (!token) return res.status(401).json({ message: 'Unauthorized, login again' });
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const company = await Company.findById(decoded.id).select('-password');
if (!company) return res.status(404).json({ message: 'Company not found' });
req.companyData = company;
next();
} catch (error) {
return res.status(401).json({ message: 'Unauthorized, login again' });
}
};
Two details matter here. select('-password') keeps the password hash out of req, so it can never leak into a response by accident. And because a company token is looked up in the Company collection, a job seeker's token simply finds nothing there and gets rejected.
Protecting the routes
With the middleware in place, each route declares who may call it. Public routes get no middleware at all:
// public
router.get('/all-jobs', getAllJobs);
// companies only
router.post('/post-job', companyAuthMiddleware, postJob);
router.post('/change-visiblity', companyAuthMiddleware, changeJobVisibility);
router.post('/view-applications', companyAuthMiddleware, getCompanyJobApplicants);
// job seekers only
router.post('/apply-job', userAuthMiddleware, applyJob);
router.post('/upload-resume', userAuthMiddleware, upload.single('resume'), uploadResume);
Reading the route file now tells you the whole permission model at a glance, which is a big part of why I like this pattern.
Roles aren't enough: check ownership
The middleware answers "who are you?" It doesn't answer "is this yours?" A logged-in company passes companyAuthMiddleware, but that alone doesn't mean it may change every job. Each handler that modifies a record has to compare the record's owner with the caller. The job-visibility toggle does exactly that:
export const changeJobVisibility = async (req, res) => {
const { id } = req.body;
const companyId = req.companyData._id;
const job = await Job.findById(id);
if (!job) return res.status(404).json({ success: false, message: 'Job not found' });
if (job.companyId.toString() === companyId.toString()) {
job.visible = !job.visible;
}
await job.save();
return res.status(200).json({ success: true, message: 'Visibility changed' });
};
One refinement I'd make: when the caller isn't the owner, this still responds with success: true even though nothing changed. Returning an explicit error is clearer for the frontend and for anyone debugging.
The ownership check itself is also easy to forget on the third or fourth endpoint. A neat way to make it impossible to skip is to put the owner into the query, so a record that belongs to someone else is never found at all:
// update an application only if it belongs to the calling company
const application = await JobApplication.findOneAndUpdate(
{ _id: id, companyId: req.companyData._id },
{ status },
{ new: true }
);
if (!application) {
return res.status(404).json({ success: false, message: 'Application not found' });
}
My RBAC checklist for Express APIs
- Keep the JWT secret in an environment variable (
process.env.JWT_SECRET), never in the source code. Anyone with the secret can mint a valid token for any account. - Use the standard header.
Authorization: Bearer <token>works with every HTTP client and proxy, unlike a customtokenheader. - Put the role in the token and write one reusable guard instead of copying middleware per role:
const requireRole = (role) => (req, res, next) => { if (req.auth?.role !== role) { return res.status(403).json({ message: 'Forbidden' }); } next(); }; router.post('/post-job', authenticate, requireRole('company'), postJob); - Return the right status code.
401means "not logged in",403means "logged in, but not allowed". For other users' records,404avoids revealing that the record exists. - Check ownership on every write, preferably inside the database query as shown above.
- Validate values, not just presence. An application status should only ever be one of a few values, so make it an enum in the schema:
enum: ['Pending', 'Accepted', 'Rejected'].
Takeaway
Separate middleware per role gives you a permission model you can read straight from the route file, which is great for a two-sided app like a job portal. Pair it with ownership checks on every write and a properly managed secret, and you have access control that holds up.
The Job Portal project page has the live demo and source code.