Skip to main content

Command Palette

Search for a command to run...

Exploring Backend Development: Implementing Access Control with Node.js

Published
•3 min read•View as Markdown
Exploring Backend Development: Implementing Access Control with Node.js

As a frontend developer stepping into the world of backend development, I recently tackled an interesting problem that significantly boosted my confidence and skills. My goal was to create a role based access control system (RBAC) using Node.js, managing different levels of authorization such as user and admin. This project not only tested my technical abilities but also reinforced my passion for becoming a full-stack developer.

The Problem

Access control is a critical aspect of any application, ensuring that users have appropriate permissions and protecting sensitive data from unauthorized access. My goal was to implement a system where users could have different roles, each with distinct permissions. This required a deep understanding of access control and how to efficiently integrate it into a Node.js application.

After conducting several researches and reading blog posts on RBAC, I dived into practice and created a mini project on this.

A Sneak Peek into My Middleware: Authorization and Access Control

Here's a glimpse of the middleware functions I developed for handling authorization and access control.

const jwt = require("jsonwebtoken");
const { User } = require("../helpers/db");
const Role = require("../helpers/role");
const JWT_SECRET = process.env.JWT_SECRET;

const authMiddleware = async (req, res, next) => {
  const authHeader = req.headers["authorization"];
  if (!authHeader) {
    return res.status(401).send("Authorization header is missing");
  }

  const token = authHeader.split(" ")[1];

  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    const user = await User.findById(decoded.id);
    if (!user) {
      return res.status(401).json({ message: "Invalid token" });
    }
    req.user = user;
    next();
  } catch (err) {
    return res.status(401).json({ message: "Invalid token" });
  }
};

const adminCheckMiddleware = (req, res, next) => {
  if (req.user && req.user.role === Role.Admin) {
    next();
  } else {
    res.status(403).json({ message: "Access denied for this service!" });
  }
};

module.exports = { authMiddleware, adminCheckMiddleware };

Routes - Using the middleware and granting access based on user roles

To manage different levels of authorization, I used the middleware functions to check the user's role before granting access to specific routes.

const express = require("express");
const router = express.Router();
const {
  login,
  register,
  getAll,
  getCurrent,
  getById,
  update,
  deleteUser,
  forgetPassword,
  resetPassword,
} = require("../controllers/user");
const { authMiddleware, adminCheckMiddleware } = require("../middlewares");

router.post("/register", register);
router.post("/login", login);
router.patch("/:id", authMiddleware, update);
router.get("/current", authMiddleware, getCurrent);
router.get("/:id", authMiddleware, getById);
router.get("/", authMiddleware, adminCheckMiddleware, getAll);
router.delete("/:id", authMiddleware, adminCheckMiddleware, deleteUser);

module.exports = router;

The Journey Ahead

This project was a significant milestone in my journey to becoming a full-stack developer. The HNG Internship presents an incredible opportunity to further hone my backend skills, particularly in a collaborative and fast-paced environment. Last year, I had the privilege of being a frontend finalist during the HNGX Internship, and I am determined to push beyond my limits to excel in the backend track this year.

HNG Internship is renowned for its comprehensive training and mentorship, making it the perfect platform to transition from a frontend developer to a full-stack developer. I am eager to learn, grow, and contribute to meaningful projects alongside talented peers and mentors.

To learn more about the HNG Internship and how it can accelerate your tech career, check out HNG Internship , HNG Premium and Hire HNG Talents.